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: PepperMediaDeviceManager* PepperPlatformVideoCapture::GetMediaDeviceManager() { RenderFrameImpl* const render_frame = RenderFrameImpl::FromRoutingID(render_frame_id_); return render_frame ? PepperMediaDeviceManager::GetForRenderFrame(render_frame) : NULL; } Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr Its lifetime is scoped to the RenderFrame, and it might go away before the hosts that refer to it. BUG=423030 Review URL: https://codereview.chromium.org/653243003 Cr-Commit-Position: refs/heads/master@{#299897} CWE ID: CWE-399 Target: 1 Example 2: Code: static void b43_dma_tx_suspend_ring(struct b43_dmaring *ring) { B43_WARN_ON(!ring->tx); ring->ops->tx_suspend(ring); } Commit Message: b43: allocate receive buffers big enough for max frame len + offset Otherwise, skb_put inside of dma_rx can fail... https://bugzilla.kernel.org/show_bug.cgi?id=32042 Signed-off-by: John W. Linville <[email protected]> Acked-by: Larry Finger <[email protected]> Cc: [email protected] 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: test_size(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type, int bdlo, int PNG_CONST bdhi) { /* Run the tests on each combination. * * NOTE: on my 32 bit x86 each of the following blocks takes * a total of 3.5 seconds if done across every combo of bit depth * width and height. This is a waste of time in practice, hence the * hinc and winc stuff: */ static PNG_CONST png_byte hinc[] = {1, 3, 11, 1, 5}; static PNG_CONST png_byte winc[] = {1, 9, 5, 7, 1}; for (; bdlo <= bdhi; ++bdlo) { png_uint_32 h, w; for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo]) { /* First test all the 'size' images against the sequential * reader using libpng to deinterlace (where required.) This * validates the write side of libpng. There are four possibilities * to validate. */ standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_NONE, w, h, 0), 0/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_NONE, w, h, 1), 0/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; # ifdef PNG_WRITE_INTERLACING_SUPPORTED standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 0), 0/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 1), 0/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; # endif /* Now validate the interlaced read side - do_interlace true, * in the progressive case this does actually make a difference * to the code used in the non-interlaced case too. */ standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_NONE, w, h, 0), 1/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; # ifdef PNG_WRITE_INTERLACING_SUPPORTED standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 0), 1/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; # endif } } return 1; /* keep going */ } 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 SystemClipboard::WriteImage(Image* image, const KURL& url, const String& title) { DCHECK(image); PaintImage paint_image = image->PaintImageForCurrentFrame(); SkBitmap bitmap; if (sk_sp<SkImage> sk_image = paint_image.GetSkImage()) sk_image->asLegacyBitmap(&bitmap); if (bitmap.isNull()) return; if (!bitmap.getPixels()) return; clipboard_->WriteImage(mojom::ClipboardBuffer::kStandard, bitmap); if (url.IsValid() && !url.IsEmpty()) { #if !defined(OS_MACOSX) clipboard_->WriteBookmark(mojom::ClipboardBuffer::kStandard, url.GetString(), NonNullString(title)); #endif clipboard_->WriteHtml(mojom::ClipboardBuffer::kStandard, URLToImageMarkup(url, title), KURL()); } clipboard_->CommitWrite(mojom::ClipboardBuffer::kStandard); } Commit Message: System Clipboard: Remove extraneous check for bitmap.getPixels() Bug 369621 originally led to this check being introduced via https://codereview.chromium.org/289573002/patch/40001/50002, but after https://crrev.com/c/1345809, I'm not sure that it's still necessary. This change succeeds when tested against the "minimized test case" provided in crbug.com/369621 's description, but I'm unsure how to make the minimized test case fail, so this doesn't prove that the change would succeed against the fuzzer's test case (which originally filed the bug). As I'm unable to view the relevant fuzzer test case, (see crbug.com/918705), I don't know exactly what may have caused the fuzzer to fail. Therefore, I've added a CHECK for the time being, so that we will be notified in canary if my assumption was incorrect. Bug: 369621 Change-Id: Ie9b47a4b38ba1ed47624de776015728e541d27f7 Reviewed-on: https://chromium-review.googlesource.com/c/1393436 Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Kai Ninomiya <[email protected]> Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Victor Costan <[email protected]> Cr-Commit-Position: refs/heads/master@{#619591} CWE ID: CWE-119 Target: 1 Example 2: Code: bool X86_lockrep(MCInst *MI, SStream *O) { unsigned int opcode; bool res = false; switch(MI->x86_prefix[0]) { default: break; case 0xf0: #ifndef CAPSTONE_DIET SStream_concat(O, "lock|"); #endif break; case 0xf2: // repne opcode = MCInst_getOpcode(MI); #ifndef CAPSTONE_DIET // only care about memonic in standard (non-diet) mode if (valid_repne(MI->csh, opcode)) { SStream_concat(O, "repne|"); add_cx(MI); } else { MI->x86_prefix[0] = 0; #ifndef CAPSTONE_X86_REDUCE if (opcode == X86_MULPDrr) { MCInst_setOpcode(MI, X86_MULSDrr); SStream_concat(O, "mulsd\t"); res = true; } #endif } #else // diet mode -> only patch opcode in special cases if (!valid_repne(MI->csh, opcode)) { MI->x86_prefix[0] = 0; } #ifndef CAPSTONE_X86_REDUCE if (opcode == X86_MULPDrr) { MCInst_setOpcode(MI, X86_MULSDrr); } #endif #endif break; case 0xf3: opcode = MCInst_getOpcode(MI); #ifndef CAPSTONE_DIET // only care about memonic in standard (non-diet) mode if (valid_rep(MI->csh, opcode)) { SStream_concat(O, "rep|"); add_cx(MI); } else if (valid_repe(MI->csh, opcode)) { SStream_concat(O, "repe|"); add_cx(MI); } else { MI->x86_prefix[0] = 0; #ifndef CAPSTONE_X86_REDUCE if (opcode == X86_MULPDrr) { MCInst_setOpcode(MI, X86_MULSSrr); SStream_concat(O, "mulss\t"); res = true; } #endif } #else // diet mode -> only patch opcode in special cases if (!valid_rep(MI->csh, opcode) && !valid_repe(MI->csh, opcode)) { MI->x86_prefix[0] = 0; } #ifndef CAPSTONE_X86_REDUCE if (opcode == X86_MULPDrr) { MCInst_setOpcode(MI, X86_MULSSrr); } #endif #endif break; } if (MI->csh->detail) memcpy(MI->flat_insn->detail->x86.prefix, MI->x86_prefix, ARR_SIZE(MI->x86_prefix)); return res; } Commit Message: x86: fast path checking for X86_insn_reg_intel() 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 FrameFetchContext::AddResourceTiming(const ResourceTimingInfo& info) { if (!document_) return; LocalFrame* frame = document_->GetFrame(); if (!frame) return; if (info.IsMainResource()) { DCHECK(frame->Owner()); frame->Owner()->AddResourceTiming(info); frame->DidSendResourceTimingInfoToParent(); return; } DOMWindowPerformance::performance(*document_->domWindow()) ->GenerateAndAddResourceTiming(info); } Commit Message: Do not forward resource timing to parent frame after back-forward navigation LocalFrame has |should_send_resource_timing_info_to_parent_| flag not to send timing info to parent except for the first navigation. This flag is cleared when the first timing is sent to parent, however this does not happen if iframe's first navigation was by back-forward navigation. For such iframes, we shouldn't send timings to parent at all. Bug: 876822 Change-Id: I128b51a82ef278c439548afc8283ae63abdef5c5 Reviewed-on: https://chromium-review.googlesource.com/1186215 Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Kunihiko Sakamoto <[email protected]> Cr-Commit-Position: refs/heads/master@{#585736} 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 MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { DDSColors colors; ssize_t j, y; MagickSizeType alpha_bits; PixelPacket *q; register ssize_t i, x; unsigned char a0, a1; size_t alpha, bits, code, alpha_code; unsigned short c0, c1; for (y = 0; y < (ssize_t) dds_info->height; y += 4) { for (x = 0; x < (ssize_t) dds_info->width; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x), Min(4, dds_info->height - y),exception); if (q == (PixelPacket *) NULL) return MagickFalse; /* Read alpha values (8 bytes) */ a0 = (unsigned char) ReadBlobByte(image); a1 = (unsigned char) ReadBlobByte(image); alpha_bits = (MagickSizeType)ReadBlobLSBLong(image); alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32); /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickTrue); /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height) { code = (bits >> ((4*j+i)*2)) & 0x3; SetPixelRed(q,ScaleCharToQuantum(colors.r[code])); SetPixelGreen(q,ScaleCharToQuantum(colors.g[code])); SetPixelBlue(q,ScaleCharToQuantum(colors.b[code])); /* Extract alpha value */ alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7; if (alpha_code == 0) alpha = a0; else if (alpha_code == 1) alpha = a1; else if (a0 > a1) alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7; else if (alpha_code == 6) alpha = 0; else if (alpha_code == 7) alpha = 255; else alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) alpha)); q++; } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } } SkipDXTMipmaps(image, dds_info, 16); return MagickTrue; } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20 Target: 1 Example 2: Code: void PluginObserver::OnMissingPluginStatus(int status) { #if defined(OS_WIN) if (status == webkit::npapi::default_plugin::MISSING_PLUGIN_AVAILABLE) { tab_contents_->AddInfoBar( new PluginInstallerInfoBarDelegate(tab_contents())); return; } DCHECK_EQ(webkit::npapi::default_plugin::MISSING_PLUGIN_USER_STARTED_DOWNLOAD, status); for (size_t i = 0; i < tab_contents_->infobar_count(); ++i) { InfoBarDelegate* delegate = tab_contents_->GetInfoBarDelegateAt(i); if (delegate->AsPluginInstallerInfoBarDelegate() != NULL) { tab_contents_->RemoveInfoBar(delegate); return; } } #endif } 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: 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 SVGDocumentExtensions::addPendingResource(const AtomicString& id, Element* element) { ASSERT(element); ASSERT(element->inDocument()); if (id.isEmpty()) return; HashMap<AtomicString, OwnPtr<SVGPendingElements> >::AddResult result = m_pendingResources.add(id, nullptr); if (result.isNewEntry) result.storedValue->value = adoptPtr(new SVGPendingElements); result.storedValue->value->add(element); element->setHasPendingResources(); } Commit Message: SVG: Moving animating <svg> to other iframe should not crash. Moving SVGSVGElement with its SMILTimeContainer already started caused crash before this patch. |SVGDocumentExtentions::startAnimations()| calls begin() against all SMILTimeContainers in the document, but the SMILTimeContainer for <svg> moved from other document may be already started. BUG=369860 Review URL: https://codereview.chromium.org/290353002 git-svn-id: svn://svn.chromium.org/blink/trunk@174338 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m) { struct session_state *state = ssh->state; u_char *p; size_t slen, rlen; int r, ssh1cipher; if (!compat20) { ssh1cipher = cipher_ctx_get_number(state->receive_context); slen = cipher_get_keyiv_len(state->send_context); rlen = cipher_get_keyiv_len(state->receive_context); if ((r = sshbuf_put_u32(m, state->remote_protocol_flags)) != 0 || (r = sshbuf_put_u32(m, ssh1cipher)) != 0 || (r = sshbuf_put_string(m, state->ssh1_key, state->ssh1_keylen)) != 0 || (r = sshbuf_put_u32(m, slen)) != 0 || (r = sshbuf_reserve(m, slen, &p)) != 0 || (r = cipher_get_keyiv(state->send_context, p, slen)) != 0 || (r = sshbuf_put_u32(m, rlen)) != 0 || (r = sshbuf_reserve(m, rlen, &p)) != 0 || (r = cipher_get_keyiv(state->receive_context, p, rlen)) != 0) return r; } else { if ((r = kex_to_blob(m, ssh->kex)) != 0 || (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 || (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 || (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 || (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 || (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 || (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 || (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 || (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 || (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 || (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 || (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 || (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0) return r; } slen = cipher_get_keycontext(state->send_context, NULL); rlen = cipher_get_keycontext(state->receive_context, NULL); if ((r = sshbuf_put_u32(m, slen)) != 0 || (r = sshbuf_reserve(m, slen, &p)) != 0) return r; if (cipher_get_keycontext(state->send_context, p) != (int)slen) return SSH_ERR_INTERNAL_ERROR; if ((r = sshbuf_put_u32(m, rlen)) != 0 || (r = sshbuf_reserve(m, rlen, &p)) != 0) return r; if (cipher_get_keycontext(state->receive_context, p) != (int)rlen) return SSH_ERR_INTERNAL_ERROR; if ((r = ssh_packet_get_compress_state(m, ssh)) != 0 || (r = sshbuf_put_stringb(m, state->input)) != 0 || (r = sshbuf_put_stringb(m, state->output)) != 0) return r; return 0; } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119 Target: 1 Example 2: Code: static int ktime2ts(ktime_t kt, struct timespec *ts) { if (kt.tv64) { *ts = ktime_to_timespec(kt); return 1; } else { return 0; } } Commit Message: Fix order of arguments to compat_put_time[spec|val] Commit 644595f89620 ("compat: Handle COMPAT_USE_64BIT_TIME in net/socket.c") introduced a bug where the helper functions to take either a 64-bit or compat time[spec|val] got the arguments in the wrong order, passing the kernel stack pointer off as a user pointer (and vice versa). Because of the user address range check, that in turn then causes an EFAULT due to the user pointer range checking failing for the kernel address. Incorrectly resuling in a failed system call for 32-bit processes with a 64-bit kernel. On odder architectures like HP-PA (with separate user/kernel address spaces), it can be used read kernel memory. Signed-off-by: Mikulas Patocka <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[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: static int packet_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { int len; int val; struct sock *sk = sock->sk; struct packet_sock *po = pkt_sk(sk); void *data; struct tpacket_stats st; if (level != SOL_PACKET) return -ENOPROTOOPT; if (get_user(len, optlen)) return -EFAULT; if (len < 0) return -EINVAL; switch (optname) { case PACKET_STATISTICS: if (len > sizeof(struct tpacket_stats)) len = sizeof(struct tpacket_stats); spin_lock_bh(&sk->sk_receive_queue.lock); st = po->stats; memset(&po->stats, 0, sizeof(st)); spin_unlock_bh(&sk->sk_receive_queue.lock); st.tp_packets += st.tp_drops; data = &st; break; case PACKET_AUXDATA: if (len > sizeof(int)) len = sizeof(int); val = po->auxdata; data = &val; break; case PACKET_ORIGDEV: if (len > sizeof(int)) len = sizeof(int); val = po->origdev; data = &val; break; case PACKET_VNET_HDR: if (len > sizeof(int)) len = sizeof(int); val = po->has_vnet_hdr; data = &val; break; case PACKET_VERSION: if (len > sizeof(int)) len = sizeof(int); val = po->tp_version; data = &val; break; case PACKET_HDRLEN: if (len > sizeof(int)) len = sizeof(int); if (copy_from_user(&val, optval, len)) return -EFAULT; switch (val) { case TPACKET_V1: val = sizeof(struct tpacket_hdr); break; case TPACKET_V2: val = sizeof(struct tpacket2_hdr); break; default: return -EINVAL; } data = &val; break; case PACKET_RESERVE: if (len > sizeof(unsigned int)) len = sizeof(unsigned int); val = po->tp_reserve; data = &val; break; case PACKET_LOSS: if (len > sizeof(unsigned int)) len = sizeof(unsigned int); val = po->tp_loss; data = &val; break; case PACKET_TIMESTAMP: if (len > sizeof(int)) len = sizeof(int); val = po->tp_tstamp; data = &val; break; default: return -ENOPROTOOPT; } if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, data, len)) return -EFAULT; return 0; } Commit Message: af_packet: prevent information leak In 2.6.27, commit 393e52e33c6c2 (packet: deliver VLAN TCI to userspace) added a small information leak. Add padding field and make sure its zeroed before copy to user. Signed-off-by: Eric Dumazet <[email protected]> CC: Patrick McHardy <[email protected]> Signed-off-by: David S. Miller <[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 ip6_fragment(struct net *net, struct sock *sk, struct sk_buff *skb, int (*output)(struct net *, struct sock *, struct sk_buff *)) { struct sk_buff *frag; struct rt6_info *rt = (struct rt6_info *)skb_dst(skb); struct ipv6_pinfo *np = skb->sk && !dev_recursion_level() ? inet6_sk(skb->sk) : NULL; struct ipv6hdr *tmp_hdr; struct frag_hdr *fh; unsigned int mtu, hlen, left, len; int hroom, troom; __be32 frag_id; int ptr, offset = 0, err = 0; u8 *prevhdr, nexthdr = 0; hlen = ip6_find_1stfragopt(skb, &prevhdr); nexthdr = *prevhdr; mtu = ip6_skb_dst_mtu(skb); /* We must not fragment if the socket is set to force MTU discovery * or if the skb it not generated by a local socket. */ if (unlikely(!skb->ignore_df && skb->len > mtu)) goto fail_toobig; if (IP6CB(skb)->frag_max_size) { if (IP6CB(skb)->frag_max_size > mtu) goto fail_toobig; /* don't send fragments larger than what we received */ mtu = IP6CB(skb)->frag_max_size; if (mtu < IPV6_MIN_MTU) mtu = IPV6_MIN_MTU; } if (np && np->frag_size < mtu) { if (np->frag_size) mtu = np->frag_size; } if (mtu < hlen + sizeof(struct frag_hdr) + 8) goto fail_toobig; mtu -= hlen + sizeof(struct frag_hdr); frag_id = ipv6_select_ident(net, &ipv6_hdr(skb)->daddr, &ipv6_hdr(skb)->saddr); if (skb->ip_summed == CHECKSUM_PARTIAL && (err = skb_checksum_help(skb))) goto fail; hroom = LL_RESERVED_SPACE(rt->dst.dev); if (skb_has_frag_list(skb)) { unsigned int first_len = skb_pagelen(skb); struct sk_buff *frag2; if (first_len - hlen > mtu || ((first_len - hlen) & 7) || skb_cloned(skb) || skb_headroom(skb) < (hroom + sizeof(struct frag_hdr))) goto slow_path; skb_walk_frags(skb, frag) { /* Correct geometry. */ if (frag->len > mtu || ((frag->len & 7) && frag->next) || skb_headroom(frag) < (hlen + hroom + sizeof(struct frag_hdr))) goto slow_path_clean; /* Partially cloned skb? */ if (skb_shared(frag)) goto slow_path_clean; BUG_ON(frag->sk); if (skb->sk) { frag->sk = skb->sk; frag->destructor = sock_wfree; } skb->truesize -= frag->truesize; } err = 0; offset = 0; /* BUILD HEADER */ *prevhdr = NEXTHDR_FRAGMENT; tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC); if (!tmp_hdr) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); err = -ENOMEM; goto fail; } frag = skb_shinfo(skb)->frag_list; skb_frag_list_init(skb); __skb_pull(skb, hlen); fh = (struct frag_hdr *)__skb_push(skb, sizeof(struct frag_hdr)); __skb_push(skb, hlen); skb_reset_network_header(skb); memcpy(skb_network_header(skb), tmp_hdr, hlen); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(IP6_MF); fh->identification = frag_id; first_len = skb_pagelen(skb); skb->data_len = first_len - skb_headlen(skb); skb->len = first_len; ipv6_hdr(skb)->payload_len = htons(first_len - sizeof(struct ipv6hdr)); dst_hold(&rt->dst); for (;;) { /* Prepare header of the next frame, * before previous one went down. */ if (frag) { frag->ip_summed = CHECKSUM_NONE; skb_reset_transport_header(frag); fh = (struct frag_hdr *)__skb_push(frag, sizeof(struct frag_hdr)); __skb_push(frag, hlen); skb_reset_network_header(frag); memcpy(skb_network_header(frag), tmp_hdr, hlen); offset += skb->len - hlen - sizeof(struct frag_hdr); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(offset); if (frag->next) fh->frag_off |= htons(IP6_MF); fh->identification = frag_id; ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ip6_copy_metadata(frag, skb); } err = output(net, sk, skb); if (!err) IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGCREATES); if (err || !frag) break; skb = frag; frag = skb->next; skb->next = NULL; } kfree(tmp_hdr); if (err == 0) { IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGOKS); ip6_rt_put(rt); return 0; } kfree_skb_list(frag); IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGFAILS); ip6_rt_put(rt); return err; slow_path_clean: skb_walk_frags(skb, frag2) { if (frag2 == frag) break; frag2->sk = NULL; frag2->destructor = NULL; skb->truesize += frag2->truesize; } } slow_path: left = skb->len - hlen; /* Space per frame */ ptr = hlen; /* Where to start from */ /* * Fragment the datagram. */ troom = rt->dst.dev->needed_tailroom; /* * Keep copying data until we run out. */ while (left > 0) { u8 *fragnexthdr_offset; len = left; /* IF: it doesn't fit, use 'mtu' - the data space left */ if (len > mtu) len = mtu; /* IF: we are not sending up to and including the packet end then align the next start on an eight byte boundary */ if (len < left) { len &= ~7; } /* Allocate buffer */ frag = alloc_skb(len + hlen + sizeof(struct frag_hdr) + hroom + troom, GFP_ATOMIC); if (!frag) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); err = -ENOMEM; goto fail; } /* * Set up data on packet */ ip6_copy_metadata(frag, skb); skb_reserve(frag, hroom); skb_put(frag, len + hlen + sizeof(struct frag_hdr)); skb_reset_network_header(frag); fh = (struct frag_hdr *)(skb_network_header(frag) + hlen); frag->transport_header = (frag->network_header + hlen + sizeof(struct frag_hdr)); /* * Charge the memory for the fragment to any owner * it might possess */ if (skb->sk) skb_set_owner_w(frag, skb->sk); /* * Copy the packet header into the new buffer. */ skb_copy_from_linear_data(skb, skb_network_header(frag), hlen); fragnexthdr_offset = skb_network_header(frag); fragnexthdr_offset += prevhdr - skb_network_header(skb); *fragnexthdr_offset = NEXTHDR_FRAGMENT; /* * Build fragment header. */ fh->nexthdr = nexthdr; fh->reserved = 0; fh->identification = frag_id; /* * Copy a block of the IP datagram. */ BUG_ON(skb_copy_bits(skb, ptr, skb_transport_header(frag), len)); left -= len; fh->frag_off = htons(offset); if (left > 0) fh->frag_off |= htons(IP6_MF); ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ptr += len; offset += len; /* * Put this fragment into the sending queue. */ err = output(net, sk, frag); if (err) goto fail; IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGCREATES); } IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGOKS); consume_skb(skb); return err; fail_toobig: if (skb->sk && dst_allfrag(skb_dst(skb))) sk_nocaps_add(skb->sk, NETIF_F_GSO_MASK); skb->dev = skb_dst(skb)->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); err = -EMSGSIZE; fail: IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return err; } Commit Message: ipv6: Prevent overrun when parsing v6 header options The KASAN warning repoted below was discovered with a syzkaller program. The reproducer is basically: int s = socket(AF_INET6, SOCK_RAW, NEXTHDR_HOP); send(s, &one_byte_of_data, 1, MSG_MORE); send(s, &more_than_mtu_bytes_data, 2000, 0); The socket() call sets the nexthdr field of the v6 header to NEXTHDR_HOP, the first send call primes the payload with a non zero byte of data, and the second send call triggers the fragmentation path. The fragmentation code tries to parse the header options in order to figure out where to insert the fragment option. Since nexthdr points to an invalid option, the calculation of the size of the network header can made to be much larger than the linear section of the skb and data is read outside of it. This fix makes ip6_find_1stfrag return an error if it detects running out-of-bounds. [ 42.361487] ================================================================== [ 42.364412] BUG: KASAN: slab-out-of-bounds in ip6_fragment+0x11c8/0x3730 [ 42.365471] Read of size 840 at addr ffff88000969e798 by task ip6_fragment-oo/3789 [ 42.366469] [ 42.366696] CPU: 1 PID: 3789 Comm: ip6_fragment-oo Not tainted 4.11.0+ #41 [ 42.367628] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.1-1ubuntu1 04/01/2014 [ 42.368824] Call Trace: [ 42.369183] dump_stack+0xb3/0x10b [ 42.369664] print_address_description+0x73/0x290 [ 42.370325] kasan_report+0x252/0x370 [ 42.370839] ? ip6_fragment+0x11c8/0x3730 [ 42.371396] check_memory_region+0x13c/0x1a0 [ 42.371978] memcpy+0x23/0x50 [ 42.372395] ip6_fragment+0x11c8/0x3730 [ 42.372920] ? nf_ct_expect_unregister_notifier+0x110/0x110 [ 42.373681] ? ip6_copy_metadata+0x7f0/0x7f0 [ 42.374263] ? ip6_forward+0x2e30/0x2e30 [ 42.374803] ip6_finish_output+0x584/0x990 [ 42.375350] ip6_output+0x1b7/0x690 [ 42.375836] ? ip6_finish_output+0x990/0x990 [ 42.376411] ? ip6_fragment+0x3730/0x3730 [ 42.376968] ip6_local_out+0x95/0x160 [ 42.377471] ip6_send_skb+0xa1/0x330 [ 42.377969] ip6_push_pending_frames+0xb3/0xe0 [ 42.378589] rawv6_sendmsg+0x2051/0x2db0 [ 42.379129] ? rawv6_bind+0x8b0/0x8b0 [ 42.379633] ? _copy_from_user+0x84/0xe0 [ 42.380193] ? debug_check_no_locks_freed+0x290/0x290 [ 42.380878] ? ___sys_sendmsg+0x162/0x930 [ 42.381427] ? rcu_read_lock_sched_held+0xa3/0x120 [ 42.382074] ? sock_has_perm+0x1f6/0x290 [ 42.382614] ? ___sys_sendmsg+0x167/0x930 [ 42.383173] ? lock_downgrade+0x660/0x660 [ 42.383727] inet_sendmsg+0x123/0x500 [ 42.384226] ? inet_sendmsg+0x123/0x500 [ 42.384748] ? inet_recvmsg+0x540/0x540 [ 42.385263] sock_sendmsg+0xca/0x110 [ 42.385758] SYSC_sendto+0x217/0x380 [ 42.386249] ? SYSC_connect+0x310/0x310 [ 42.386783] ? __might_fault+0x110/0x1d0 [ 42.387324] ? lock_downgrade+0x660/0x660 [ 42.387880] ? __fget_light+0xa1/0x1f0 [ 42.388403] ? __fdget+0x18/0x20 [ 42.388851] ? sock_common_setsockopt+0x95/0xd0 [ 42.389472] ? SyS_setsockopt+0x17f/0x260 [ 42.390021] ? entry_SYSCALL_64_fastpath+0x5/0xbe [ 42.390650] SyS_sendto+0x40/0x50 [ 42.391103] entry_SYSCALL_64_fastpath+0x1f/0xbe [ 42.391731] RIP: 0033:0x7fbbb711e383 [ 42.392217] RSP: 002b:00007ffff4d34f28 EFLAGS: 00000246 ORIG_RAX: 000000000000002c [ 42.393235] RAX: ffffffffffffffda RBX: 0000000000000000 RCX: 00007fbbb711e383 [ 42.394195] RDX: 0000000000001000 RSI: 00007ffff4d34f60 RDI: 0000000000000003 [ 42.395145] RBP: 0000000000000046 R08: 00007ffff4d34f40 R09: 0000000000000018 [ 42.396056] R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000400aad [ 42.396598] R13: 0000000000000066 R14: 00007ffff4d34ee0 R15: 00007fbbb717af00 [ 42.397257] [ 42.397411] Allocated by task 3789: [ 42.397702] save_stack_trace+0x16/0x20 [ 42.398005] save_stack+0x46/0xd0 [ 42.398267] kasan_kmalloc+0xad/0xe0 [ 42.398548] kasan_slab_alloc+0x12/0x20 [ 42.398848] __kmalloc_node_track_caller+0xcb/0x380 [ 42.399224] __kmalloc_reserve.isra.32+0x41/0xe0 [ 42.399654] __alloc_skb+0xf8/0x580 [ 42.400003] sock_wmalloc+0xab/0xf0 [ 42.400346] __ip6_append_data.isra.41+0x2472/0x33d0 [ 42.400813] ip6_append_data+0x1a8/0x2f0 [ 42.401122] rawv6_sendmsg+0x11ee/0x2db0 [ 42.401505] inet_sendmsg+0x123/0x500 [ 42.401860] sock_sendmsg+0xca/0x110 [ 42.402209] ___sys_sendmsg+0x7cb/0x930 [ 42.402582] __sys_sendmsg+0xd9/0x190 [ 42.402941] SyS_sendmsg+0x2d/0x50 [ 42.403273] entry_SYSCALL_64_fastpath+0x1f/0xbe [ 42.403718] [ 42.403871] Freed by task 1794: [ 42.404146] save_stack_trace+0x16/0x20 [ 42.404515] save_stack+0x46/0xd0 [ 42.404827] kasan_slab_free+0x72/0xc0 [ 42.405167] kfree+0xe8/0x2b0 [ 42.405462] skb_free_head+0x74/0xb0 [ 42.405806] skb_release_data+0x30e/0x3a0 [ 42.406198] skb_release_all+0x4a/0x60 [ 42.406563] consume_skb+0x113/0x2e0 [ 42.406910] skb_free_datagram+0x1a/0xe0 [ 42.407288] netlink_recvmsg+0x60d/0xe40 [ 42.407667] sock_recvmsg+0xd7/0x110 [ 42.408022] ___sys_recvmsg+0x25c/0x580 [ 42.408395] __sys_recvmsg+0xd6/0x190 [ 42.408753] SyS_recvmsg+0x2d/0x50 [ 42.409086] entry_SYSCALL_64_fastpath+0x1f/0xbe [ 42.409513] [ 42.409665] The buggy address belongs to the object at ffff88000969e780 [ 42.409665] which belongs to the cache kmalloc-512 of size 512 [ 42.410846] The buggy address is located 24 bytes inside of [ 42.410846] 512-byte region [ffff88000969e780, ffff88000969e980) [ 42.411941] The buggy address belongs to the page: [ 42.412405] page:ffffea000025a780 count:1 mapcount:0 mapping: (null) index:0x0 compound_mapcount: 0 [ 42.413298] flags: 0x100000000008100(slab|head) [ 42.413729] raw: 0100000000008100 0000000000000000 0000000000000000 00000001800c000c [ 42.414387] raw: ffffea00002a9500 0000000900000007 ffff88000c401280 0000000000000000 [ 42.415074] page dumped because: kasan: bad access detected [ 42.415604] [ 42.415757] Memory state around the buggy address: [ 42.416222] ffff88000969e880: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 42.416904] ffff88000969e900: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 42.417591] >ffff88000969e980: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [ 42.418273] ^ [ 42.418588] ffff88000969ea00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb [ 42.419273] ffff88000969ea80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb [ 42.419882] ================================================================== Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: Craig Gallek <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125 Target: 1 Example 2: Code: static void virtio_gpu_set_features(VirtIODevice *vdev, uint64_t features) { static const uint32_t virgl = (1 << VIRTIO_GPU_F_VIRGL); VirtIOGPU *g = VIRTIO_GPU(vdev); g->use_virgl_renderer = ((features & virgl) == virgl); trace_virtio_gpu_features(g->use_virgl_renderer); } 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: bool RTCPeerConnectionHandler::AddICECandidate( scoped_refptr<blink::WebRTCICECandidate> candidate) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::addICECandidate"); std::unique_ptr<webrtc::IceCandidateInterface> native_candidate( dependency_factory_->CreateIceCandidate(candidate->SdpMid().Utf8(), candidate->SdpMLineIndex(), candidate->Candidate().Utf8())); bool return_value = false; if (native_candidate) { return_value = native_peer_connection_->AddIceCandidate(native_candidate.get()); LOG_IF(ERROR, !return_value) << "Error processing ICE candidate."; } else { LOG(ERROR) << "Could not create native ICE candidate."; } if (peer_connection_tracker_) { peer_connection_tracker_->TrackAddIceCandidate( this, std::move(candidate), PeerConnectionTracker::SOURCE_REMOTE, return_value); } return return_value; } Commit Message: Check weak pointers in RTCPeerConnectionHandler::WebRtcSetDescriptionObserverImpl Bug: 912074 Change-Id: I8ba86751f5d5bf12db51520f985ef0d3dae63ed8 Reviewed-on: https://chromium-review.googlesource.com/c/1411916 Commit-Queue: Guido Urdaneta <[email protected]> Reviewed-by: Henrik Boström <[email protected]> Cr-Commit-Position: refs/heads/master@{#622945} 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: BufferMeta(const sp<GraphicBuffer> &graphicBuffer, OMX_U32 portIndex) : mGraphicBuffer(graphicBuffer), mIsBackup(false), mPortIndex(portIndex) { } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200 Target: 1 Example 2: Code: void RenderThreadImpl::Shutdown() { FOR_EACH_OBSERVER( RenderProcessObserver, observers_, OnRenderProcessShutdown()); ChildThread::Shutdown(); if (memory_observer_) { message_loop()->RemoveTaskObserver(memory_observer_.get()); memory_observer_.reset(); } if (webkit_platform_support_) { WebView::willEnterModalLoop(); webkit_platform_support_->web_database_observer_impl()-> WaitForAllDatabasesToClose(); WebView::didExitModalLoop(); } if (devtools_agent_message_filter_.get()) { RemoveFilter(devtools_agent_message_filter_.get()); devtools_agent_message_filter_ = NULL; } RemoveFilter(audio_input_message_filter_.get()); audio_input_message_filter_ = NULL; #if defined(ENABLE_WEBRTC) RTCPeerConnectionHandler::DestructAllHandlers(); peer_connection_factory_.reset(); #endif RemoveFilter(vc_manager_->video_capture_message_filter()); vc_manager_.reset(); RemoveFilter(db_message_filter_.get()); db_message_filter_ = NULL; if (file_thread_) file_thread_->Stop(); if (compositor_output_surface_filter_.get()) { RemoveFilter(compositor_output_surface_filter_.get()); compositor_output_surface_filter_ = NULL; } media_thread_.reset(); RemoveFilter(audio_message_filter_.get()); audio_message_filter_ = NULL; compositor_thread_.reset(); input_handler_manager_.reset(); if (input_event_filter_.get()) { RemoveFilter(input_event_filter_.get()); input_event_filter_ = NULL; } embedded_worker_dispatcher_.reset(); main_thread_indexed_db_dispatcher_.reset(); main_thread_compositor_task_runner_ = NULL; main_message_loop_.reset(); if (webkit_platform_support_) blink::shutdown(); lazy_tls.Pointer()->Set(NULL); #if defined(OS_WIN) NPChannelBase::CleanupChannels(); #endif } Commit Message: Disable forwarding tasks to the Blink scheduler Disable forwarding tasks to the Blink scheduler to avoid some regressions which it has introduced. BUG=391005,415758,415478,412714,416362,416827,417608 [email protected] Review URL: https://codereview.chromium.org/609483002 Cr-Commit-Position: refs/heads/master@{#296916} 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: trace (const char *format, ...) #else trace (format, va_alist) const char *format; va_dcl #endif { va_list args; static FILE *tracefp = (FILE *)NULL; if (tracefp == NULL) tracefp = fopen("/tmp/bash-trace.log", "a+"); if (tracefp == NULL) tracefp = stderr; else fcntl (fileno (tracefp), F_SETFD, 1); /* close-on-exec */ fprintf(tracefp, "TRACE: pid %ld: ", (long)getpid()); SH_VA_START (args, format); vfprintf (tracefp, format, args); fprintf (tracefp, "\n"); va_end (args); fflush(tracefp); } 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: check_mountpoint(const char *progname, char *mountpoint) { int err; struct stat statbuf; /* does mountpoint exist and is it a directory? */ err = stat(mountpoint, &statbuf); if (err) { fprintf(stderr, "%s: failed to stat %s: %s\n", progname, mountpoint, strerror(errno)); return EX_USAGE; } if (!S_ISDIR(statbuf.st_mode)) { fprintf(stderr, "%s: %s is not a directory!", progname, mountpoint); return EX_USAGE; } #if CIFS_LEGACY_SETUID_CHECK /* do extra checks on mountpoint for legacy setuid behavior */ if (!getuid() || geteuid()) return 0; if (statbuf.st_uid != getuid()) { fprintf(stderr, "%s: %s is not owned by user\n", progname, mountpoint); return EX_USAGE; } if ((statbuf.st_mode & S_IRWXU) != S_IRWXU) { fprintf(stderr, "%s: invalid permissions on %s\n", progname, mountpoint); return EX_USAGE; } #endif /* CIFS_LEGACY_SETUID_CHECK */ return 0; } Commit Message: CWE ID: CWE-59 Target: 1 Example 2: Code: namePop(xmlParserCtxtPtr ctxt) { const xmlChar *ret; if ((ctxt == NULL) || (ctxt->nameNr <= 0)) return (NULL); ctxt->nameNr--; if (ctxt->nameNr > 0) ctxt->name = ctxt->nameTab[ctxt->nameNr - 1]; else ctxt->name = NULL; ret = ctxt->nameTab[ctxt->nameNr]; ctxt->nameTab[ctxt->nameNr] = NULL; return (ret); } Commit Message: DO NOT MERGE: Add validation for eternal enities https://bugzilla.gnome.org/show_bug.cgi?id=780691 Bug: 36556310 Change-Id: I9450743e167c3c73af5e4071f3fc85e81d061648 (cherry picked from commit bef9af3d89d241bcb518c20cba6da2a2fd9ba049) CWE ID: CWE-611 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<JSONObject> ClipPaintPropertyNode::ToJSON() const { auto json = JSONObject::Create(); if (Parent()) json->SetString("parent", String::Format("%p", Parent())); json->SetString("localTransformSpace", String::Format("%p", state_.local_transform_space.get())); json->SetString("rect", state_.clip_rect.ToString()); if (state_.clip_rect_excluding_overlay_scrollbars) { json->SetString("rectExcludingOverlayScrollbars", state_.clip_rect_excluding_overlay_scrollbars->ToString()); } if (state_.clip_path) { json->SetBoolean("hasClipPath", true); } if (state_.direct_compositing_reasons != CompositingReason::kNone) { json->SetString( "directCompositingReasons", CompositingReason::ToString(state_.direct_compositing_reasons)); } return json; } 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:
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: authentic_process_fci(struct sc_card *card, struct sc_file *file, const unsigned char *buf, size_t buflen) { struct sc_context *ctx = card->ctx; size_t taglen; int rv; unsigned ii; const unsigned char *tag = NULL; unsigned char ops_DF[8] = { SC_AC_OP_CREATE, SC_AC_OP_DELETE, SC_AC_OP_CRYPTO, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; unsigned char ops_EF[8] = { SC_AC_OP_READ, SC_AC_OP_DELETE, SC_AC_OP_UPDATE, SC_AC_OP_RESIZE, 0xFF, 0xFF, 0xFF, 0xFF }; LOG_FUNC_CALLED(ctx); tag = sc_asn1_find_tag(card->ctx, buf, buflen, 0x6F, &taglen); if (tag != NULL) { sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen); buf = tag; buflen = taglen; } tag = sc_asn1_find_tag(card->ctx, buf, buflen, 0x62, &taglen); if (tag != NULL) { sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen); buf = tag; buflen = taglen; } rv = iso_ops->process_fci(card, file, buf, buflen); LOG_TEST_RET(ctx, rv, "ISO parse FCI failed"); if (!file->sec_attr_len) { sc_log_hex(ctx, "ACLs not found in data", buf, buflen); sc_log(ctx, "Path:%s; Type:%X; PathType:%X", sc_print_path(&file->path), file->type, file->path.type); if (file->path.type == SC_PATH_TYPE_DF_NAME || file->type == SC_FILE_TYPE_DF) { file->type = SC_FILE_TYPE_DF; } else { LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "ACLs tag missing"); } } sc_log_hex(ctx, "ACL data", file->sec_attr, file->sec_attr_len); for (ii = 0; ii < file->sec_attr_len / 2; ii++) { unsigned char op = file->type == SC_FILE_TYPE_DF ? ops_DF[ii] : ops_EF[ii]; unsigned char acl = *(file->sec_attr + ii*2); unsigned char cred_id = *(file->sec_attr + ii*2 + 1); unsigned sc = acl * 0x100 + cred_id; sc_log(ctx, "ACL(%i) op 0x%X, acl %X:%X", ii, op, acl, cred_id); if (op == 0xFF) ; else if (!acl && !cred_id) sc_file_add_acl_entry(file, op, SC_AC_NONE, 0); else if (acl == 0xFF) sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0); else if (acl & AUTHENTIC_AC_SM_MASK) sc_file_add_acl_entry(file, op, SC_AC_SCB, sc); else if (cred_id) sc_file_add_acl_entry(file, op, SC_AC_CHV, cred_id); else sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0); } LOG_FUNC_RETURN(ctx, 0); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125 Target: 1 Example 2: Code: static void ocfs2_write_end_inline(struct inode *inode, loff_t pos, unsigned len, unsigned *copied, struct ocfs2_dinode *di, struct ocfs2_write_ctxt *wc) { void *kaddr; if (unlikely(*copied < len)) { if (!PageUptodate(wc->w_target_page)) { *copied = 0; return; } } kaddr = kmap_atomic(wc->w_target_page); memcpy(di->id2.i_data.id_data + pos, kaddr + pos, *copied); kunmap_atomic(kaddr); trace_ocfs2_write_end_inline( (unsigned long long)OCFS2_I(inode)->ip_blkno, (unsigned long long)pos, *copied, le16_to_cpu(di->id2.i_data.id_count), le16_to_cpu(di->i_dyn_features)); } Commit Message: ocfs2: ip_alloc_sem should be taken in ocfs2_get_block() ip_alloc_sem should be taken in ocfs2_get_block() when reading file in DIRECT mode to prevent concurrent access to extent tree with ocfs2_dio_end_io_write(), which may cause BUGON in the following situation: read file 'A' end_io of writing file 'A' vfs_read __vfs_read ocfs2_file_read_iter generic_file_read_iter ocfs2_direct_IO __blockdev_direct_IO do_blockdev_direct_IO do_direct_IO get_more_blocks ocfs2_get_block ocfs2_extent_map_get_blocks ocfs2_get_clusters ocfs2_get_clusters_nocache() ocfs2_search_extent_list return the index of record which contains the v_cluster, that is v_cluster > rec[i]->e_cpos. ocfs2_dio_end_io ocfs2_dio_end_io_write down_write(&oi->ip_alloc_sem); ocfs2_mark_extent_written ocfs2_change_extent_flag ocfs2_split_extent ... --> modify the rec[i]->e_cpos, resulting in v_cluster < rec[i]->e_cpos. BUG_ON(v_cluster < le32_to_cpu(rec->e_cpos)) [[email protected]: v3] Link: http://lkml.kernel.org/r/[email protected] Link: http://lkml.kernel.org/r/[email protected] Fixes: c15471f79506 ("ocfs2: fix sparse file & data ordering issue in direct io") Signed-off-by: Alex Chen <[email protected]> Reviewed-by: Jun Piao <[email protected]> Reviewed-by: Joseph Qi <[email protected]> Reviewed-by: Gang He <[email protected]> Acked-by: Changwei Ge <[email protected]> Cc: Mark Fasheh <[email protected]> Cc: Joel Becker <[email protected]> Cc: Junxiao Bi <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[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 hns_rcb_get_ring_regs(struct hnae_queue *queue, void *data) { u32 *regs = data; struct ring_pair_cb *ring_pair = container_of(queue, struct ring_pair_cb, q); u32 i = 0; /*rcb ring registers */ regs[0] = dsaf_read_dev(queue, RCB_RING_RX_RING_BASEADDR_L_REG); regs[1] = dsaf_read_dev(queue, RCB_RING_RX_RING_BASEADDR_H_REG); regs[2] = dsaf_read_dev(queue, RCB_RING_RX_RING_BD_NUM_REG); regs[3] = dsaf_read_dev(queue, RCB_RING_RX_RING_BD_LEN_REG); regs[4] = dsaf_read_dev(queue, RCB_RING_RX_RING_PKTLINE_REG); regs[5] = dsaf_read_dev(queue, RCB_RING_RX_RING_TAIL_REG); regs[6] = dsaf_read_dev(queue, RCB_RING_RX_RING_HEAD_REG); regs[7] = dsaf_read_dev(queue, RCB_RING_RX_RING_FBDNUM_REG); regs[8] = dsaf_read_dev(queue, RCB_RING_RX_RING_PKTNUM_RECORD_REG); regs[9] = dsaf_read_dev(queue, RCB_RING_TX_RING_BASEADDR_L_REG); regs[10] = dsaf_read_dev(queue, RCB_RING_TX_RING_BASEADDR_H_REG); regs[11] = dsaf_read_dev(queue, RCB_RING_TX_RING_BD_NUM_REG); regs[12] = dsaf_read_dev(queue, RCB_RING_TX_RING_BD_LEN_REG); regs[13] = dsaf_read_dev(queue, RCB_RING_TX_RING_PKTLINE_REG); regs[15] = dsaf_read_dev(queue, RCB_RING_TX_RING_TAIL_REG); regs[16] = dsaf_read_dev(queue, RCB_RING_TX_RING_HEAD_REG); regs[17] = dsaf_read_dev(queue, RCB_RING_TX_RING_FBDNUM_REG); regs[18] = dsaf_read_dev(queue, RCB_RING_TX_RING_OFFSET_REG); regs[19] = dsaf_read_dev(queue, RCB_RING_TX_RING_PKTNUM_RECORD_REG); regs[20] = dsaf_read_dev(queue, RCB_RING_PREFETCH_EN_REG); regs[21] = dsaf_read_dev(queue, RCB_RING_CFG_VF_NUM_REG); regs[22] = dsaf_read_dev(queue, RCB_RING_ASID_REG); regs[23] = dsaf_read_dev(queue, RCB_RING_RX_VM_REG); regs[24] = dsaf_read_dev(queue, RCB_RING_T0_BE_RST); regs[25] = dsaf_read_dev(queue, RCB_RING_COULD_BE_RST); regs[26] = dsaf_read_dev(queue, RCB_RING_WRR_WEIGHT_REG); regs[27] = dsaf_read_dev(queue, RCB_RING_INTMSK_RXWL_REG); regs[28] = dsaf_read_dev(queue, RCB_RING_INTSTS_RX_RING_REG); regs[29] = dsaf_read_dev(queue, RCB_RING_INTMSK_TXWL_REG); regs[30] = dsaf_read_dev(queue, RCB_RING_INTSTS_TX_RING_REG); regs[31] = dsaf_read_dev(queue, RCB_RING_INTMSK_RX_OVERTIME_REG); regs[32] = dsaf_read_dev(queue, RCB_RING_INTSTS_RX_OVERTIME_REG); regs[33] = dsaf_read_dev(queue, RCB_RING_INTMSK_TX_OVERTIME_REG); regs[34] = dsaf_read_dev(queue, RCB_RING_INTSTS_TX_OVERTIME_REG); /* mark end of ring regs */ for (i = 35; i < 40; i++) regs[i] = 0xcccccc00 + ring_pair->index; } Commit Message: net: hns: fix ethtool_get_strings overflow in hns driver hns_get_sset_count() returns HNS_NET_STATS_CNT and the data space allocated is not enough for ethtool_get_strings(), which will cause random memory corruption. When SLAB and DEBUG_SLAB are both enabled, memory corruptions like the the following can be observed without this patch: [ 43.115200] Slab corruption (Not tainted): Acpi-ParseExt start=ffff801fb0b69030, len=80 [ 43.115206] Redzone: 0x9f911029d006462/0x5f78745f31657070. [ 43.115208] Last user: [<5f7272655f746b70>](0x5f7272655f746b70) [ 43.115214] 010: 70 70 65 31 5f 74 78 5f 70 6b 74 00 6b 6b 6b 6b ppe1_tx_pkt.kkkk [ 43.115217] 030: 70 70 65 31 5f 74 78 5f 70 6b 74 5f 6f 6b 00 6b ppe1_tx_pkt_ok.k [ 43.115218] Next obj: start=ffff801fb0b69098, len=80 [ 43.115220] Redzone: 0x706d655f6f666966/0x9f911029d74e35b. [ 43.115229] Last user: [<ffff0000084b11b0>](acpi_os_release_object+0x28/0x38) [ 43.115231] 000: 74 79 00 6b 6b 6b 6b 6b 70 70 65 31 5f 74 78 5f ty.kkkkkppe1_tx_ [ 43.115232] 010: 70 6b 74 5f 65 72 72 5f 63 73 75 6d 5f 66 61 69 pkt_err_csum_fai Signed-off-by: Timmy Li <[email protected]> Signed-off-by: David S. Miller <[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: gss_wrap_aead (minor_status, context_handle, conf_req_flag, qop_req, input_assoc_buffer, input_payload_buffer, conf_state, output_message_buffer) OM_uint32 * minor_status; gss_ctx_id_t context_handle; int conf_req_flag; gss_qop_t qop_req; gss_buffer_t input_assoc_buffer; gss_buffer_t input_payload_buffer; int * conf_state; gss_buffer_t output_message_buffer; { OM_uint32 status; gss_mechanism mech; gss_union_ctx_id_t ctx; status = val_wrap_aead_args(minor_status, context_handle, conf_req_flag, qop_req, input_assoc_buffer, input_payload_buffer, conf_state, output_message_buffer); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t)context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (!mech) return (GSS_S_BAD_MECH); return gssint_wrap_aead(mech, minor_status, ctx, conf_req_flag, qop_req, input_assoc_buffer, input_payload_buffer, conf_state, output_message_buffer); } Commit Message: Preserve GSS context on init/accept failure After gss_init_sec_context() or gss_accept_sec_context() has created a context, don't delete the mechglue context on failures from subsequent calls, even if the mechanism deletes the mech-specific context (which is allowed by RFC 2744 but not preferred). Check for union contexts with no mechanism context in each GSS function which accepts a gss_ctx_id_t. CVE-2017-11462: RFC 2744 permits a GSS-API implementation to delete an existing security context on a second or subsequent call to gss_init_sec_context() or gss_accept_sec_context() if the call results in an error. This API behavior has been found to be dangerous, leading to the possibility of memory errors in some callers. For safety, GSS-API implementations should instead preserve existing security contexts on error until the caller deletes them. All versions of MIT krb5 prior to this change may delete acceptor contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through 1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on error. ticket: 8598 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup CWE ID: CWE-415 Target: 1 Example 2: Code: static int mqueue_fill_super(struct super_block *sb, void *data, int silent) { struct inode *inode; struct ipc_namespace *ns = sb->s_fs_info; sb->s_iflags |= SB_I_NOEXEC | SB_I_NODEV; sb->s_blocksize = PAGE_SIZE; sb->s_blocksize_bits = PAGE_SHIFT; sb->s_magic = MQUEUE_MAGIC; sb->s_op = &mqueue_super_ops; inode = mqueue_get_inode(sb, ns, S_IFDIR | S_ISVTX | S_IRWXUGO, NULL); if (IS_ERR(inode)) return PTR_ERR(inode); sb->s_root = d_make_root(inode); if (!sb->s_root) return -ENOMEM; return 0; } Commit Message: mqueue: fix a use-after-free in sys_mq_notify() The retry logic for netlink_attachskb() inside sys_mq_notify() is nasty and vulnerable: 1) The sock refcnt is already released when retry is needed 2) The fd is controllable by user-space because we already release the file refcnt so we when retry but the fd has been just closed by user-space during this small window, we end up calling netlink_detachskb() on the error path which releases the sock again, later when the user-space closes this socket a use-after-free could be triggered. Setting 'sock' to NULL here should be sufficient to fix it. Reported-by: GeneBlue <[email protected]> Signed-off-by: Cong Wang <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Manfred Spraul <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[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: const Block* Track::EOSBlock::GetBlock() const { return NULL; } 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 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 AXNodeObject::isMultiSelectable() const { const AtomicString& ariaMultiSelectable = getAttribute(aria_multiselectableAttr); if (equalIgnoringCase(ariaMultiSelectable, "true")) return true; if (equalIgnoringCase(ariaMultiSelectable, "false")) return false; return isHTMLSelectElement(getNode()) && toHTMLSelectElement(*getNode()).isMultiple(); } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254 Target: 1 Example 2: Code: static void nci_core_conn_credits_ntf_packet(struct nci_dev *ndev, struct sk_buff *skb) { struct nci_core_conn_credit_ntf *ntf = (void *) skb->data; int i; pr_debug("num_entries %d\n", ntf->num_entries); if (ntf->num_entries > NCI_MAX_NUM_CONN) ntf->num_entries = NCI_MAX_NUM_CONN; /* update the credits */ for (i = 0; i < ntf->num_entries; i++) { ntf->conn_entries[i].conn_id = nci_conn_id(&ntf->conn_entries[i].conn_id); pr_debug("entry[%d]: conn_id %d, credits %d\n", i, ntf->conn_entries[i].conn_id, ntf->conn_entries[i].credits); if (ntf->conn_entries[i].conn_id == NCI_STATIC_RF_CONN_ID) { /* found static rf connection */ atomic_add(ntf->conn_entries[i].credits, &ndev->credits_cnt); } } /* trigger the next tx */ if (!skb_queue_empty(&ndev->tx_q)) queue_work(ndev->tx_wq, &ndev->tx_work); } Commit Message: NFC: Prevent multiple buffer overflows in NCI Fix multiple remotely-exploitable stack-based buffer overflows due to the NCI code pulling length fields directly from incoming frames and copying too much data into statically-sized arrays. Signed-off-by: Dan Rosenberg <[email protected]> Cc: [email protected] Cc: [email protected] Cc: Lauro Ramos Venancio <[email protected]> Cc: Aloisio Almeida Jr <[email protected]> Cc: Samuel Ortiz <[email protected]> Cc: David S. Miller <[email protected]> Acked-by: Ilan Elias <[email protected]> Signed-off-by: Samuel Ortiz <[email protected]> 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 __init proc_root_init(void) { struct vfsmount *mnt; int err; proc_init_inodecache(); err = register_filesystem(&proc_fs_type); if (err) return; mnt = kern_mount_data(&proc_fs_type, &init_pid_ns); if (IS_ERR(mnt)) { unregister_filesystem(&proc_fs_type); return; } init_pid_ns.proc_mnt = mnt; proc_symlink("mounts", NULL, "self/mounts"); proc_net_init(); #ifdef CONFIG_SYSVIPC proc_mkdir("sysvipc", NULL); #endif proc_mkdir("fs", NULL); proc_mkdir("driver", NULL); proc_mkdir("fs/nfsd", NULL); /* somewhere for the nfsd filesystem to be mounted */ #if defined(CONFIG_SUN_OPENPROMFS) || defined(CONFIG_SUN_OPENPROMFS_MODULE) /* just give it a mountpoint */ proc_mkdir("openprom", NULL); #endif proc_tty_init(); #ifdef CONFIG_PROC_DEVICETREE proc_device_tree_init(); #endif proc_mkdir("bus", NULL); proc_sys_init(); } Commit Message: procfs: fix a vfsmount longterm reference leak kern_mount() doesn't pair with plain mntput()... Signed-off-by: Al Viro <[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: static void unix_detach_fds(struct scm_cookie *scm, struct sk_buff *skb) { int i; scm->fp = UNIXCB(skb).fp; UNIXCB(skb).fp = NULL; for (i = scm->fp->count-1; i >= 0; i--) unix_notinflight(scm->fp->fp[i]); } Commit Message: unix: correctly track in-flight fds in sending process user_struct The commit referenced in the Fixes tag incorrectly accounted the number of in-flight fds over a unix domain socket to the original opener of the file-descriptor. This allows another process to arbitrary deplete the original file-openers resource limit for the maximum of open files. Instead the sending processes and its struct cred should be credited. To do so, we add a reference counted struct user_struct pointer to the scm_fp_list and use it to account for the number of inflight unix fds. Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets") Reported-by: David Herrmann <[email protected]> Cc: David Herrmann <[email protected]> Cc: Willy Tarreau <[email protected]> Cc: Linus Torvalds <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: std::string context_language() { return context_language_; } 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: 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: tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; unsigned char* buffer=NULL; unsigned char* samplebuffer=NULL; tsize_t bufferoffset=0; tsize_t samplebufferoffset=0; tsize_t read=0; tstrip_t i=0; tstrip_t j=0; tstrip_t stripcount=0; tsize_t stripsize=0; tsize_t sepstripcount=0; tsize_t sepstripsize=0; #ifdef OJPEG_SUPPORT toff_t inputoffset=0; uint16 h_samp=1; uint16 v_samp=1; uint16 ri=1; uint32 rows=0; #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint64* sbc; unsigned char* stripbuffer; tsize_t striplength=0; uint32 max_striplength=0; #endif /* ifdef JPEG_SUPPORT */ /* Fail if prior error (in particular, can't trust tiff_datasize) */ if (t2p->t2p_error != T2P_ERR_OK) return(0); if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if (buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ /* * make sure is lsb-to-msb * bit-endianness fill order */ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef CCITT_SUPPORT */ #ifdef ZIP_SUPPORT if (t2p->pdf_compression == T2P_COMPRESS_ZIP) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB) { TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef ZIP_SUPPORT */ #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG) { if(t2p->tiff_dataoffset != 0) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if(t2p->pdf_ojpegiflength==0){ inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); t2pReadFile(input, (tdata_t) buffer, t2p->tiff_datasize); t2pSeekFile(input, inputoffset, SEEK_SET); t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } else { inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); bufferoffset = t2pReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength); t2p->pdf_ojpegiflength = 0; t2pSeekFile(input, inputoffset, SEEK_SET); TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp); buffer[bufferoffset++]= 0xff; buffer[bufferoffset++]= 0xdd; buffer[bufferoffset++]= 0x00; buffer[bufferoffset++]= 0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; buffer[bufferoffset++]= (ri>>8) & 0xff; buffer[bufferoffset++]= ri & 0xff; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0 ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } } else { if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); bufferoffset=t2p->pdf_ojpegdatalength; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); #if 0 /* This hunk of code removed code is clearly mis-placed and we are not sure where it should be (if anywhere) */ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with no JPEG File Interchange offset", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); #endif } } #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if(count > 4) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; } } stripcount=TIFFNumberOfStrips(input); TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); for(i=0;i<stripcount;i++){ if(sbc[i]>max_striplength) max_striplength=sbc[i]; } stripbuffer = (unsigned char*) _TIFFmalloc(max_striplength); if(stripbuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", max_striplength, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1); if(!t2p_process_jpeg_strip( stripbuffer, &striplength, buffer, &bufferoffset, i, t2p->tiff_length)){ TIFFError(TIFF2PDF_MODULE, "Can't process JPEG data in input file %s", TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(stripbuffer); _TIFFfree(buffer); return(bufferoffset); } #endif /* ifdef JPEG_SUPPORT */ (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } } else { if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ sepstripsize=TIFFStripSize(input); sepstripcount=TIFFNumberOfStrips(input); stripsize=sepstripsize*t2p->tiff_samplesperpixel; stripcount=sepstripcount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); samplebuffer = (unsigned char*) _TIFFmalloc(stripsize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } for(i=0;i<stripcount;i++){ samplebufferoffset=0; for(j=0;j<t2p->tiff_samplesperpixel;j++){ read = TIFFReadEncodedStrip(input, i + j*stripcount, (tdata_t) &(samplebuffer[samplebufferoffset]), TIFFmin(sepstripsize, stripsize - samplebufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i + j*stripcount, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; } _TIFFfree(samplebuffer); goto dataready; } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t) buffer, t2p->tiff_datasize * t2p->tiff_samplesperpixel); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; t2p->tiff_datasize *= t2p->tiff_samplesperpixel; } t2p_sample_realize_palette(t2p, buffer); } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length*4); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; } if(!TIFFReadRGBAImageOriented( input, t2p->tiff_width, t2p->tiff_length, (uint32*)buffer, ORIENTATION_TOPLEFT, 0)){ TIFFError(TIFF2PDF_MODULE, "Can't use TIFFReadRGBAImageOriented to extract RGB image from %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } t2p->tiff_datasize=t2p_sample_abgr_to_rgb( (tdata_t) buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } } dataready: t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width); TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length); TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length); TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif /* ifdef CCITT_SUPPORT */ #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=0 ) { if(hor != 0 && ver != 0){ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){ TIFFError(TIFF2PDF_MODULE, "Unable to use JPEG compression for input %s and output %s", TIFFFileName(input), TIFFFileName(output)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif /* ifdef JPEG_SUPPORT */ #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif /* ifdef ZIP_SUPPORT */ default: break; } t2p_enable(output); t2p->outputwritten = 0; #ifdef JPEG_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_JPEG && t2p->tiff_photometric == PHOTOMETRIC_YCBCR){ bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, stripsize * stripcount); } else #endif /* ifdef JPEG_SUPPORT */ { bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize); } if (buffer != NULL) { _TIFFfree(buffer); buffer=NULL; } if (bufferoffset == (tsize_t)-1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded strip to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities in heap or stack allocated buffers. Reported as MSVR 35093, MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR 35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities in heap allocated buffers. Reported as MSVR 35094. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1() that didn't reset the tif_rawcc and tif_rawcp members. I'm not completely sure if that could happen in practice outside of the odd behaviour of t2p_seekproc() of tiff2pdf). The report points that a better fix could be to check the return value of TIFFFlushData1() in places where it isn't done currently, but it seems this patch is enough. Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan & Suha Can from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-787 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 Track::VetEntry(const BlockEntry* pBlockEntry) const { assert(pBlockEntry); const Block* const pBlock = pBlockEntry->GetBlock(); assert(pBlock); assert(pBlock->GetTrackNumber() == m_info.number); if (!pBlock || pBlock->GetTrackNumber() != m_info.number) return false; return true; } 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: PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionCode& ec) { if (!attr) { ec = TYPE_MISMATCH_ERR; return 0; } if (attr->ownerElement() != this) { ec = NOT_FOUND_ERR; return 0; } ASSERT(document() == attr->document()); synchronizeAttribute(attr->qualifiedName()); size_t index = elementData()->getAttrIndex(attr); if (index == notFound) { ec = NOT_FOUND_ERR; return 0; } RefPtr<Attr> guard(attr); detachAttrNodeAtIndex(attr, index); return guard.release(); } Commit Message: Set Attr.ownerDocument in Element#setAttributeNode() Attr objects can move across documents by setAttributeNode(). So It needs to reset ownerDocument through TreeScopeAdoptr::adoptIfNeeded(). BUG=248950 TEST=set-attribute-node-from-iframe.html Review URL: https://chromiumcodereview.appspot.com/17583003 git-svn-id: svn://svn.chromium.org/blink/trunk@152938 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 inline int btif_hl_select_wakeup(void){ char sig_on = btif_hl_signal_select_wakeup; BTIF_TRACE_DEBUG("btif_hl_select_wakeup"); return send(signal_fds[1], &sig_on, sizeof(sig_on), 0); } 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: ext4_xattr_release_block(handle_t *handle, struct inode *inode, struct buffer_head *bh) { struct mb_cache_entry *ce = NULL; int error = 0; struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode); ce = mb_cache_entry_get(ext4_mb_cache, bh->b_bdev, bh->b_blocknr); BUFFER_TRACE(bh, "get_write_access"); error = ext4_journal_get_write_access(handle, bh); if (error) goto out; lock_buffer(bh); if (BHDR(bh)->h_refcount == cpu_to_le32(1)) { ea_bdebug(bh, "refcount now=0; freeing"); if (ce) mb_cache_entry_free(ce); get_bh(bh); unlock_buffer(bh); ext4_free_blocks(handle, inode, bh, 0, 1, EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET); } else { le32_add_cpu(&BHDR(bh)->h_refcount, -1); if (ce) mb_cache_entry_release(ce); /* * Beware of this ugliness: Releasing of xattr block references * from different inodes can race and so we have to protect * from a race where someone else frees the block (and releases * its journal_head) before we are done dirtying the buffer. In * nojournal mode this race is harmless and we actually cannot * call ext4_handle_dirty_xattr_block() with locked buffer as * that function can call sync_dirty_buffer() so for that case * we handle the dirtying after unlocking the buffer. */ if (ext4_handle_valid(handle)) error = ext4_handle_dirty_xattr_block(handle, inode, bh); unlock_buffer(bh); if (!ext4_handle_valid(handle)) error = ext4_handle_dirty_xattr_block(handle, inode, bh); if (IS_SYNC(inode)) ext4_handle_sync(handle); dquot_free_block(inode, EXT4_C2B(EXT4_SB(inode->i_sb), 1)); ea_bdebug(bh, "refcount now=%d; releasing", le32_to_cpu(BHDR(bh)->h_refcount)); } out: ext4_std_error(inode->i_sb, error); return; } Commit Message: ext4: convert to mbcache2 The conversion is generally straightforward. The only tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting buffer lock. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-19 Target: 1 Example 2: Code: void NavigateAndCheckDownload(const GURL& url) { const GURL original_url(shell()->web_contents()->GetLastCommittedURL()); DownloadManager* download_manager = BrowserContext::GetDownloadManager( shell()->web_contents()->GetBrowserContext()); DownloadTestObserverTerminal download_observer( download_manager, 1, DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL); NavigateToURL(shell(), url); download_observer.WaitForFinished(); EXPECT_EQ(original_url, shell()->web_contents()->GetLastCommittedURL()); } Commit Message: Do not use NavigationEntry to block history navigations. This is no longer necessary after r477371. BUG=777419 TEST=See bug for repro steps. Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation Change-Id: I701e4d4853858281b43e3743b12274dbeadfbf18 Reviewed-on: https://chromium-review.googlesource.com/733959 Reviewed-by: Devlin <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#511942} 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 su_pam_conv(int num_msg, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr) { if (suppress_pam_info && num_msg == 1 && msg && msg[0]->msg_style == PAM_TEXT_INFO) return PAM_SUCCESS; #ifdef HAVE_SECURITY_PAM_MISC_H return misc_conv(num_msg, msg, resp, appdata_ptr); #elif defined(HAVE_SECURITY_OPENPAM_H) return openpam_ttyconv(num_msg, msg, resp, appdata_ptr); #endif } Commit Message: su: properly clear child PID Reported-by: Tobias Stöckmann <[email protected]> Signed-off-by: Karel Zak <[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 int setup_ttydir_console(const struct lxc_rootfs *rootfs, const struct lxc_console *console, char *ttydir) { char path[MAXPATHLEN], lxcpath[MAXPATHLEN]; int ret; /* create rootfs/dev/<ttydir> directory */ ret = snprintf(path, sizeof(path), "%s/dev/%s", rootfs->mount, ttydir); if (ret >= sizeof(path)) return -1; ret = mkdir(path, 0755); if (ret && errno != EEXIST) { SYSERROR("failed with errno %d to create %s", errno, path); return -1; } INFO("created %s", path); ret = snprintf(lxcpath, sizeof(lxcpath), "%s/dev/%s/console", rootfs->mount, ttydir); if (ret >= sizeof(lxcpath)) { ERROR("console path too long"); return -1; } snprintf(path, sizeof(path), "%s/dev/console", rootfs->mount); ret = unlink(path); if (ret && errno != ENOENT) { SYSERROR("error unlinking %s", path); return -1; } ret = creat(lxcpath, 0660); if (ret==-1 && errno != EEXIST) { SYSERROR("error %d creating %s", errno, lxcpath); return -1; } if (ret >= 0) close(ret); if (console->master < 0) { INFO("no console"); return 0; } if (mount(console->name, lxcpath, "none", MS_BIND, 0)) { ERROR("failed to mount '%s' on '%s'", console->name, lxcpath); return -1; } /* create symlink from rootfs/dev/console to 'lxc/console' */ ret = snprintf(lxcpath, sizeof(lxcpath), "%s/console", ttydir); if (ret >= sizeof(lxcpath)) { ERROR("lxc/console path too long"); return -1; } ret = symlink(lxcpath, path); if (ret) { SYSERROR("failed to create symlink for console"); return -1; } INFO("console has been setup on %s", lxcpath); return 0; } Commit Message: CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <[email protected]> Acked-by: Stéphane Graber <[email protected]> CWE ID: CWE-59 Target: 1 Example 2: Code: PHP_MINFO_FUNCTION(radius) { php_info_print_table_start(); php_info_print_table_header(2, "radius support", "enabled"); php_info_print_table_row(2, "version", PHP_RADIUS_VERSION); php_info_print_table_end(); } Commit Message: Fix a security issue in radius_get_vendor_attr(). The underlying rad_get_vendor_attr() function assumed that it would always be given valid VSA data. Indeed, the buffer length wasn't even passed in; the assumption was that the length field within the VSA structure would be valid. This could result in denial of service by providing a length that would be beyond the memory limit, or potential arbitrary memory access by providing a length greater than the actual data given. rad_get_vendor_attr() has been changed to require the raw data length be provided, and this is then used to check that the VSA is valid. Conflicts: radlib_vs.h 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: PHP_METHOD(Phar, offsetSet) { char *fname, *cont_str = NULL; size_t fname_len, cont_len; zval *zresource; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "sr", &fname, &fname_len, &zresource) == FAILURE && zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) { return; } if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set stub \".phar/stub.php\" directly in phar \"%s\", use setStub", phar_obj->archive->fname); return; } if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set alias \".phar/alias.txt\" directly in phar \"%s\", use setAlias", phar_obj->archive->fname); return; } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set any files or directories in magic \".phar\" directory", phar_obj->archive->fname); return; } phar_add_file(&(phar_obj->archive), fname, fname_len, cont_str, cont_len, zresource); } Commit Message: CWE ID: CWE-20 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: LinkChangeSerializerMarkupAccumulator::LinkChangeSerializerMarkupAccumulator(PageSerializer* serializer, Document* document, Vector<Node*>* nodes, LinkLocalPathMap* links, String directoryName) : SerializerMarkupAccumulator(serializer, document, nodes) , m_replaceLinks(links) , m_directoryName(directoryName) { } Commit Message: Revert 162155 "This review merges the two existing page serializ..." Change r162155 broke the world even though it was landed using the CQ. > This review merges the two existing page serializers, WebPageSerializerImpl and > PageSerializer, into one, PageSerializer. In addition to this it moves all > the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the > PageSerializerTest structure and splits out one test for MHTML into a new > MHTMLTest file. > > Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the > 'Save Page as MHTML' flag is enabled now uses the same code, and should thus > have the same feature set. Meaning that both modes now should be a bit better. > > Detailed list of changes: > > - PageSerializerTest: Prepare for more DTD test > - PageSerializerTest: Remove now unneccesary input image test > - PageSerializerTest: Remove unused WebPageSerializer/Impl code > - PageSerializerTest: Move data URI morph test > - PageSerializerTest: Move data URI test > - PageSerializerTest: Move namespace test > - PageSerializerTest: Move SVG Image test > - MHTMLTest: Move MHTML specific test to own test file > - PageSerializerTest: Delete duplicate XML header test > - PageSerializerTest: Move blank frame test > - PageSerializerTest: Move CSS test > - PageSerializerTest: Add frameset/frame test > - PageSerializerTest: Move old iframe test > - PageSerializerTest: Move old elements test > - Use PageSerizer for saving web pages > - PageSerializerTest: Test for rewriting links > - PageSerializer: Add rewrite link accumulator > - PageSerializer: Serialize images in iframes/frames src > - PageSerializer: XHTML fix for meta tags > - PageSerializer: Add presentation CSS > - PageSerializer: Rename out parameter > > BUG= > [email protected] > > Review URL: https://codereview.chromium.org/68613003 [email protected] Review URL: https://codereview.chromium.org/73673003 git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 1 Example 2: Code: bool ShouldQuicAllowServerMigration( const VariationParameters& quic_trial_params) { return base::LowerCaseEqualsASCII( GetVariationParam(quic_trial_params, "allow_server_migration"), "true"); } Commit Message: Fix a bug in network_session_configurator.cc in which support for HTTPS URLS in QUIC proxies was always set to false. BUG=914497 Change-Id: I56ad16088168302598bb448553ba32795eee3756 Reviewed-on: https://chromium-review.googlesource.com/c/1417356 Auto-Submit: Ryan Hamilton <[email protected]> Commit-Queue: Zhongyi Shi <[email protected]> Reviewed-by: Zhongyi Shi <[email protected]> Cr-Commit-Position: refs/heads/master@{#623763} 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: OMX_ERRORTYPE omx_venc::set_parameter(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE paramIndex, OMX_IN OMX_PTR paramData) { (void)hComp; OMX_ERRORTYPE eRet = OMX_ErrorNone; if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("ERROR: Set Param in Invalid State"); return OMX_ErrorInvalidState; } if (paramData == NULL) { DEBUG_PRINT_ERROR("ERROR: Get Param in Invalid paramData"); return OMX_ErrorBadParameter; } /*set_parameter can be called in loaded state or disabled port */ if (m_state == OMX_StateLoaded || m_sInPortDef.bEnabled == OMX_FALSE || m_sOutPortDef.bEnabled == OMX_FALSE) { DEBUG_PRINT_LOW("Set Parameter called in valid state"); } else { DEBUG_PRINT_ERROR("ERROR: Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } switch ((int)paramIndex) { case OMX_IndexParamPortDefinition: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_PORTDEFINITIONTYPE); OMX_PARAM_PORTDEFINITIONTYPE *portDefn; portDefn = (OMX_PARAM_PORTDEFINITIONTYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition H= %d, W = %d", (int)portDefn->format.video.nFrameHeight, (int)portDefn->format.video.nFrameWidth); if (PORT_INDEX_IN == portDefn->nPortIndex) { if (!dev_is_video_session_supported(portDefn->format.video.nFrameWidth, portDefn->format.video.nFrameHeight)) { DEBUG_PRINT_ERROR("video session not supported"); omx_report_unsupported_setting(); return OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_LOW("i/p actual cnt requested = %u", (unsigned int)portDefn->nBufferCountActual); DEBUG_PRINT_LOW("i/p min cnt requested = %u", (unsigned int)portDefn->nBufferCountMin); DEBUG_PRINT_LOW("i/p buffersize requested = %u", (unsigned int)portDefn->nBufferSize); if (portDefn->nBufferCountMin > portDefn->nBufferCountActual) { DEBUG_PRINT_ERROR("ERROR: (In_PORT) Min buffers (%u) > actual count (%u)", (unsigned int)portDefn->nBufferCountMin, (unsigned int)portDefn->nBufferCountActual); return OMX_ErrorUnsupportedSetting; } if (handle->venc_set_param(paramData,OMX_IndexParamPortDefinition) != true) { DEBUG_PRINT_ERROR("ERROR: venc_set_param input failed"); return handle->hw_overload ? OMX_ErrorInsufficientResources : OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_LOW("i/p previous actual cnt = %u", (unsigned int)m_sInPortDef.nBufferCountActual); DEBUG_PRINT_LOW("i/p previous min cnt = %u", (unsigned int)m_sInPortDef.nBufferCountMin); memcpy(&m_sInPortDef, portDefn,sizeof(OMX_PARAM_PORTDEFINITIONTYPE)); #ifdef _ANDROID_ICS_ if (portDefn->format.video.eColorFormat == (OMX_COLOR_FORMATTYPE)QOMX_COLOR_FormatAndroidOpaque) { m_sInPortDef.format.video.eColorFormat = (OMX_COLOR_FORMATTYPE) QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m; if (!mUseProxyColorFormat) { if (!c2d_conv.init()) { DEBUG_PRINT_ERROR("C2D init failed"); return OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_HIGH("C2D init is successful"); } mUseProxyColorFormat = true; m_input_msg_id = OMX_COMPONENT_GENERATE_ETB_OPQ; } else mUseProxyColorFormat = false; #endif /*Query Input Buffer Requirements*/ dev_get_buf_req (&m_sInPortDef.nBufferCountMin, &m_sInPortDef.nBufferCountActual, &m_sInPortDef.nBufferSize, m_sInPortDef.nPortIndex); /*Query ouput Buffer Requirements*/ dev_get_buf_req (&m_sOutPortDef.nBufferCountMin, &m_sOutPortDef.nBufferCountActual, &m_sOutPortDef.nBufferSize, m_sOutPortDef.nPortIndex); m_sInPortDef.nBufferCountActual = portDefn->nBufferCountActual; } else if (PORT_INDEX_OUT == portDefn->nPortIndex) { DEBUG_PRINT_LOW("o/p actual cnt requested = %u", (unsigned int)portDefn->nBufferCountActual); DEBUG_PRINT_LOW("o/p min cnt requested = %u", (unsigned int)portDefn->nBufferCountMin); DEBUG_PRINT_LOW("o/p buffersize requested = %u", (unsigned int)portDefn->nBufferSize); if (portDefn->nBufferCountMin > portDefn->nBufferCountActual) { DEBUG_PRINT_ERROR("ERROR: (Out_PORT) Min buffers (%u) > actual count (%u)", (unsigned int)portDefn->nBufferCountMin, (unsigned int)portDefn->nBufferCountActual); return OMX_ErrorUnsupportedSetting; } if (handle->venc_set_param(paramData,OMX_IndexParamPortDefinition) != true) { DEBUG_PRINT_ERROR("ERROR: venc_set_param output failed"); return OMX_ErrorUnsupportedSetting; } #ifdef _MSM8974_ /*Query ouput Buffer Requirements*/ dev_get_buf_req(&m_sOutPortDef.nBufferCountMin, &m_sOutPortDef.nBufferCountActual, &m_sOutPortDef.nBufferSize, m_sOutPortDef.nPortIndex); #endif memcpy(&m_sOutPortDef,portDefn,sizeof(struct OMX_PARAM_PORTDEFINITIONTYPE)); update_profile_level(); //framerate , bitrate DEBUG_PRINT_LOW("o/p previous actual cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountActual); DEBUG_PRINT_LOW("o/p previous min cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountMin); m_sOutPortDef.nBufferCountActual = portDefn->nBufferCountActual; } else { DEBUG_PRINT_ERROR("ERROR: Set_parameter: Bad Port idx %d", (int)portDefn->nPortIndex); eRet = OMX_ErrorBadPortIndex; } m_sConfigFramerate.xEncodeFramerate = portDefn->format.video.xFramerate; m_sConfigBitrate.nEncodeBitrate = portDefn->format.video.nBitrate; m_sParamBitrate.nTargetBitrate = portDefn->format.video.nBitrate; } break; case OMX_IndexParamVideoPortFormat: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PORTFORMATTYPE); OMX_VIDEO_PARAM_PORTFORMATTYPE *portFmt = (OMX_VIDEO_PARAM_PORTFORMATTYPE *)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoPortFormat %d", portFmt->eColorFormat); if (PORT_INDEX_IN == portFmt->nPortIndex) { if (handle->venc_set_param(paramData,OMX_IndexParamVideoPortFormat) != true) { return OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoPortFormat %d", portFmt->eColorFormat); update_profile_level(); //framerate #ifdef _ANDROID_ICS_ if (portFmt->eColorFormat == (OMX_COLOR_FORMATTYPE)QOMX_COLOR_FormatAndroidOpaque) { m_sInPortFormat.eColorFormat = (OMX_COLOR_FORMATTYPE) QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m; if (!mUseProxyColorFormat) { if (!c2d_conv.init()) { DEBUG_PRINT_ERROR("C2D init failed"); return OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_HIGH("C2D init is successful"); } mUseProxyColorFormat = true; m_input_msg_id = OMX_COMPONENT_GENERATE_ETB_OPQ; } else #endif { m_sInPortFormat.eColorFormat = portFmt->eColorFormat; m_sInPortDef.format.video.eColorFormat = portFmt->eColorFormat; m_input_msg_id = OMX_COMPONENT_GENERATE_ETB; mUseProxyColorFormat = false; } m_sInPortFormat.xFramerate = portFmt->xFramerate; } } break; case OMX_IndexParamVideoInit: { //TODO, do we need this index set param VALIDATE_OMX_PARAM_DATA(paramData, OMX_PORT_PARAM_TYPE); OMX_PORT_PARAM_TYPE* pParam = (OMX_PORT_PARAM_TYPE*)(paramData); DEBUG_PRINT_LOW("Set OMX_IndexParamVideoInit called"); break; } case OMX_IndexParamVideoBitrate: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_BITRATETYPE); OMX_VIDEO_PARAM_BITRATETYPE* pParam = (OMX_VIDEO_PARAM_BITRATETYPE*)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoBitrate"); if (handle->venc_set_param(paramData,OMX_IndexParamVideoBitrate) != true) { return OMX_ErrorUnsupportedSetting; } m_sParamBitrate.nTargetBitrate = pParam->nTargetBitrate; m_sParamBitrate.eControlRate = pParam->eControlRate; update_profile_level(); //bitrate m_sConfigBitrate.nEncodeBitrate = pParam->nTargetBitrate; m_sInPortDef.format.video.nBitrate = pParam->nTargetBitrate; m_sOutPortDef.format.video.nBitrate = pParam->nTargetBitrate; DEBUG_PRINT_LOW("bitrate = %u", (unsigned int)m_sOutPortDef.format.video.nBitrate); break; } case OMX_IndexParamVideoMpeg4: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_MPEG4TYPE); OMX_VIDEO_PARAM_MPEG4TYPE* pParam = (OMX_VIDEO_PARAM_MPEG4TYPE*)paramData; OMX_VIDEO_PARAM_MPEG4TYPE mp4_param; memcpy(&mp4_param, pParam, sizeof(struct OMX_VIDEO_PARAM_MPEG4TYPE)); DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoMpeg4"); if (pParam->eProfile == OMX_VIDEO_MPEG4ProfileAdvancedSimple) { #ifdef MAX_RES_1080P if (pParam->nBFrames) { DEBUG_PRINT_HIGH("INFO: Only 1 Bframe is supported"); mp4_param.nBFrames = 1; } #else if (pParam->nBFrames) { DEBUG_PRINT_ERROR("Warning: B frames not supported"); mp4_param.nBFrames = 0; } #endif #ifdef _MSM8974_ if (pParam->nBFrames || bframes) mp4_param.nBFrames = (pParam->nBFrames > (unsigned int) bframes)? pParam->nBFrames : bframes; DEBUG_PRINT_HIGH("MPEG4: %u BFrames are being set", (unsigned int)mp4_param.nBFrames); #endif } else { if (pParam->nBFrames) { DEBUG_PRINT_ERROR("Warning: B frames not supported"); mp4_param.nBFrames = 0; } } if (handle->venc_set_param(&mp4_param,OMX_IndexParamVideoMpeg4) != true) { return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamMPEG4,pParam, sizeof(struct OMX_VIDEO_PARAM_MPEG4TYPE)); m_sIntraperiod.nPFrames = m_sParamMPEG4.nPFrames; if (pParam->nBFrames || bframes) m_sIntraperiod.nBFrames = m_sParamMPEG4.nBFrames = mp4_param.nBFrames; else m_sIntraperiod.nBFrames = m_sParamMPEG4.nBFrames; break; } case OMX_IndexParamVideoH263: { OMX_VIDEO_PARAM_H263TYPE* pParam = (OMX_VIDEO_PARAM_H263TYPE*)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoH263"); if (handle->venc_set_param(paramData,OMX_IndexParamVideoH263) != true) { return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamH263,pParam, sizeof(struct OMX_VIDEO_PARAM_H263TYPE)); m_sIntraperiod.nPFrames = m_sParamH263.nPFrames; m_sIntraperiod.nBFrames = m_sParamH263.nBFrames; break; } case OMX_IndexParamVideoAvc: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_AVCTYPE); OMX_VIDEO_PARAM_AVCTYPE* pParam = (OMX_VIDEO_PARAM_AVCTYPE*)paramData; OMX_VIDEO_PARAM_AVCTYPE avc_param; memcpy(&avc_param, pParam, sizeof( struct OMX_VIDEO_PARAM_AVCTYPE)); DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoAvc"); if ((pParam->eProfile == OMX_VIDEO_AVCProfileHigh)|| (pParam->eProfile == OMX_VIDEO_AVCProfileMain)) { #ifdef MAX_RES_1080P if (pParam->nBFrames) { DEBUG_PRINT_HIGH("INFO: Only 1 Bframe is supported"); avc_param.nBFrames = 1; } if (pParam->nRefFrames != 2) { DEBUG_PRINT_ERROR("Warning: 2 RefFrames are needed, changing RefFrames from %u to 2", (unsigned int)pParam->nRefFrames); avc_param.nRefFrames = 2; } #else if (pParam->nBFrames) { DEBUG_PRINT_ERROR("Warning: B frames not supported"); avc_param.nBFrames = 0; } if (pParam->nRefFrames != 1) { DEBUG_PRINT_ERROR("Warning: Only 1 RefFrame is supported, changing RefFrame from %u to 1)", (unsigned int)pParam->nRefFrames); avc_param.nRefFrames = 1; } #endif #ifdef _MSM8974_ if (pParam->nBFrames || bframes) { avc_param.nBFrames = (pParam->nBFrames > (unsigned int) bframes)? pParam->nBFrames : bframes; avc_param.nRefFrames = (avc_param.nBFrames < 4)? avc_param.nBFrames + 1 : 4; } DEBUG_PRINT_HIGH("AVC: RefFrames: %u, BFrames: %u", (unsigned int)avc_param.nRefFrames, (unsigned int)avc_param.nBFrames); avc_param.bEntropyCodingCABAC = (OMX_BOOL)(avc_param.bEntropyCodingCABAC && entropy); avc_param.nCabacInitIdc = entropy ? avc_param.nCabacInitIdc : 0; #endif } else { if (pParam->nRefFrames != 1) { DEBUG_PRINT_ERROR("Warning: Only 1 RefFrame is supported, changing RefFrame from %u to 1)", (unsigned int)pParam->nRefFrames); avc_param.nRefFrames = 1; } if (pParam->nBFrames) { DEBUG_PRINT_ERROR("Warning: B frames not supported"); avc_param.nBFrames = 0; } } if (handle->venc_set_param(&avc_param,OMX_IndexParamVideoAvc) != true) { return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamAVC,pParam, sizeof(struct OMX_VIDEO_PARAM_AVCTYPE)); m_sIntraperiod.nPFrames = m_sParamAVC.nPFrames; if (pParam->nBFrames || bframes) m_sIntraperiod.nBFrames = m_sParamAVC.nBFrames = avc_param.nBFrames; else m_sIntraperiod.nBFrames = m_sParamAVC.nBFrames; break; } case (OMX_INDEXTYPE)OMX_IndexParamVideoVp8: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_VP8TYPE); OMX_VIDEO_PARAM_VP8TYPE* pParam = (OMX_VIDEO_PARAM_VP8TYPE*)paramData; OMX_VIDEO_PARAM_VP8TYPE vp8_param; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoVp8"); if (pParam->nDCTPartitions != m_sParamVP8.nDCTPartitions || pParam->bErrorResilientMode != m_sParamVP8.bErrorResilientMode) { DEBUG_PRINT_ERROR("VP8 doesn't support nDCTPartitions or bErrorResilientMode"); } memcpy(&vp8_param, pParam, sizeof( struct OMX_VIDEO_PARAM_VP8TYPE)); if (handle->venc_set_param(&vp8_param, (OMX_INDEXTYPE)OMX_IndexParamVideoVp8) != true) { return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamVP8,pParam, sizeof(struct OMX_VIDEO_PARAM_VP8TYPE)); break; } case (OMX_INDEXTYPE)OMX_IndexParamVideoHevc: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_HEVCTYPE); OMX_VIDEO_PARAM_HEVCTYPE* pParam = (OMX_VIDEO_PARAM_HEVCTYPE*)paramData; OMX_VIDEO_PARAM_HEVCTYPE hevc_param; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoHevc"); memcpy(&hevc_param, pParam, sizeof( struct OMX_VIDEO_PARAM_HEVCTYPE)); if (handle->venc_set_param(&hevc_param, (OMX_INDEXTYPE)OMX_IndexParamVideoHevc) != true) { DEBUG_PRINT_ERROR("Failed : set_parameter: OMX_IndexParamVideoHevc"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamHEVC, pParam, sizeof(struct OMX_VIDEO_PARAM_HEVCTYPE)); break; } case OMX_IndexParamVideoProfileLevelCurrent: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PROFILELEVELTYPE); OMX_VIDEO_PARAM_PROFILELEVELTYPE* pParam = (OMX_VIDEO_PARAM_PROFILELEVELTYPE*)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoProfileLevelCurrent"); if (handle->venc_set_param(pParam,OMX_IndexParamVideoProfileLevelCurrent) != true) { DEBUG_PRINT_ERROR("set_parameter: OMX_IndexParamVideoProfileLevelCurrent failed for Profile: %u " "Level :%u", (unsigned int)pParam->eProfile, (unsigned int)pParam->eLevel); return OMX_ErrorUnsupportedSetting; } m_sParamProfileLevel.eProfile = pParam->eProfile; m_sParamProfileLevel.eLevel = pParam->eLevel; if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.mpeg4",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamMPEG4.eProfile = (OMX_VIDEO_MPEG4PROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamMPEG4.eLevel = (OMX_VIDEO_MPEG4LEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("MPEG4 profile = %d, level = %d", m_sParamMPEG4.eProfile, m_sParamMPEG4.eLevel); } else if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.h263",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamH263.eProfile = (OMX_VIDEO_H263PROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamH263.eLevel = (OMX_VIDEO_H263LEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("H263 profile = %d, level = %d", m_sParamH263.eProfile, m_sParamH263.eLevel); } else if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.avc",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamAVC.eProfile = (OMX_VIDEO_AVCPROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamAVC.eLevel = (OMX_VIDEO_AVCLEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("AVC profile = %d, level = %d", m_sParamAVC.eProfile, m_sParamAVC.eLevel); } else if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.avc.secure",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamAVC.eProfile = (OMX_VIDEO_AVCPROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamAVC.eLevel = (OMX_VIDEO_AVCLEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("\n AVC profile = %d, level = %d", m_sParamAVC.eProfile, m_sParamAVC.eLevel); } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.vp8",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamVP8.eProfile = (OMX_VIDEO_VP8PROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamVP8.eLevel = (OMX_VIDEO_VP8LEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("VP8 profile = %d, level = %d", m_sParamVP8.eProfile, m_sParamVP8.eLevel); } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.hevc",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamHEVC.eProfile = (OMX_VIDEO_HEVCPROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamHEVC.eLevel = (OMX_VIDEO_HEVCLEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("HEVC profile = %d, level = %d", m_sParamHEVC.eProfile, m_sParamHEVC.eLevel); } break; } case OMX_IndexParamStandardComponentRole: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_COMPONENTROLETYPE); OMX_PARAM_COMPONENTROLETYPE *comp_role; comp_role = (OMX_PARAM_COMPONENTROLETYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamStandardComponentRole %s", comp_role->cRole); if ((m_state == OMX_StateLoaded)&& !BITMASK_PRESENT(&m_flags,OMX_COMPONENT_IDLE_PENDING)) { DEBUG_PRINT_LOW("Set Parameter called in valid state"); } else { DEBUG_PRINT_ERROR("Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.avc",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((char*)comp_role->cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.avc.secure",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((char*)comp_role->cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s\n", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_encoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.mpeg4",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.h263",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_encoder.h263",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.h263",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } #ifdef _MSM8974_ else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.vp8",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_encoder.vp8",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.vp8",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } #endif else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.hevc",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_encoder.hevc",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.hevc",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown param %s", m_nkind); eRet = OMX_ErrorInvalidComponentName; } break; } case OMX_IndexParamPriorityMgmt: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PRIORITYMGMTTYPE); DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPriorityMgmt"); if (m_state != OMX_StateLoaded) { DEBUG_PRINT_ERROR("ERROR: Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } OMX_PRIORITYMGMTTYPE *priorityMgmtype = (OMX_PRIORITYMGMTTYPE*) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPriorityMgmt %u", (unsigned int)priorityMgmtype->nGroupID); DEBUG_PRINT_LOW("set_parameter: priorityMgmtype %u", (unsigned int)priorityMgmtype->nGroupPriority); m_sPriorityMgmt.nGroupID = priorityMgmtype->nGroupID; m_sPriorityMgmt.nGroupPriority = priorityMgmtype->nGroupPriority; break; } case OMX_IndexParamCompBufferSupplier: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_BUFFERSUPPLIERTYPE); DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamCompBufferSupplier"); OMX_PARAM_BUFFERSUPPLIERTYPE *bufferSupplierType = (OMX_PARAM_BUFFERSUPPLIERTYPE*) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamCompBufferSupplier %d", bufferSupplierType->eBufferSupplier); if (bufferSupplierType->nPortIndex == 0 || bufferSupplierType->nPortIndex ==1) m_sInBufSupplier.eBufferSupplier = bufferSupplierType->eBufferSupplier; else eRet = OMX_ErrorBadPortIndex; break; } case OMX_IndexParamVideoQuantization: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_QUANTIZATIONTYPE); DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoQuantization"); OMX_VIDEO_PARAM_QUANTIZATIONTYPE *session_qp = (OMX_VIDEO_PARAM_QUANTIZATIONTYPE*) paramData; if (session_qp->nPortIndex == PORT_INDEX_OUT) { if (handle->venc_set_param(paramData, OMX_IndexParamVideoQuantization) != true) { return OMX_ErrorUnsupportedSetting; } m_sSessionQuantization.nQpI = session_qp->nQpI; m_sSessionQuantization.nQpP = session_qp->nQpP; m_sSessionQuantization.nQpB = session_qp->nQpB; } else { DEBUG_PRINT_ERROR("ERROR: Unsupported port Index for Session QP setting"); eRet = OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexParamVideoQPRange: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_VIDEO_PARAM_QPRANGETYPE); DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexParamVideoQPRange"); OMX_QCOM_VIDEO_PARAM_QPRANGETYPE *qp_range = (OMX_QCOM_VIDEO_PARAM_QPRANGETYPE*) paramData; if (qp_range->nPortIndex == PORT_INDEX_OUT) { if (handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexParamVideoQPRange) != true) { return OMX_ErrorUnsupportedSetting; } m_sSessionQPRange.minQP= qp_range->minQP; m_sSessionQPRange.maxQP= qp_range->maxQP; } else { DEBUG_PRINT_ERROR("ERROR: Unsupported port Index for QP range setting"); eRet = OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexPortDefn: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_PARAM_PORTDEFINITIONTYPE); OMX_QCOM_PARAM_PORTDEFINITIONTYPE* pParam = (OMX_QCOM_PARAM_PORTDEFINITIONTYPE*)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexPortDefn"); if (pParam->nPortIndex == (OMX_U32)PORT_INDEX_IN) { if (pParam->nMemRegion > OMX_QCOM_MemRegionInvalid && pParam->nMemRegion < OMX_QCOM_MemRegionMax) { m_use_input_pmem = OMX_TRUE; } else { m_use_input_pmem = OMX_FALSE; } } else if (pParam->nPortIndex == (OMX_U32)PORT_INDEX_OUT) { if (pParam->nMemRegion > OMX_QCOM_MemRegionInvalid && pParam->nMemRegion < OMX_QCOM_MemRegionMax) { m_use_output_pmem = OMX_TRUE; } else { m_use_output_pmem = OMX_FALSE; } } else { DEBUG_PRINT_ERROR("ERROR: SetParameter called on unsupported Port Index for QcomPortDefn"); return OMX_ErrorBadPortIndex; } break; } case OMX_IndexParamVideoErrorCorrection: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE); DEBUG_PRINT_LOW("OMX_IndexParamVideoErrorCorrection"); OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE* pParam = (OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE*)paramData; if (!handle->venc_set_param(paramData, OMX_IndexParamVideoErrorCorrection)) { DEBUG_PRINT_ERROR("ERROR: Request for setting Error Resilience failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sErrorCorrection,pParam, sizeof(m_sErrorCorrection)); break; } case OMX_IndexParamVideoIntraRefresh: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_INTRAREFRESHTYPE); DEBUG_PRINT_LOW("set_param:OMX_IndexParamVideoIntraRefresh"); OMX_VIDEO_PARAM_INTRAREFRESHTYPE* pParam = (OMX_VIDEO_PARAM_INTRAREFRESHTYPE*)paramData; if (!handle->venc_set_param(paramData,OMX_IndexParamVideoIntraRefresh)) { DEBUG_PRINT_ERROR("ERROR: Request for setting intra refresh failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sIntraRefresh, pParam, sizeof(m_sIntraRefresh)); break; } #ifdef _ANDROID_ICS_ case OMX_QcomIndexParamVideoMetaBufferMode: { VALIDATE_OMX_PARAM_DATA(paramData, StoreMetaDataInBuffersParams); StoreMetaDataInBuffersParams *pParam = (StoreMetaDataInBuffersParams*)paramData; DEBUG_PRINT_HIGH("set_parameter:OMX_QcomIndexParamVideoMetaBufferMode: " "port_index = %u, meta_mode = %d", (unsigned int)pParam->nPortIndex, pParam->bStoreMetaData); if (pParam->nPortIndex == PORT_INDEX_IN) { if (pParam->bStoreMetaData != meta_mode_enable) { if (!handle->venc_set_meta_mode(pParam->bStoreMetaData)) { DEBUG_PRINT_ERROR("ERROR: set Metabuffer mode %d fail", pParam->bStoreMetaData); return OMX_ErrorUnsupportedSetting; } meta_mode_enable = pParam->bStoreMetaData; if (meta_mode_enable) { m_sInPortDef.nBufferCountActual = m_sInPortDef.nBufferCountMin; if (handle->venc_set_param(&m_sInPortDef,OMX_IndexParamPortDefinition) != true) { DEBUG_PRINT_ERROR("ERROR: venc_set_param input failed"); return OMX_ErrorUnsupportedSetting; } } else { /*TODO: reset encoder driver Meta mode*/ dev_get_buf_req (&m_sOutPortDef.nBufferCountMin, &m_sOutPortDef.nBufferCountActual, &m_sOutPortDef.nBufferSize, m_sOutPortDef.nPortIndex); } } } else if (pParam->nPortIndex == PORT_INDEX_OUT && secure_session) { if (pParam->bStoreMetaData != meta_mode_enable) { if (!handle->venc_set_meta_mode(pParam->bStoreMetaData)) { DEBUG_PRINT_ERROR("\nERROR: set Metabuffer mode %d fail", pParam->bStoreMetaData); return OMX_ErrorUnsupportedSetting; } meta_mode_enable = pParam->bStoreMetaData; } } else { DEBUG_PRINT_ERROR("set_parameter: metamode is " "valid for input port only"); eRet = OMX_ErrorUnsupportedIndex; } } break; #endif #if !defined(MAX_RES_720P) || defined(_MSM8974_) case OMX_QcomIndexParamIndexExtraDataType: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXEXTRADATATYPE); DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamIndexExtraDataType"); QOMX_INDEXEXTRADATATYPE *pParam = (QOMX_INDEXEXTRADATATYPE *)paramData; bool enable = false; OMX_U32 mask = 0; if (pParam->nIndex == (OMX_INDEXTYPE)OMX_ExtraDataVideoEncoderSliceInfo) { if (pParam->nPortIndex == PORT_INDEX_OUT) { mask = VEN_EXTRADATA_SLICEINFO; DEBUG_PRINT_HIGH("SliceInfo extradata %s", ((pParam->bEnabled == OMX_TRUE) ? "enabled" : "disabled")); } else { DEBUG_PRINT_ERROR("set_parameter: Slice information is " "valid for output port only"); eRet = OMX_ErrorUnsupportedIndex; break; } } else if (pParam->nIndex == (OMX_INDEXTYPE)OMX_ExtraDataVideoEncoderMBInfo) { if (pParam->nPortIndex == PORT_INDEX_OUT) { mask = VEN_EXTRADATA_MBINFO; DEBUG_PRINT_HIGH("MBInfo extradata %s", ((pParam->bEnabled == OMX_TRUE) ? "enabled" : "disabled")); } else { DEBUG_PRINT_ERROR("set_parameter: MB information is " "valid for output port only"); eRet = OMX_ErrorUnsupportedIndex; break; } } #ifndef _MSM8974_ else if (pParam->nIndex == (OMX_INDEXTYPE)OMX_ExtraDataVideoLTRInfo) { if (pParam->nPortIndex == PORT_INDEX_OUT) { if (pParam->bEnabled == OMX_TRUE) mask = VEN_EXTRADATA_LTRINFO; DEBUG_PRINT_HIGH("LTRInfo extradata %s", ((pParam->bEnabled == OMX_TRUE) ? "enabled" : "disabled")); } else { DEBUG_PRINT_ERROR("set_parameter: LTR information is " "valid for output port only"); eRet = OMX_ErrorUnsupportedIndex; break; } } #endif else { DEBUG_PRINT_ERROR("set_parameter: unsupported extrdata index (%x)", pParam->nIndex); eRet = OMX_ErrorUnsupportedIndex; break; } if (pParam->bEnabled == OMX_TRUE) m_sExtraData |= mask; else m_sExtraData &= ~mask; enable = !!(m_sExtraData & mask); if (handle->venc_set_param(&enable, (OMX_INDEXTYPE)pParam->nIndex) != true) { DEBUG_PRINT_ERROR("ERROR: Setting Extradata (%x) failed", pParam->nIndex); return OMX_ErrorUnsupportedSetting; } else { m_sOutPortDef.nPortIndex = PORT_INDEX_OUT; dev_get_buf_req(&m_sOutPortDef.nBufferCountMin, &m_sOutPortDef.nBufferCountActual, &m_sOutPortDef.nBufferSize, m_sOutPortDef.nPortIndex); DEBUG_PRINT_HIGH("updated out_buf_req: buffer cnt=%u, " "count min=%u, buffer size=%u", (unsigned int)m_sOutPortDef.nBufferCountActual, (unsigned int)m_sOutPortDef.nBufferCountMin, (unsigned int)m_sOutPortDef.nBufferSize); } break; } case QOMX_IndexParamVideoLTRMode: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_PARAM_LTRMODE_TYPE); QOMX_VIDEO_PARAM_LTRMODE_TYPE* pParam = (QOMX_VIDEO_PARAM_LTRMODE_TYPE*)paramData; if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)QOMX_IndexParamVideoLTRMode)) { DEBUG_PRINT_ERROR("ERROR: Setting LTR mode failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamLTRMode, pParam, sizeof(m_sParamLTRMode)); break; } case QOMX_IndexParamVideoLTRCount: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_PARAM_LTRCOUNT_TYPE); QOMX_VIDEO_PARAM_LTRCOUNT_TYPE* pParam = (QOMX_VIDEO_PARAM_LTRCOUNT_TYPE*)paramData; if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)QOMX_IndexParamVideoLTRCount)) { DEBUG_PRINT_ERROR("ERROR: Setting LTR count failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamLTRCount, pParam, sizeof(m_sParamLTRCount)); break; } #endif case OMX_QcomIndexParamVideoMaxAllowedBitrateCheck: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_EXTNINDEX_PARAMTYPE); QOMX_EXTNINDEX_PARAMTYPE* pParam = (QOMX_EXTNINDEX_PARAMTYPE*)paramData; if (pParam->nPortIndex == PORT_INDEX_OUT) { handle->m_max_allowed_bitrate_check = ((pParam->bEnable == OMX_TRUE) ? true : false); DEBUG_PRINT_HIGH("set_parameter: max allowed bitrate check %s", ((pParam->bEnable == OMX_TRUE) ? "enabled" : "disabled")); } else { DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexParamVideoMaxAllowedBitrateCheck " " called on wrong port(%u)", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } #ifdef MAX_RES_1080P case OMX_QcomIndexEnableSliceDeliveryMode: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_EXTNINDEX_PARAMTYPE); QOMX_EXTNINDEX_PARAMTYPE* pParam = (QOMX_EXTNINDEX_PARAMTYPE*)paramData; if (pParam->nPortIndex == PORT_INDEX_OUT) { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexEnableSliceDeliveryMode)) { DEBUG_PRINT_ERROR("ERROR: Request for setting slice delivery mode failed"); return OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexEnableSliceDeliveryMode " "called on wrong port(%u)", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } #endif case OMX_QcomIndexEnableH263PlusPType: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_EXTNINDEX_PARAMTYPE); QOMX_EXTNINDEX_PARAMTYPE* pParam = (QOMX_EXTNINDEX_PARAMTYPE*)paramData; DEBUG_PRINT_LOW("OMX_QcomIndexEnableH263PlusPType"); if (pParam->nPortIndex == PORT_INDEX_OUT) { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexEnableH263PlusPType)) { DEBUG_PRINT_ERROR("ERROR: Request for setting PlusPType failed"); return OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexEnableH263PlusPType " "called on wrong port(%u)", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexParamSequenceHeaderWithIDR: { VALIDATE_OMX_PARAM_DATA(paramData, PrependSPSPPSToIDRFramesParams); if(!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexParamSequenceHeaderWithIDR)) { DEBUG_PRINT_ERROR("%s: %s", "OMX_QComIndexParamSequenceHeaderWithIDR:", "request for inband sps/pps failed."); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamH264AUDelimiter: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_VIDEO_CONFIG_H264_AUD); if(!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexParamH264AUDelimiter)) { DEBUG_PRINT_ERROR("%s: %s", "OMX_QComIndexParamh264AUDelimiter:", "request for AU Delimiters failed."); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexHierarchicalStructure: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_HIERARCHICALLAYERS); QOMX_VIDEO_HIERARCHICALLAYERS* pParam = (QOMX_VIDEO_HIERARCHICALLAYERS*)paramData; DEBUG_PRINT_LOW("OMX_QcomIndexHierarchicalStructure"); if (pParam->nPortIndex == PORT_INDEX_OUT) { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexHierarchicalStructure)) { DEBUG_PRINT_ERROR("ERROR: Request for setting PlusPType failed"); return OMX_ErrorUnsupportedSetting; } if((pParam->eHierarchicalCodingType == QOMX_HIERARCHICALCODING_B) && pParam->nNumLayers) hier_b_enabled = true; m_sHierLayers.nNumLayers = pParam->nNumLayers; m_sHierLayers.eHierarchicalCodingType = pParam->eHierarchicalCodingType; } else { DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexHierarchicalStructure called on wrong port(%u)", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexParamPerfLevel: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_VIDEO_PARAM_PERF_LEVEL); if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE) OMX_QcomIndexParamPerfLevel)) { DEBUG_PRINT_ERROR("ERROR: Setting performance level"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamH264VUITimingInfo: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_VIDEO_PARAM_VUI_TIMING_INFO); if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE) OMX_QcomIndexParamH264VUITimingInfo)) { DEBUG_PRINT_ERROR("ERROR: Setting VUI timing info"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamPeakBitrate: { VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_VIDEO_PARAM_PEAK_BITRATE); if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE) OMX_QcomIndexParamPeakBitrate)) { DEBUG_PRINT_ERROR("ERROR: Setting peak bitrate"); return OMX_ErrorUnsupportedSetting; } break; } case QOMX_IndexParamVideoInitialQp: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_EXTNINDEX_VIDEO_INITIALQP); if(!handle->venc_set_param(paramData, (OMX_INDEXTYPE)QOMX_IndexParamVideoInitialQp)) { DEBUG_PRINT_ERROR("Request to Enable initial QP failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamInitqp, paramData, sizeof(m_sParamInitqp)); break; } case OMX_QcomIndexParamSetMVSearchrange: { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE) OMX_QcomIndexParamSetMVSearchrange)) { DEBUG_PRINT_ERROR("ERROR: Setting Searchrange"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamVideoHybridHierpMode: { VALIDATE_OMX_PARAM_DATA(paramData, QOMX_EXTNINDEX_VIDEO_HYBRID_HP_MODE); if(!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexParamVideoHybridHierpMode)) { DEBUG_PRINT_ERROR("Request to Enable Hybrid Hier-P failed"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_IndexParamVideoSliceFMO: default: { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown param %d", paramIndex); eRet = OMX_ErrorUnsupportedIndex; break; } } return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: add safety checks for freeing buffers Allow only up to 64 buffers on input/output port (since the allocation bitmap is only 64-wide). Add safety checks to free only as many buffers were allocated. Fixes: Heap Overflow and Possible Local Privilege Escalation in MediaServer (libOmxVenc problem) Bug: 27532497 Change-Id: I31e576ef9dc542df73aa6b0ea113d72724b50fc6 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 ssize_t generic_perform_write(struct file *file, struct iov_iter *i, loff_t pos) { struct address_space *mapping = file->f_mapping; const struct address_space_operations *a_ops = mapping->a_ops; long status = 0; ssize_t written = 0; unsigned int flags = 0; /* * Copies from kernel address space cannot fail (NFSD is a big user). */ if (segment_eq(get_fs(), KERNEL_DS)) flags |= AOP_FLAG_UNINTERRUPTIBLE; do { struct page *page; pgoff_t index; /* Pagecache index for current page */ unsigned long offset; /* Offset into pagecache page */ unsigned long bytes; /* Bytes to write to page */ size_t copied; /* Bytes copied from user */ void *fsdata; offset = (pos & (PAGE_CACHE_SIZE - 1)); index = pos >> PAGE_CACHE_SHIFT; bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset, iov_iter_count(i)); again: /* * Bring in the user page that we will copy from _first_. * Otherwise there's a nasty deadlock on copying from the * same page as we're writing to, without it being marked * up-to-date. * * Not only is this an optimisation, but it is also required * to check that the address is actually valid, when atomic * usercopies are used, below. */ if (unlikely(iov_iter_fault_in_readable(i, bytes))) { status = -EFAULT; break; } status = a_ops->write_begin(file, mapping, pos, bytes, flags, &page, &fsdata); if (unlikely(status)) break; pagefault_disable(); copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes); pagefault_enable(); flush_dcache_page(page); status = a_ops->write_end(file, mapping, pos, bytes, copied, page, fsdata); if (unlikely(status < 0)) break; copied = status; cond_resched(); if (unlikely(copied == 0)) { /* * If we were unable to copy any data at all, we must * fall back to a single segment length write. * * If we didn't fallback here, we could livelock * because not all segments in the iov can be copied at * once without a pagefault. */ bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset, iov_iter_single_seg_count(i)); goto again; } iov_iter_advance(i, copied); pos += copied; written += copied; balance_dirty_pages_ratelimited(mapping); } while (iov_iter_count(i)); return written ? written : status; } Commit Message: fix writev regression: pan hanging unkillable and un-straceable Frederik Himpe reported an unkillable and un-straceable pan process. Zero length iovecs can go into an infinite loop in writev, because the iovec iterator does not always advance over them. The sequence required to trigger this is not trivial. I think it requires that a zero-length iovec be followed by a non-zero-length iovec which causes a pagefault in the atomic usercopy. This causes the writev code to drop back into single-segment copy mode, which then tries to copy the 0 bytes of the zero-length iovec; a zero length copy looks like a failure though, so it loops. Put a test into iov_iter_advance to catch zero-length iovecs. We could just put the test in the fallback path, but I feel it is more robust to skip over zero-length iovecs throughout the code (iovec iterator may be used in filesystems too, so it should be robust). Signed-off-by: Nick Piggin <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: PrintMsg_Print_Params::~PrintMsg_Print_Params() {} 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: 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 buffer_head *isofs_bread(struct inode *inode, sector_t block) { sector_t blknr = isofs_bmap(inode, block); if (!blknr) return NULL; return sb_bread(inode->i_sb, blknr); } Commit Message: isofs: Fix unbounded recursion when processing relocated directories We did not check relocated directory in any way when processing Rock Ridge 'CL' tag. Thus a corrupted isofs image can possibly have a CL entry pointing to another CL entry leading to possibly unbounded recursion in kernel code and thus stack overflow or deadlocks (if there is a loop created from CL entries). Fix the problem by not allowing CL entry to point to a directory entry with CL entry (such use makes no good sense anyway) and by checking whether CL entry doesn't point to itself. CC: [email protected] Reported-by: Chris Evans <[email protected]> Signed-off-by: Jan Kara <[email protected]> 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 PrintWebViewHelper::UpdatePrintSettings( WebKit::WebFrame* frame, const WebKit::WebNode& node, const DictionaryValue& passed_job_settings) { DCHECK(is_preview_enabled_); const DictionaryValue* job_settings = &passed_job_settings; DictionaryValue modified_job_settings; if (job_settings->empty()) { if (!print_for_preview_) print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING); return false; } bool source_is_html = true; if (print_for_preview_) { if (!job_settings->GetBoolean(printing::kSettingPreviewModifiable, &source_is_html)) { NOTREACHED(); } } else { source_is_html = !PrintingNodeOrPdfFrame(frame, node); } if (print_for_preview_ || !source_is_html) { modified_job_settings.MergeDictionary(job_settings); modified_job_settings.SetBoolean(printing::kSettingHeaderFooterEnabled, false); modified_job_settings.SetInteger(printing::kSettingMarginsType, printing::NO_MARGINS); job_settings = &modified_job_settings; } int cookie = print_pages_params_.get() ? print_pages_params_->params.document_cookie : 0; PrintMsg_PrintPages_Params settings; Send(new PrintHostMsg_UpdatePrintSettings(routing_id(), cookie, *job_settings, &settings)); print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings)); if (!PrintMsg_Print_Params_IsValid(settings.params)) { if (!print_for_preview_) { print_preview_context_.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS); } else { WebKit::WebFrame* print_frame = NULL; GetPrintFrame(&print_frame); if (print_frame) { render_view()->RunModalAlertDialog( print_frame, l10n_util::GetStringUTF16( IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS)); } } return false; } if (settings.params.dpi < kMinDpi || !settings.params.document_cookie) { print_preview_context_.set_error(PREVIEW_ERROR_UPDATING_PRINT_SETTINGS); return false; } if (!print_for_preview_) { if (!job_settings->GetString(printing::kPreviewUIAddr, &(settings.params.preview_ui_addr)) || !job_settings->GetInteger(printing::kPreviewRequestID, &(settings.params.preview_request_id)) || !job_settings->GetBoolean(printing::kIsFirstRequest, &(settings.params.is_first_request))) { NOTREACHED(); print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING); return false; } settings.params.print_to_pdf = IsPrintToPdfRequested(*job_settings); UpdateFrameMarginsCssInfo(*job_settings); settings.params.print_scaling_option = GetPrintScalingOption( source_is_html, *job_settings, settings.params); if (settings.params.display_header_footer) { header_footer_info_.reset(new DictionaryValue()); header_footer_info_->SetString(printing::kSettingHeaderFooterDate, settings.params.date); header_footer_info_->SetString(printing::kSettingHeaderFooterURL, settings.params.url); header_footer_info_->SetString(printing::kSettingHeaderFooterTitle, settings.params.title); } } print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings)); Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(), settings.params.document_cookie)); return true; } 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: static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot) { if (!memslot->dirty_bitmap) return; kvm_kvfree(memslot->dirty_bitmap); memslot->dirty_bitmap = NULL; } Commit Message: KVM: perform an invalid memslot step for gpa base change PPC must flush all translations before the new memory slot is visible. Signed-off-by: Marcelo Tosatti <[email protected]> Signed-off-by: Avi Kivity <[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: void FeatureInfo::InitializeFeatures() { std::string extensions_string(gl::GetGLExtensionsFromCurrentContext()); gfx::ExtensionSet extensions(gfx::MakeExtensionSet(extensions_string)); const char* version_str = reinterpret_cast<const char*>(glGetString(GL_VERSION)); const char* renderer_str = reinterpret_cast<const char*>(glGetString(GL_RENDERER)); gl_version_info_.reset( new gl::GLVersionInfo(version_str, renderer_str, extensions)); bool enable_es3 = IsWebGL2OrES3OrHigherContext(); bool has_pixel_buffers = gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile || gfx::HasExtension(extensions, "GL_ARB_pixel_buffer_object") || gfx::HasExtension(extensions, "GL_NV_pixel_buffer_object"); ScopedPixelUnpackBufferOverride scoped_pbo_override(has_pixel_buffers, 0); AddExtensionString("GL_ANGLE_translated_shader_source"); AddExtensionString("GL_CHROMIUM_async_pixel_transfers"); AddExtensionString("GL_CHROMIUM_bind_uniform_location"); AddExtensionString("GL_CHROMIUM_color_space_metadata"); AddExtensionString("GL_CHROMIUM_command_buffer_query"); AddExtensionString("GL_CHROMIUM_command_buffer_latency_query"); AddExtensionString("GL_CHROMIUM_copy_texture"); AddExtensionString("GL_CHROMIUM_deschedule"); AddExtensionString("GL_CHROMIUM_get_error_query"); AddExtensionString("GL_CHROMIUM_lose_context"); AddExtensionString("GL_CHROMIUM_pixel_transfer_buffer_object"); AddExtensionString("GL_CHROMIUM_rate_limit_offscreen_context"); AddExtensionString("GL_CHROMIUM_resize"); AddExtensionString("GL_CHROMIUM_resource_safe"); AddExtensionString("GL_CHROMIUM_strict_attribs"); AddExtensionString("GL_CHROMIUM_texture_mailbox"); AddExtensionString("GL_CHROMIUM_trace_marker"); AddExtensionString("GL_EXT_debug_marker"); AddExtensionString("GL_EXT_unpack_subimage"); AddExtensionString("GL_OES_vertex_array_object"); if (gfx::HasExtension(extensions, "GL_ANGLE_translated_shader_source")) { feature_flags_.angle_translated_shader_source = true; } bool enable_dxt1 = false; bool enable_dxt3 = false; bool enable_dxt5 = false; bool have_s3tc = gfx::HasExtension(extensions, "GL_EXT_texture_compression_s3tc"); bool have_dxt3 = have_s3tc || gfx::HasExtension(extensions, "GL_ANGLE_texture_compression_dxt3"); bool have_dxt5 = have_s3tc || gfx::HasExtension(extensions, "GL_ANGLE_texture_compression_dxt5"); if (gfx::HasExtension(extensions, "GL_EXT_texture_compression_dxt1") || gfx::HasExtension(extensions, "GL_ANGLE_texture_compression_dxt1") || have_s3tc) { enable_dxt1 = true; } if (have_dxt3) { enable_dxt3 = true; } if (have_dxt5) { enable_dxt5 = true; } if (enable_dxt1) { feature_flags_.ext_texture_format_dxt1 = true; AddExtensionString("GL_ANGLE_texture_compression_dxt1"); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGB_S3TC_DXT1_EXT); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGBA_S3TC_DXT1_EXT); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_RGB_S3TC_DXT1_EXT); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_RGBA_S3TC_DXT1_EXT); } if (enable_dxt3) { AddExtensionString("GL_ANGLE_texture_compression_dxt3"); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGBA_S3TC_DXT3_EXT); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_RGBA_S3TC_DXT3_EXT); } if (enable_dxt5) { feature_flags_.ext_texture_format_dxt5 = true; AddExtensionString("GL_ANGLE_texture_compression_dxt5"); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGBA_S3TC_DXT5_EXT); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_RGBA_S3TC_DXT5_EXT); } bool have_astc = gfx::HasExtension(extensions, "GL_KHR_texture_compression_astc_ldr"); if (have_astc) { feature_flags_.ext_texture_format_astc = true; AddExtensionString("GL_KHR_texture_compression_astc_ldr"); GLint astc_format_it = GL_COMPRESSED_RGBA_ASTC_4x4_KHR; GLint astc_format_max = GL_COMPRESSED_RGBA_ASTC_12x12_KHR; for (; astc_format_it <= astc_format_max; astc_format_it++) { validators_.compressed_texture_format.AddValue(astc_format_it); validators_.texture_internal_format_storage.AddValue(astc_format_it); } astc_format_it = GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; astc_format_max = GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; for (; astc_format_it <= astc_format_max; astc_format_it++) { validators_.compressed_texture_format.AddValue(astc_format_it); validators_.texture_internal_format_storage.AddValue(astc_format_it); } } bool have_atc = gfx::HasExtension(extensions, "GL_AMD_compressed_ATC_texture") || gfx::HasExtension(extensions, "GL_ATI_texture_compression_atitc"); if (have_atc) { feature_flags_.ext_texture_format_atc = true; AddExtensionString("GL_AMD_compressed_ATC_texture"); validators_.compressed_texture_format.AddValue(GL_ATC_RGB_AMD); validators_.compressed_texture_format.AddValue( GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD); validators_.texture_internal_format_storage.AddValue(GL_ATC_RGB_AMD); validators_.texture_internal_format_storage.AddValue( GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD); } if (gfx::HasExtension(extensions, "GL_EXT_texture_filter_anisotropic")) { AddExtensionString("GL_EXT_texture_filter_anisotropic"); validators_.texture_parameter.AddValue(GL_TEXTURE_MAX_ANISOTROPY_EXT); validators_.g_l_state.AddValue(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT); } bool enable_depth_texture = false; GLenum depth_texture_format = GL_NONE; if (!workarounds_.disable_depth_texture && (gfx::HasExtension(extensions, "GL_ARB_depth_texture") || gfx::HasExtension(extensions, "GL_OES_depth_texture") || gfx::HasExtension(extensions, "GL_ANGLE_depth_texture") || gl_version_info_->is_desktop_core_profile)) { enable_depth_texture = true; depth_texture_format = GL_DEPTH_COMPONENT; feature_flags_.angle_depth_texture = gfx::HasExtension(extensions, "GL_ANGLE_depth_texture"); } if (enable_depth_texture) { AddExtensionString("GL_CHROMIUM_depth_texture"); AddExtensionString("GL_GOOGLE_depth_texture"); validators_.texture_internal_format.AddValue(GL_DEPTH_COMPONENT); validators_.texture_format.AddValue(GL_DEPTH_COMPONENT); validators_.pixel_type.AddValue(GL_UNSIGNED_SHORT); validators_.pixel_type.AddValue(GL_UNSIGNED_INT); validators_.texture_depth_renderable_internal_format.AddValue( GL_DEPTH_COMPONENT); } GLenum depth_stencil_texture_format = GL_NONE; if (gfx::HasExtension(extensions, "GL_EXT_packed_depth_stencil") || gfx::HasExtension(extensions, "GL_OES_packed_depth_stencil") || gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile) { AddExtensionString("GL_OES_packed_depth_stencil"); feature_flags_.packed_depth24_stencil8 = true; if (enable_depth_texture) { if (gl_version_info_->is_es3) { depth_stencil_texture_format = GL_DEPTH24_STENCIL8; } else { depth_stencil_texture_format = GL_DEPTH_STENCIL; } validators_.texture_internal_format.AddValue(GL_DEPTH_STENCIL); validators_.texture_format.AddValue(GL_DEPTH_STENCIL); validators_.pixel_type.AddValue(GL_UNSIGNED_INT_24_8); validators_.texture_depth_renderable_internal_format.AddValue( GL_DEPTH_STENCIL); validators_.texture_stencil_renderable_internal_format.AddValue( GL_DEPTH_STENCIL); } validators_.render_buffer_format.AddValue(GL_DEPTH24_STENCIL8); if (context_type_ == CONTEXT_TYPE_WEBGL1) { validators_.attachment.AddValue(GL_DEPTH_STENCIL_ATTACHMENT); validators_.attachment_query.AddValue(GL_DEPTH_STENCIL_ATTACHMENT); } } if (gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile || gfx::HasExtension(extensions, "GL_OES_vertex_array_object") || gfx::HasExtension(extensions, "GL_ARB_vertex_array_object") || gfx::HasExtension(extensions, "GL_APPLE_vertex_array_object")) { feature_flags_.native_vertex_array_object = true; } if (workarounds_.use_client_side_arrays_for_stream_buffers) { feature_flags_.native_vertex_array_object = false; } if (gl_version_info_->is_es3 || gfx::HasExtension(extensions, "GL_OES_element_index_uint") || gl::HasDesktopGLFeatures()) { AddExtensionString("GL_OES_element_index_uint"); validators_.index_type.AddValue(GL_UNSIGNED_INT); } bool has_srgb_framebuffer_support = false; if (gl_version_info_->IsAtLeastGL(3, 2) || (gl_version_info_->IsAtLeastGL(2, 0) && (gfx::HasExtension(extensions, "GL_EXT_framebuffer_sRGB") || gfx::HasExtension(extensions, "GL_ARB_framebuffer_sRGB")))) { feature_flags_.desktop_srgb_support = true; has_srgb_framebuffer_support = true; } if ((((gl_version_info_->is_es3 || gfx::HasExtension(extensions, "GL_OES_rgb8_rgba8")) && gfx::HasExtension(extensions, "GL_EXT_sRGB")) || feature_flags_.desktop_srgb_support) && IsWebGL1OrES2Context()) { feature_flags_.ext_srgb = true; AddExtensionString("GL_EXT_sRGB"); validators_.texture_internal_format.AddValue(GL_SRGB_EXT); validators_.texture_internal_format.AddValue(GL_SRGB_ALPHA_EXT); validators_.texture_format.AddValue(GL_SRGB_EXT); validators_.texture_format.AddValue(GL_SRGB_ALPHA_EXT); validators_.render_buffer_format.AddValue(GL_SRGB8_ALPHA8_EXT); validators_.framebuffer_attachment_parameter.AddValue( GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT); validators_.texture_unsized_internal_format.AddValue(GL_SRGB_EXT); validators_.texture_unsized_internal_format.AddValue(GL_SRGB_ALPHA_EXT); has_srgb_framebuffer_support = true; } if (gl_version_info_->is_es3) has_srgb_framebuffer_support = true; if (has_srgb_framebuffer_support && !IsWebGLContext()) { if (feature_flags_.desktop_srgb_support || gfx::HasExtension(extensions, "GL_EXT_sRGB_write_control")) { feature_flags_.ext_srgb_write_control = true; AddExtensionString("GL_EXT_sRGB_write_control"); validators_.capability.AddValue(GL_FRAMEBUFFER_SRGB_EXT); } } if (gfx::HasExtension(extensions, "GL_EXT_texture_sRGB_decode") && !IsWebGLContext()) { AddExtensionString("GL_EXT_texture_sRGB_decode"); validators_.texture_parameter.AddValue(GL_TEXTURE_SRGB_DECODE_EXT); } bool have_s3tc_srgb = false; if (gl_version_info_->is_es) { have_s3tc_srgb = gfx::HasExtension(extensions, "GL_NV_sRGB_formats") || gfx::HasExtension(extensions, "GL_EXT_texture_compression_s3tc_srgb"); } else { if (gfx::HasExtension(extensions, "GL_EXT_texture_sRGB") || gl_version_info_->IsAtLeastGL(4, 1)) { have_s3tc_srgb = gfx::HasExtension(extensions, "GL_EXT_texture_compression_s3tc"); } } if (have_s3tc_srgb) { AddExtensionString("GL_EXT_texture_compression_s3tc_srgb"); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_SRGB_S3TC_DXT1_EXT); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_SRGB_S3TC_DXT1_EXT); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT); } bool has_apple_bgra = gfx::HasExtension(extensions, "GL_APPLE_texture_format_BGRA8888"); bool has_ext_bgra = gfx::HasExtension(extensions, "GL_EXT_texture_format_BGRA8888"); bool enable_texture_format_bgra8888 = has_ext_bgra || has_apple_bgra || !gl_version_info_->is_es; bool has_ext_texture_storage = gfx::HasExtension(extensions, "GL_EXT_texture_storage"); bool has_arb_texture_storage = gfx::HasExtension(extensions, "GL_ARB_texture_storage"); bool has_texture_storage = !workarounds_.disable_texture_storage && (has_ext_texture_storage || has_arb_texture_storage || gl_version_info_->is_es3 || gl_version_info_->IsAtLeastGL(4, 2)); bool enable_texture_storage = has_texture_storage; bool texture_storage_incompatible_with_bgra = gl_version_info_->is_es3 && !has_ext_texture_storage && !has_apple_bgra; if (texture_storage_incompatible_with_bgra && enable_texture_format_bgra8888 && enable_texture_storage) { switch (context_type_) { case CONTEXT_TYPE_OPENGLES2: enable_texture_storage = false; break; case CONTEXT_TYPE_OPENGLES3: enable_texture_format_bgra8888 = false; break; case CONTEXT_TYPE_WEBGL1: case CONTEXT_TYPE_WEBGL2: case CONTEXT_TYPE_WEBGL2_COMPUTE: case CONTEXT_TYPE_WEBGPU: break; } } if (enable_texture_storage) { feature_flags_.ext_texture_storage = true; AddExtensionString("GL_EXT_texture_storage"); validators_.texture_parameter.AddValue(GL_TEXTURE_IMMUTABLE_FORMAT_EXT); } if (enable_texture_format_bgra8888) { feature_flags_.ext_texture_format_bgra8888 = true; AddExtensionString("GL_EXT_texture_format_BGRA8888"); validators_.texture_internal_format.AddValue(GL_BGRA_EXT); validators_.texture_format.AddValue(GL_BGRA_EXT); validators_.texture_unsized_internal_format.AddValue(GL_BGRA_EXT); validators_.texture_internal_format_storage.AddValue(GL_BGRA8_EXT); validators_.texture_sized_color_renderable_internal_format.AddValue( GL_BGRA8_EXT); validators_.texture_sized_texture_filterable_internal_format.AddValue( GL_BGRA8_EXT); feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::BGRA_8888); feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::BGRX_8888); } bool enable_render_buffer_bgra = gl_version_info_->is_angle || !gl_version_info_->is_es; if (enable_render_buffer_bgra) { feature_flags_.ext_render_buffer_format_bgra8888 = true; AddExtensionString("GL_CHROMIUM_renderbuffer_format_BGRA8888"); validators_.render_buffer_format.AddValue(GL_BGRA8_EXT); } bool enable_read_format_bgra = gfx::HasExtension(extensions, "GL_EXT_read_format_bgra") || !gl_version_info_->is_es; if (enable_read_format_bgra) { feature_flags_.ext_read_format_bgra = true; AddExtensionString("GL_EXT_read_format_bgra"); validators_.read_pixel_format.AddValue(GL_BGRA_EXT); } feature_flags_.arb_es3_compatibility = gfx::HasExtension(extensions, "GL_ARB_ES3_compatibility") && !gl_version_info_->is_es; feature_flags_.ext_disjoint_timer_query = gfx::HasExtension(extensions, "GL_EXT_disjoint_timer_query"); if (feature_flags_.ext_disjoint_timer_query || gfx::HasExtension(extensions, "GL_ARB_timer_query") || gfx::HasExtension(extensions, "GL_EXT_timer_query")) { AddExtensionString("GL_EXT_disjoint_timer_query"); } if (gfx::HasExtension(extensions, "GL_OES_rgb8_rgba8") || gl::HasDesktopGLFeatures()) { AddExtensionString("GL_OES_rgb8_rgba8"); validators_.render_buffer_format.AddValue(GL_RGB8_OES); validators_.render_buffer_format.AddValue(GL_RGBA8_OES); } if (!disallowed_features_.npot_support && (gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile || gfx::HasExtension(extensions, "GL_ARB_texture_non_power_of_two") || gfx::HasExtension(extensions, "GL_OES_texture_npot"))) { AddExtensionString("GL_OES_texture_npot"); feature_flags_.npot_ok = true; } InitializeFloatAndHalfFloatFeatures(extensions); if (!workarounds_.disable_chromium_framebuffer_multisample) { bool ext_has_multisample = gfx::HasExtension(extensions, "GL_ARB_framebuffer_object") || (gfx::HasExtension(extensions, "GL_EXT_framebuffer_multisample") && gfx::HasExtension(extensions, "GL_EXT_framebuffer_blit")) || gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile; if (gl_version_info_->is_angle || gl_version_info_->is_swiftshader) { ext_has_multisample |= gfx::HasExtension(extensions, "GL_ANGLE_framebuffer_multisample"); } if (ext_has_multisample) { feature_flags_.chromium_framebuffer_multisample = true; validators_.framebuffer_target.AddValue(GL_READ_FRAMEBUFFER_EXT); validators_.framebuffer_target.AddValue(GL_DRAW_FRAMEBUFFER_EXT); validators_.g_l_state.AddValue(GL_READ_FRAMEBUFFER_BINDING_EXT); validators_.g_l_state.AddValue(GL_MAX_SAMPLES_EXT); validators_.render_buffer_parameter.AddValue(GL_RENDERBUFFER_SAMPLES_EXT); AddExtensionString("GL_CHROMIUM_framebuffer_multisample"); } } if (gfx::HasExtension(extensions, "GL_EXT_multisampled_render_to_texture")) { feature_flags_.multisampled_render_to_texture = true; } else if (gfx::HasExtension(extensions, "GL_IMG_multisampled_render_to_texture")) { feature_flags_.multisampled_render_to_texture = true; feature_flags_.use_img_for_multisampled_render_to_texture = true; } if (feature_flags_.multisampled_render_to_texture) { validators_.render_buffer_parameter.AddValue(GL_RENDERBUFFER_SAMPLES_EXT); validators_.g_l_state.AddValue(GL_MAX_SAMPLES_EXT); validators_.framebuffer_attachment_parameter.AddValue( GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT); AddExtensionString("GL_EXT_multisampled_render_to_texture"); } if (!gl_version_info_->is_es || gfx::HasExtension(extensions, "GL_EXT_multisample_compatibility")) { AddExtensionString("GL_EXT_multisample_compatibility"); feature_flags_.ext_multisample_compatibility = true; validators_.capability.AddValue(GL_MULTISAMPLE_EXT); validators_.capability.AddValue(GL_SAMPLE_ALPHA_TO_ONE_EXT); } if (gfx::HasExtension(extensions, "GL_INTEL_framebuffer_CMAA")) { feature_flags_.chromium_screen_space_antialiasing = true; AddExtensionString("GL_CHROMIUM_screen_space_antialiasing"); } else if (gl_version_info_->IsAtLeastGLES(3, 1) || (gl_version_info_->IsAtLeastGL(3, 0) && gfx::HasExtension(extensions, "GL_ARB_shading_language_420pack") && gfx::HasExtension(extensions, "GL_ARB_texture_storage") && gfx::HasExtension(extensions, "GL_ARB_texture_gather") && gfx::HasExtension(extensions, "GL_ARB_explicit_uniform_location") && gfx::HasExtension(extensions, "GL_ARB_explicit_attrib_location") && gfx::HasExtension(extensions, "GL_ARB_shader_image_load_store"))) { feature_flags_.chromium_screen_space_antialiasing = true; feature_flags_.use_chromium_screen_space_antialiasing_via_shaders = true; AddExtensionString("GL_CHROMIUM_screen_space_antialiasing"); } if (gfx::HasExtension(extensions, "GL_OES_depth24") || gl::HasDesktopGLFeatures() || gl_version_info_->is_es3) { AddExtensionString("GL_OES_depth24"); feature_flags_.oes_depth24 = true; validators_.render_buffer_format.AddValue(GL_DEPTH_COMPONENT24); } if (gl_version_info_->is_es3 || gfx::HasExtension(extensions, "GL_OES_standard_derivatives") || gl::HasDesktopGLFeatures()) { AddExtensionString("GL_OES_standard_derivatives"); feature_flags_.oes_standard_derivatives = true; validators_.hint_target.AddValue(GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES); validators_.g_l_state.AddValue(GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES); } if (gfx::HasExtension(extensions, "GL_CHROMIUM_texture_filtering_hint")) { AddExtensionString("GL_CHROMIUM_texture_filtering_hint"); feature_flags_.chromium_texture_filtering_hint = true; validators_.hint_target.AddValue(GL_TEXTURE_FILTERING_HINT_CHROMIUM); validators_.g_l_state.AddValue(GL_TEXTURE_FILTERING_HINT_CHROMIUM); } if (gfx::HasExtension(extensions, "GL_OES_EGL_image_external")) { AddExtensionString("GL_OES_EGL_image_external"); feature_flags_.oes_egl_image_external = true; } if (gfx::HasExtension(extensions, "GL_NV_EGL_stream_consumer_external")) { AddExtensionString("GL_NV_EGL_stream_consumer_external"); feature_flags_.nv_egl_stream_consumer_external = true; } if (feature_flags_.oes_egl_image_external || feature_flags_.nv_egl_stream_consumer_external) { validators_.texture_bind_target.AddValue(GL_TEXTURE_EXTERNAL_OES); validators_.get_tex_param_target.AddValue(GL_TEXTURE_EXTERNAL_OES); validators_.texture_parameter.AddValue(GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES); validators_.g_l_state.AddValue(GL_TEXTURE_BINDING_EXTERNAL_OES); } if (gfx::HasExtension(extensions, "GL_OES_compressed_ETC1_RGB8_texture") && !gl_version_info_->is_angle) { AddExtensionString("GL_OES_compressed_ETC1_RGB8_texture"); feature_flags_.oes_compressed_etc1_rgb8_texture = true; validators_.compressed_texture_format.AddValue(GL_ETC1_RGB8_OES); validators_.texture_internal_format_storage.AddValue(GL_ETC1_RGB8_OES); } if (gfx::HasExtension(extensions, "GL_CHROMIUM_compressed_texture_etc") || (gl_version_info_->is_es3 && !gl_version_info_->is_angle)) { AddExtensionString("GL_CHROMIUM_compressed_texture_etc"); validators_.UpdateETCCompressedTextureFormats(); } if (gfx::HasExtension(extensions, "GL_AMD_compressed_ATC_texture")) { AddExtensionString("GL_AMD_compressed_ATC_texture"); validators_.compressed_texture_format.AddValue(GL_ATC_RGB_AMD); validators_.compressed_texture_format.AddValue( GL_ATC_RGBA_EXPLICIT_ALPHA_AMD); validators_.compressed_texture_format.AddValue( GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD); validators_.texture_internal_format_storage.AddValue(GL_ATC_RGB_AMD); validators_.texture_internal_format_storage.AddValue( GL_ATC_RGBA_EXPLICIT_ALPHA_AMD); validators_.texture_internal_format_storage.AddValue( GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD); } if (gfx::HasExtension(extensions, "GL_IMG_texture_compression_pvrtc")) { AddExtensionString("GL_IMG_texture_compression_pvrtc"); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG); validators_.texture_internal_format_storage.AddValue( GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG); } if (gfx::HasExtension(extensions, "GL_ARB_texture_rectangle") || gfx::HasExtension(extensions, "GL_ANGLE_texture_rectangle") || gl_version_info_->is_desktop_core_profile) { AddExtensionString("GL_ARB_texture_rectangle"); feature_flags_.arb_texture_rectangle = true; validators_.texture_bind_target.AddValue(GL_TEXTURE_RECTANGLE_ARB); validators_.texture_target.AddValue(GL_TEXTURE_RECTANGLE_ARB); validators_.get_tex_param_target.AddValue(GL_TEXTURE_RECTANGLE_ARB); validators_.g_l_state.AddValue(GL_TEXTURE_BINDING_RECTANGLE_ARB); } #if defined(OS_MACOSX) || defined(OS_CHROMEOS) AddExtensionString("GL_CHROMIUM_ycbcr_420v_image"); feature_flags_.chromium_image_ycbcr_420v = true; #endif if (feature_flags_.chromium_image_ycbcr_420v) { feature_flags_.gpu_memory_buffer_formats.Add( gfx::BufferFormat::YUV_420_BIPLANAR); } if (gfx::HasExtension(extensions, "GL_APPLE_ycbcr_422")) { AddExtensionString("GL_CHROMIUM_ycbcr_422_image"); feature_flags_.chromium_image_ycbcr_422 = true; feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::UYVY_422); } #if defined(OS_MACOSX) feature_flags_.chromium_image_xr30 = base::mac::IsAtLeastOS10_13(); #elif !defined(OS_WIN) feature_flags_.chromium_image_xb30 = gl_version_info_->IsAtLeastGL(3, 3) || gl_version_info_->IsAtLeastGLES(3, 0) || gfx::HasExtension(extensions, "GL_EXT_texture_type_2_10_10_10_REV"); #endif if (feature_flags_.chromium_image_xr30 || feature_flags_.chromium_image_xb30) { validators_.texture_internal_format.AddValue(GL_RGB10_A2_EXT); validators_.render_buffer_format.AddValue(GL_RGB10_A2_EXT); validators_.texture_internal_format_storage.AddValue(GL_RGB10_A2_EXT); validators_.pixel_type.AddValue(GL_UNSIGNED_INT_2_10_10_10_REV); } if (feature_flags_.chromium_image_xr30) { feature_flags_.gpu_memory_buffer_formats.Add( gfx::BufferFormat::BGRX_1010102); } if (feature_flags_.chromium_image_xb30) { feature_flags_.gpu_memory_buffer_formats.Add( gfx::BufferFormat::RGBX_1010102); } if (gfx::HasExtension(extensions, "GL_ANGLE_texture_usage")) { feature_flags_.angle_texture_usage = true; AddExtensionString("GL_ANGLE_texture_usage"); validators_.texture_parameter.AddValue(GL_TEXTURE_USAGE_ANGLE); } bool have_occlusion_query = gl_version_info_->IsAtLeastGLES(3, 0) || gl_version_info_->IsAtLeastGL(3, 3); bool have_ext_occlusion_query_boolean = gfx::HasExtension(extensions, "GL_EXT_occlusion_query_boolean"); bool have_arb_occlusion_query2 = gfx::HasExtension(extensions, "GL_ARB_occlusion_query2"); bool have_arb_occlusion_query = (gl_version_info_->is_desktop_core_profile && gl_version_info_->IsAtLeastGL(1, 5)) || gfx::HasExtension(extensions, "GL_ARB_occlusion_query"); if (have_occlusion_query || have_ext_occlusion_query_boolean || have_arb_occlusion_query2 || have_arb_occlusion_query) { feature_flags_.occlusion_query = have_arb_occlusion_query; if (context_type_ == CONTEXT_TYPE_OPENGLES2) { AddExtensionString("GL_EXT_occlusion_query_boolean"); } feature_flags_.occlusion_query_boolean = true; feature_flags_.use_arb_occlusion_query2_for_occlusion_query_boolean = !have_ext_occlusion_query_boolean && (have_arb_occlusion_query2 || (gl_version_info_->IsAtLeastGL(3, 3) && gl_version_info_->IsLowerThanGL(4, 3))); feature_flags_.use_arb_occlusion_query_for_occlusion_query_boolean = !have_ext_occlusion_query_boolean && have_arb_occlusion_query && !have_arb_occlusion_query2; } if (gfx::HasExtension(extensions, "GL_ANGLE_instanced_arrays") || (gfx::HasExtension(extensions, "GL_ARB_instanced_arrays") && gfx::HasExtension(extensions, "GL_ARB_draw_instanced")) || gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile) { AddExtensionString("GL_ANGLE_instanced_arrays"); feature_flags_.angle_instanced_arrays = true; validators_.vertex_attribute.AddValue(GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE); } bool have_es2_draw_buffers_vendor_agnostic = gl_version_info_->is_desktop_core_profile || gfx::HasExtension(extensions, "GL_ARB_draw_buffers") || gfx::HasExtension(extensions, "GL_EXT_draw_buffers"); bool can_emulate_es2_draw_buffers_on_es3_nv = gl_version_info_->is_es3 && gfx::HasExtension(extensions, "GL_NV_draw_buffers"); bool is_webgl_compatibility_context = gfx::HasExtension(extensions, "GL_ANGLE_webgl_compatibility"); bool have_es2_draw_buffers = !workarounds_.disable_ext_draw_buffers && (have_es2_draw_buffers_vendor_agnostic || can_emulate_es2_draw_buffers_on_es3_nv) && (context_type_ == CONTEXT_TYPE_OPENGLES2 || (context_type_ == CONTEXT_TYPE_WEBGL1 && IsWebGLDrawBuffersSupported(is_webgl_compatibility_context, depth_texture_format, depth_stencil_texture_format))); if (have_es2_draw_buffers) { AddExtensionString("GL_EXT_draw_buffers"); feature_flags_.ext_draw_buffers = true; feature_flags_.nv_draw_buffers = can_emulate_es2_draw_buffers_on_es3_nv && !have_es2_draw_buffers_vendor_agnostic; } if (IsWebGL2OrES3OrHigherContext() || have_es2_draw_buffers) { GLint max_color_attachments = 0; glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &max_color_attachments); for (GLenum i = GL_COLOR_ATTACHMENT1_EXT; i < static_cast<GLenum>(GL_COLOR_ATTACHMENT0 + max_color_attachments); ++i) { validators_.attachment.AddValue(i); validators_.attachment_query.AddValue(i); } static_assert(GL_COLOR_ATTACHMENT0_EXT == GL_COLOR_ATTACHMENT0, "GL_COLOR_ATTACHMENT0_EXT should equal GL_COLOR_ATTACHMENT0"); validators_.g_l_state.AddValue(GL_MAX_COLOR_ATTACHMENTS_EXT); validators_.g_l_state.AddValue(GL_MAX_DRAW_BUFFERS_ARB); GLint max_draw_buffers = 0; glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &max_draw_buffers); for (GLenum i = GL_DRAW_BUFFER0_ARB; i < static_cast<GLenum>(GL_DRAW_BUFFER0_ARB + max_draw_buffers); ++i) { validators_.g_l_state.AddValue(i); } } if (gl_version_info_->is_es3 || gfx::HasExtension(extensions, "GL_EXT_blend_minmax") || gl::HasDesktopGLFeatures()) { AddExtensionString("GL_EXT_blend_minmax"); validators_.equation.AddValue(GL_MIN_EXT); validators_.equation.AddValue(GL_MAX_EXT); static_assert(GL_MIN_EXT == GL_MIN && GL_MAX_EXT == GL_MAX, "min & max variations must match"); } if (gfx::HasExtension(extensions, "GL_EXT_frag_depth") || gl::HasDesktopGLFeatures()) { AddExtensionString("GL_EXT_frag_depth"); feature_flags_.ext_frag_depth = true; } if (gfx::HasExtension(extensions, "GL_EXT_shader_texture_lod") || gl::HasDesktopGLFeatures()) { AddExtensionString("GL_EXT_shader_texture_lod"); feature_flags_.ext_shader_texture_lod = true; } bool ui_gl_fence_works = gl::GLFence::IsSupported(); UMA_HISTOGRAM_BOOLEAN("GPU.FenceSupport", ui_gl_fence_works); feature_flags_.map_buffer_range = gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile || gfx::HasExtension(extensions, "GL_ARB_map_buffer_range") || gfx::HasExtension(extensions, "GL_EXT_map_buffer_range"); if (has_pixel_buffers && ui_gl_fence_works && !workarounds_.disable_async_readpixels) { feature_flags_.use_async_readpixels = true; } if (gl_version_info_->is_es3 || gfx::HasExtension(extensions, "GL_ARB_sampler_objects")) { feature_flags_.enable_samplers = true; } if ((gl_version_info_->is_es3 || gfx::HasExtension(extensions, "GL_EXT_discard_framebuffer")) && !workarounds_.disable_discard_framebuffer) { AddExtensionString("GL_EXT_discard_framebuffer"); feature_flags_.ext_discard_framebuffer = true; } if (ui_gl_fence_works) { AddExtensionString("GL_CHROMIUM_sync_query"); feature_flags_.chromium_sync_query = true; } if (!workarounds_.disable_blend_equation_advanced) { bool blend_equation_advanced_coherent = gfx::HasExtension(extensions, "GL_NV_blend_equation_advanced_coherent") || gfx::HasExtension(extensions, "GL_KHR_blend_equation_advanced_coherent"); if (blend_equation_advanced_coherent || gfx::HasExtension(extensions, "GL_NV_blend_equation_advanced") || gfx::HasExtension(extensions, "GL_KHR_blend_equation_advanced")) { const GLenum equations[] = { GL_MULTIPLY_KHR, GL_SCREEN_KHR, GL_OVERLAY_KHR, GL_DARKEN_KHR, GL_LIGHTEN_KHR, GL_COLORDODGE_KHR, GL_COLORBURN_KHR, GL_HARDLIGHT_KHR, GL_SOFTLIGHT_KHR, GL_DIFFERENCE_KHR, GL_EXCLUSION_KHR, GL_HSL_HUE_KHR, GL_HSL_SATURATION_KHR, GL_HSL_COLOR_KHR, GL_HSL_LUMINOSITY_KHR}; for (GLenum equation : equations) validators_.equation.AddValue(equation); if (blend_equation_advanced_coherent) AddExtensionString("GL_KHR_blend_equation_advanced_coherent"); AddExtensionString("GL_KHR_blend_equation_advanced"); feature_flags_.blend_equation_advanced = true; feature_flags_.blend_equation_advanced_coherent = blend_equation_advanced_coherent; } } if (gfx::HasExtension(extensions, "GL_NV_framebuffer_mixed_samples")) { AddExtensionString("GL_CHROMIUM_framebuffer_mixed_samples"); feature_flags_.chromium_framebuffer_mixed_samples = true; validators_.g_l_state.AddValue(GL_COVERAGE_MODULATION_CHROMIUM); } if (gfx::HasExtension(extensions, "GL_NV_path_rendering")) { bool has_dsa = gl_version_info_->IsAtLeastGL(4, 5) || gfx::HasExtension(extensions, "GL_EXT_direct_state_access"); bool has_piq = gl_version_info_->IsAtLeastGL(4, 3) || gfx::HasExtension(extensions, "GL_ARB_program_interface_query"); bool has_fms = feature_flags_.chromium_framebuffer_mixed_samples; if ((gl_version_info_->IsAtLeastGLES(3, 1) || (gl_version_info_->IsAtLeastGL(3, 2) && has_dsa && has_piq)) && has_fms) { AddExtensionString("GL_CHROMIUM_path_rendering"); feature_flags_.chromium_path_rendering = true; validators_.g_l_state.AddValue(GL_PATH_MODELVIEW_MATRIX_CHROMIUM); validators_.g_l_state.AddValue(GL_PATH_PROJECTION_MATRIX_CHROMIUM); validators_.g_l_state.AddValue(GL_PATH_STENCIL_FUNC_CHROMIUM); validators_.g_l_state.AddValue(GL_PATH_STENCIL_REF_CHROMIUM); validators_.g_l_state.AddValue(GL_PATH_STENCIL_VALUE_MASK_CHROMIUM); } } if ((gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile || gfx::HasExtension(extensions, "GL_EXT_texture_rg") || gfx::HasExtension(extensions, "GL_ARB_texture_rg")) && IsGL_REDSupportedOnFBOs()) { feature_flags_.ext_texture_rg = true; AddExtensionString("GL_EXT_texture_rg"); validators_.texture_format.AddValue(GL_RED_EXT); validators_.texture_format.AddValue(GL_RG_EXT); validators_.texture_internal_format.AddValue(GL_RED_EXT); validators_.texture_internal_format.AddValue(GL_R8_EXT); validators_.texture_internal_format.AddValue(GL_RG_EXT); validators_.texture_internal_format.AddValue(GL_RG8_EXT); validators_.read_pixel_format.AddValue(GL_RED_EXT); validators_.read_pixel_format.AddValue(GL_RG_EXT); validators_.render_buffer_format.AddValue(GL_R8_EXT); validators_.render_buffer_format.AddValue(GL_RG8_EXT); validators_.texture_unsized_internal_format.AddValue(GL_RED_EXT); validators_.texture_unsized_internal_format.AddValue(GL_RG_EXT); validators_.texture_internal_format_storage.AddValue(GL_R8_EXT); validators_.texture_internal_format_storage.AddValue(GL_RG8_EXT); feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::R_8); feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::RG_88); } UMA_HISTOGRAM_BOOLEAN("GPU.TextureRG", feature_flags_.ext_texture_rg); if (gl_version_info_->is_desktop_core_profile || (gl_version_info_->IsAtLeastGL(2, 1) && gfx::HasExtension(extensions, "GL_ARB_texture_rg")) || gfx::HasExtension(extensions, "GL_EXT_texture_norm16")) { feature_flags_.ext_texture_norm16 = true; g_r16_is_present = true; validators_.pixel_type.AddValue(GL_UNSIGNED_SHORT); validators_.texture_format.AddValue(GL_RED_EXT); validators_.texture_internal_format.AddValue(GL_R16_EXT); validators_.texture_internal_format.AddValue(GL_RED_EXT); validators_.texture_unsized_internal_format.AddValue(GL_RED_EXT); validators_.texture_internal_format_storage.AddValue(GL_R16_EXT); feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::R_16); } UMA_HISTOGRAM_ENUMERATION( "GPU.TextureR16Ext_LuminanceF16", GpuTextureUMAHelper(), static_cast<int>(GpuTextureResultR16_L16::kMax) + 1); if (enable_es3 && gfx::HasExtension(extensions, "GL_EXT_window_rectangles")) { AddExtensionString("GL_EXT_window_rectangles"); feature_flags_.ext_window_rectangles = true; validators_.g_l_state.AddValue(GL_WINDOW_RECTANGLE_MODE_EXT); validators_.g_l_state.AddValue(GL_MAX_WINDOW_RECTANGLES_EXT); validators_.g_l_state.AddValue(GL_NUM_WINDOW_RECTANGLES_EXT); validators_.indexed_g_l_state.AddValue(GL_WINDOW_RECTANGLE_EXT); } bool has_opengl_dual_source_blending = gl_version_info_->IsAtLeastGL(3, 3) || (gl_version_info_->IsAtLeastGL(3, 2) && gfx::HasExtension(extensions, "GL_ARB_blend_func_extended")); if (!disable_shader_translator_ && !workarounds_.get_frag_data_info_bug && ((gl_version_info_->IsAtLeastGL(3, 2) && has_opengl_dual_source_blending) || (gl_version_info_->IsAtLeastGLES(3, 0) && gfx::HasExtension(extensions, "GL_EXT_blend_func_extended")))) { feature_flags_.ext_blend_func_extended = true; AddExtensionString("GL_EXT_blend_func_extended"); validators_.dst_blend_factor.AddValue(GL_SRC_ALPHA_SATURATE_EXT); validators_.src_blend_factor.AddValue(GL_SRC1_ALPHA_EXT); validators_.dst_blend_factor.AddValue(GL_SRC1_ALPHA_EXT); validators_.src_blend_factor.AddValue(GL_SRC1_COLOR_EXT); validators_.dst_blend_factor.AddValue(GL_SRC1_COLOR_EXT); validators_.src_blend_factor.AddValue(GL_ONE_MINUS_SRC1_COLOR_EXT); validators_.dst_blend_factor.AddValue(GL_ONE_MINUS_SRC1_COLOR_EXT); validators_.src_blend_factor.AddValue(GL_ONE_MINUS_SRC1_ALPHA_EXT); validators_.dst_blend_factor.AddValue(GL_ONE_MINUS_SRC1_ALPHA_EXT); validators_.g_l_state.AddValue(GL_MAX_DUAL_SOURCE_DRAW_BUFFERS_EXT); } #if !defined(OS_MACOSX) if (workarounds_.ignore_egl_sync_failures) { gl::GLFenceEGL::SetIgnoreFailures(); } #endif if (workarounds_.avoid_egl_image_target_texture_reuse) { TextureDefinition::AvoidEGLTargetTextureReuse(); } if (gl_version_info_->IsLowerThanGL(4, 3)) { feature_flags_.emulate_primitive_restart_fixed_index = true; } feature_flags_.angle_robust_client_memory = gfx::HasExtension(extensions, "GL_ANGLE_robust_client_memory"); feature_flags_.khr_debug = gl_version_info_->IsAtLeastGL(4, 3) || gl_version_info_->IsAtLeastGLES(3, 2) || gfx::HasExtension(extensions, "GL_KHR_debug"); feature_flags_.chromium_gpu_fence = gl::GLFence::IsGpuFenceSupported(); if (feature_flags_.chromium_gpu_fence) AddExtensionString("GL_CHROMIUM_gpu_fence"); feature_flags_.chromium_bind_generates_resource = gfx::HasExtension(extensions, "GL_CHROMIUM_bind_generates_resource"); feature_flags_.angle_webgl_compatibility = is_webgl_compatibility_context; feature_flags_.chromium_copy_texture = gfx::HasExtension(extensions, "GL_CHROMIUM_copy_texture"); feature_flags_.chromium_copy_compressed_texture = gfx::HasExtension(extensions, "GL_CHROMIUM_copy_compressed_texture"); feature_flags_.angle_client_arrays = gfx::HasExtension(extensions, "GL_ANGLE_client_arrays"); feature_flags_.angle_request_extension = gfx::HasExtension(extensions, "GL_ANGLE_request_extension"); feature_flags_.ext_debug_marker = gfx::HasExtension(extensions, "GL_EXT_debug_marker"); feature_flags_.arb_robustness = gfx::HasExtension(extensions, "GL_ARB_robustness"); feature_flags_.khr_robustness = gfx::HasExtension(extensions, "GL_KHR_robustness"); feature_flags_.ext_robustness = gfx::HasExtension(extensions, "GL_EXT_robustness"); feature_flags_.ext_pixel_buffer_object = gfx::HasExtension(extensions, "GL_ARB_pixel_buffer_object") || gfx::HasExtension(extensions, "GL_NV_pixel_buffer_object"); feature_flags_.ext_unpack_subimage = gfx::HasExtension(extensions, "GL_EXT_unpack_subimage"); feature_flags_.oes_rgb8_rgba8 = gfx::HasExtension(extensions, "GL_OES_rgb8_rgba8"); feature_flags_.angle_robust_resource_initialization = gfx::HasExtension(extensions, "GL_ANGLE_robust_resource_initialization"); feature_flags_.nv_fence = gfx::HasExtension(extensions, "GL_NV_fence"); feature_flags_.unpremultiply_and_dither_copy = !is_passthrough_cmd_decoder_; if (feature_flags_.unpremultiply_and_dither_copy) AddExtensionString("GL_CHROMIUM_unpremultiply_and_dither_copy"); feature_flags_.separate_stencil_ref_mask_writemask = !(gl_version_info_->is_d3d) && !IsWebGLContext(); if (gfx::HasExtension(extensions, "GL_MESA_framebuffer_flip_y")) { feature_flags_.mesa_framebuffer_flip_y = true; validators_.framebuffer_parameter.AddValue(GL_FRAMEBUFFER_FLIP_Y_MESA); AddExtensionString("GL_MESA_framebuffer_flip_y"); } if (is_passthrough_cmd_decoder_ && gfx::HasExtension(extensions, "GL_OVR_multiview2")) { AddExtensionString("GL_OVR_multiview2"); feature_flags_.ovr_multiview2 = true; } if (is_passthrough_cmd_decoder_ && gfx::HasExtension(extensions, "GL_KHR_parallel_shader_compile")) { AddExtensionString("GL_KHR_parallel_shader_compile"); feature_flags_.khr_parallel_shader_compile = true; validators_.g_l_state.AddValue(GL_MAX_SHADER_COMPILER_THREADS_KHR); validators_.shader_parameter.AddValue(GL_COMPLETION_STATUS_KHR); validators_.program_parameter.AddValue(GL_COMPLETION_STATUS_KHR); } if (gfx::HasExtension(extensions, "GL_KHR_robust_buffer_access_behavior")) { AddExtensionString("GL_KHR_robust_buffer_access_behavior"); feature_flags_.khr_robust_buffer_access_behavior = true; } if (!is_passthrough_cmd_decoder_ || gfx::HasExtension(extensions, "GL_ANGLE_multi_draw")) { feature_flags_.webgl_multi_draw = true; AddExtensionString("GL_WEBGL_multi_draw"); if (gfx::HasExtension(extensions, "GL_ANGLE_instanced_arrays") || feature_flags_.angle_instanced_arrays || gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile) { feature_flags_.webgl_multi_draw_instanced = true; AddExtensionString("GL_WEBGL_multi_draw_instanced"); } } if (gfx::HasExtension(extensions, "GL_NV_internalformat_sample_query")) { feature_flags_.nv_internalformat_sample_query = true; } if (gfx::HasExtension(extensions, "GL_AMD_framebuffer_multisample_advanced")) { feature_flags_.amd_framebuffer_multisample_advanced = true; AddExtensionString("GL_AMD_framebuffer_multisample_advanced"); } } 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:
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 IsTraceEventArgsWhitelisted(const char* category_group_name, const char* event_name) { if (base::MatchPattern(category_group_name, "benchmark") && base::MatchPattern(event_name, "whitelisted")) { return true; } return false; } 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 int check_firmware(struct dvb_frontend *fe, unsigned int type, v4l2_std_id std, __u16 int_freq) { struct xc2028_data *priv = fe->tuner_priv; struct firmware_properties new_fw; int rc, retry_count = 0; u16 version, hwmodel; v4l2_std_id std0; tuner_dbg("%s called\n", __func__); rc = check_device_status(priv); if (rc < 0) return rc; if (priv->ctrl.mts && !(type & FM)) type |= MTS; retry: new_fw.type = type; new_fw.id = std; new_fw.std_req = std; new_fw.scode_table = SCODE | priv->ctrl.scode_table; new_fw.scode_nr = 0; new_fw.int_freq = int_freq; tuner_dbg("checking firmware, user requested type="); if (debug) { dump_firm_type(new_fw.type); printk("(%x), id %016llx, ", new_fw.type, (unsigned long long)new_fw.std_req); if (!int_freq) { printk("scode_tbl "); dump_firm_type(priv->ctrl.scode_table); printk("(%x), ", priv->ctrl.scode_table); } else printk("int_freq %d, ", new_fw.int_freq); printk("scode_nr %d\n", new_fw.scode_nr); } /* * No need to reload base firmware if it matches and if the tuner * is not at sleep mode */ if ((priv->state == XC2028_ACTIVE) && (((BASE | new_fw.type) & BASE_TYPES) == (priv->cur_fw.type & BASE_TYPES))) { tuner_dbg("BASE firmware not changed.\n"); goto skip_base; } /* Updating BASE - forget about all currently loaded firmware */ memset(&priv->cur_fw, 0, sizeof(priv->cur_fw)); /* Reset is needed before loading firmware */ rc = do_tuner_callback(fe, XC2028_TUNER_RESET, 0); if (rc < 0) goto fail; /* BASE firmwares are all std0 */ std0 = 0; rc = load_firmware(fe, BASE | new_fw.type, &std0); if (rc < 0) { tuner_err("Error %d while loading base firmware\n", rc); goto fail; } /* Load INIT1, if needed */ tuner_dbg("Load init1 firmware, if exists\n"); rc = load_firmware(fe, BASE | INIT1 | new_fw.type, &std0); if (rc == -ENOENT) rc = load_firmware(fe, (BASE | INIT1 | new_fw.type) & ~F8MHZ, &std0); if (rc < 0 && rc != -ENOENT) { tuner_err("Error %d while loading init1 firmware\n", rc); goto fail; } skip_base: /* * No need to reload standard specific firmware if base firmware * was not reloaded and requested video standards have not changed. */ if (priv->cur_fw.type == (BASE | new_fw.type) && priv->cur_fw.std_req == std) { tuner_dbg("Std-specific firmware already loaded.\n"); goto skip_std_specific; } /* Reloading std-specific firmware forces a SCODE update */ priv->cur_fw.scode_table = 0; rc = load_firmware(fe, new_fw.type, &new_fw.id); if (rc == -ENOENT) rc = load_firmware(fe, new_fw.type & ~F8MHZ, &new_fw.id); if (rc < 0) goto fail; skip_std_specific: if (priv->cur_fw.scode_table == new_fw.scode_table && priv->cur_fw.scode_nr == new_fw.scode_nr) { tuner_dbg("SCODE firmware already loaded.\n"); goto check_device; } if (new_fw.type & FM) goto check_device; /* Load SCODE firmware, if exists */ tuner_dbg("Trying to load scode %d\n", new_fw.scode_nr); rc = load_scode(fe, new_fw.type | new_fw.scode_table, &new_fw.id, new_fw.int_freq, new_fw.scode_nr); check_device: if (xc2028_get_reg(priv, 0x0004, &version) < 0 || xc2028_get_reg(priv, 0x0008, &hwmodel) < 0) { tuner_err("Unable to read tuner registers.\n"); goto fail; } tuner_dbg("Device is Xceive %d version %d.%d, " "firmware version %d.%d\n", hwmodel, (version & 0xf000) >> 12, (version & 0xf00) >> 8, (version & 0xf0) >> 4, version & 0xf); if (priv->ctrl.read_not_reliable) goto read_not_reliable; /* Check firmware version against what we downloaded. */ if (priv->firm_version != ((version & 0xf0) << 4 | (version & 0x0f))) { if (!priv->ctrl.read_not_reliable) { tuner_err("Incorrect readback of firmware version.\n"); goto fail; } else { tuner_err("Returned an incorrect version. However, " "read is not reliable enough. Ignoring it.\n"); hwmodel = 3028; } } /* Check that the tuner hardware model remains consistent over time. */ if (priv->hwmodel == 0 && (hwmodel == 2028 || hwmodel == 3028)) { priv->hwmodel = hwmodel; priv->hwvers = version & 0xff00; } else if (priv->hwmodel == 0 || priv->hwmodel != hwmodel || priv->hwvers != (version & 0xff00)) { tuner_err("Read invalid device hardware information - tuner " "hung?\n"); goto fail; } read_not_reliable: priv->cur_fw = new_fw; /* * By setting BASE in cur_fw.type only after successfully loading all * firmwares, we can: * 1. Identify that BASE firmware with type=0 has been loaded; * 2. Tell whether BASE firmware was just changed the next time through. */ priv->cur_fw.type |= BASE; priv->state = XC2028_ACTIVE; return 0; fail: priv->state = XC2028_NO_FIRMWARE; memset(&priv->cur_fw, 0, sizeof(priv->cur_fw)); if (retry_count < 8) { msleep(50); retry_count++; tuner_dbg("Retrying firmware load\n"); goto retry; } /* Firmware didn't load. Put the device to sleep */ xc2028_sleep(fe); if (rc == -ENOENT) rc = -EINVAL; return rc; } Commit Message: [media] xc2028: avoid use after free If struct xc2028_config is passed without a firmware name, the following trouble may happen: [11009.907205] xc2028 5-0061: type set to XCeive xc2028/xc3028 tuner [11009.907491] ================================================================== [11009.907750] BUG: KASAN: use-after-free in strcmp+0x96/0xb0 at addr ffff8803bd78ab40 [11009.907992] Read of size 1 by task modprobe/28992 [11009.907994] ============================================================================= [11009.907997] BUG kmalloc-16 (Tainted: G W ): kasan: bad access detected [11009.907999] ----------------------------------------------------------------------------- [11009.908008] INFO: Allocated in xhci_urb_enqueue+0x214/0x14c0 [xhci_hcd] age=0 cpu=3 pid=28992 [11009.908012] ___slab_alloc+0x581/0x5b0 [11009.908014] __slab_alloc+0x51/0x90 [11009.908017] __kmalloc+0x27b/0x350 [11009.908022] xhci_urb_enqueue+0x214/0x14c0 [xhci_hcd] [11009.908026] usb_hcd_submit_urb+0x1e8/0x1c60 [11009.908029] usb_submit_urb+0xb0e/0x1200 [11009.908032] usb_serial_generic_write_start+0xb6/0x4c0 [11009.908035] usb_serial_generic_write+0x92/0xc0 [11009.908039] usb_console_write+0x38a/0x560 [11009.908045] call_console_drivers.constprop.14+0x1ee/0x2c0 [11009.908051] console_unlock+0x40d/0x900 [11009.908056] vprintk_emit+0x4b4/0x830 [11009.908061] vprintk_default+0x1f/0x30 [11009.908064] printk+0x99/0xb5 [11009.908067] kasan_report_error+0x10a/0x550 [11009.908070] __asan_report_load1_noabort+0x43/0x50 [11009.908074] INFO: Freed in xc2028_set_config+0x90/0x630 [tuner_xc2028] age=1 cpu=3 pid=28992 [11009.908077] __slab_free+0x2ec/0x460 [11009.908080] kfree+0x266/0x280 [11009.908083] xc2028_set_config+0x90/0x630 [tuner_xc2028] [11009.908086] xc2028_attach+0x310/0x8a0 [tuner_xc2028] [11009.908090] em28xx_attach_xc3028.constprop.7+0x1f9/0x30d [em28xx_dvb] [11009.908094] em28xx_dvb_init.part.3+0x8e4/0x5cf4 [em28xx_dvb] [11009.908098] em28xx_dvb_init+0x81/0x8a [em28xx_dvb] [11009.908101] em28xx_register_extension+0xd9/0x190 [em28xx] [11009.908105] em28xx_dvb_register+0x10/0x1000 [em28xx_dvb] [11009.908108] do_one_initcall+0x141/0x300 [11009.908111] do_init_module+0x1d0/0x5ad [11009.908114] load_module+0x6666/0x9ba0 [11009.908117] SyS_finit_module+0x108/0x130 [11009.908120] entry_SYSCALL_64_fastpath+0x16/0x76 [11009.908123] INFO: Slab 0xffffea000ef5e280 objects=25 used=25 fp=0x (null) flags=0x2ffff8000004080 [11009.908126] INFO: Object 0xffff8803bd78ab40 @offset=2880 fp=0x0000000000000001 [11009.908130] Bytes b4 ffff8803bd78ab30: 01 00 00 00 2a 07 00 00 9d 28 00 00 01 00 00 00 ....*....(...... [11009.908133] Object ffff8803bd78ab40: 01 00 00 00 00 00 00 00 b0 1d c3 6a 00 88 ff ff ...........j.... [11009.908137] CPU: 3 PID: 28992 Comm: modprobe Tainted: G B W 4.5.0-rc1+ #43 [11009.908140] Hardware name: /NUC5i7RYB, BIOS RYBDWi35.86A.0350.2015.0812.1722 08/12/2015 [11009.908142] ffff8803bd78a000 ffff8802c273f1b8 ffffffff81932007 ffff8803c6407a80 [11009.908148] ffff8802c273f1e8 ffffffff81556759 ffff8803c6407a80 ffffea000ef5e280 [11009.908153] ffff8803bd78ab40 dffffc0000000000 ffff8802c273f210 ffffffff8155ccb4 [11009.908158] Call Trace: [11009.908162] [<ffffffff81932007>] dump_stack+0x4b/0x64 [11009.908165] [<ffffffff81556759>] print_trailer+0xf9/0x150 [11009.908168] [<ffffffff8155ccb4>] object_err+0x34/0x40 [11009.908171] [<ffffffff8155f260>] kasan_report_error+0x230/0x550 [11009.908175] [<ffffffff81237d71>] ? trace_hardirqs_off_caller+0x21/0x290 [11009.908179] [<ffffffff8155e926>] ? kasan_unpoison_shadow+0x36/0x50 [11009.908182] [<ffffffff8155f5c3>] __asan_report_load1_noabort+0x43/0x50 [11009.908185] [<ffffffff8155ea00>] ? __asan_register_globals+0x50/0xa0 [11009.908189] [<ffffffff8194cea6>] ? strcmp+0x96/0xb0 [11009.908192] [<ffffffff8194cea6>] strcmp+0x96/0xb0 [11009.908196] [<ffffffffa13ba4ac>] xc2028_set_config+0x15c/0x630 [tuner_xc2028] [11009.908200] [<ffffffffa13bac90>] xc2028_attach+0x310/0x8a0 [tuner_xc2028] [11009.908203] [<ffffffff8155ea78>] ? memset+0x28/0x30 [11009.908206] [<ffffffffa13ba980>] ? xc2028_set_config+0x630/0x630 [tuner_xc2028] [11009.908211] [<ffffffffa157a59a>] em28xx_attach_xc3028.constprop.7+0x1f9/0x30d [em28xx_dvb] [11009.908215] [<ffffffffa157aa2a>] ? em28xx_dvb_init.part.3+0x37c/0x5cf4 [em28xx_dvb] [11009.908219] [<ffffffffa157a3a1>] ? hauppauge_hvr930c_init+0x487/0x487 [em28xx_dvb] [11009.908222] [<ffffffffa01795ac>] ? lgdt330x_attach+0x1cc/0x370 [lgdt330x] [11009.908226] [<ffffffffa01793e0>] ? i2c_read_demod_bytes.isra.2+0x210/0x210 [lgdt330x] [11009.908230] [<ffffffff812e87d0>] ? ref_module.part.15+0x10/0x10 [11009.908233] [<ffffffff812e56e0>] ? module_assert_mutex_or_preempt+0x80/0x80 [11009.908238] [<ffffffffa157af92>] em28xx_dvb_init.part.3+0x8e4/0x5cf4 [em28xx_dvb] [11009.908242] [<ffffffffa157a6ae>] ? em28xx_attach_xc3028.constprop.7+0x30d/0x30d [em28xx_dvb] [11009.908245] [<ffffffff8195222d>] ? string+0x14d/0x1f0 [11009.908249] [<ffffffff8195381f>] ? symbol_string+0xff/0x1a0 [11009.908253] [<ffffffff81953720>] ? uuid_string+0x6f0/0x6f0 [11009.908257] [<ffffffff811a775e>] ? __kernel_text_address+0x7e/0xa0 [11009.908260] [<ffffffff8104b02f>] ? print_context_stack+0x7f/0xf0 [11009.908264] [<ffffffff812e9846>] ? __module_address+0xb6/0x360 [11009.908268] [<ffffffff8137fdc9>] ? is_ftrace_trampoline+0x99/0xe0 [11009.908271] [<ffffffff811a775e>] ? __kernel_text_address+0x7e/0xa0 [11009.908275] [<ffffffff81240a70>] ? debug_check_no_locks_freed+0x290/0x290 [11009.908278] [<ffffffff8104a24b>] ? dump_trace+0x11b/0x300 [11009.908282] [<ffffffffa13e8143>] ? em28xx_register_extension+0x23/0x190 [em28xx] [11009.908285] [<ffffffff81237d71>] ? trace_hardirqs_off_caller+0x21/0x290 [11009.908289] [<ffffffff8123ff56>] ? trace_hardirqs_on_caller+0x16/0x590 [11009.908292] [<ffffffff812404dd>] ? trace_hardirqs_on+0xd/0x10 [11009.908296] [<ffffffffa13e8143>] ? em28xx_register_extension+0x23/0x190 [em28xx] [11009.908299] [<ffffffff822dcbb0>] ? mutex_trylock+0x400/0x400 [11009.908302] [<ffffffff810021a1>] ? do_one_initcall+0x131/0x300 [11009.908306] [<ffffffff81296dc7>] ? call_rcu_sched+0x17/0x20 [11009.908309] [<ffffffff8159e708>] ? put_object+0x48/0x70 [11009.908314] [<ffffffffa1579f11>] em28xx_dvb_init+0x81/0x8a [em28xx_dvb] [11009.908317] [<ffffffffa13e81f9>] em28xx_register_extension+0xd9/0x190 [em28xx] [11009.908320] [<ffffffffa0150000>] ? 0xffffffffa0150000 [11009.908324] [<ffffffffa0150010>] em28xx_dvb_register+0x10/0x1000 [em28xx_dvb] [11009.908327] [<ffffffff810021b1>] do_one_initcall+0x141/0x300 [11009.908330] [<ffffffff81002070>] ? try_to_run_init_process+0x40/0x40 [11009.908333] [<ffffffff8123ff56>] ? trace_hardirqs_on_caller+0x16/0x590 [11009.908337] [<ffffffff8155e926>] ? kasan_unpoison_shadow+0x36/0x50 [11009.908340] [<ffffffff8155e926>] ? kasan_unpoison_shadow+0x36/0x50 [11009.908343] [<ffffffff8155e926>] ? kasan_unpoison_shadow+0x36/0x50 [11009.908346] [<ffffffff8155ea37>] ? __asan_register_globals+0x87/0xa0 [11009.908350] [<ffffffff8144da7b>] do_init_module+0x1d0/0x5ad [11009.908353] [<ffffffff812f2626>] load_module+0x6666/0x9ba0 [11009.908356] [<ffffffff812e9c90>] ? symbol_put_addr+0x50/0x50 [11009.908361] [<ffffffffa1580037>] ? em28xx_dvb_init.part.3+0x5989/0x5cf4 [em28xx_dvb] [11009.908366] [<ffffffff812ebfc0>] ? module_frob_arch_sections+0x20/0x20 [11009.908369] [<ffffffff815bc940>] ? open_exec+0x50/0x50 [11009.908374] [<ffffffff811671bb>] ? ns_capable+0x5b/0xd0 [11009.908377] [<ffffffff812f5e58>] SyS_finit_module+0x108/0x130 [11009.908379] [<ffffffff812f5d50>] ? SyS_init_module+0x1f0/0x1f0 [11009.908383] [<ffffffff81004044>] ? lockdep_sys_exit_thunk+0x12/0x14 [11009.908394] [<ffffffff822e6936>] entry_SYSCALL_64_fastpath+0x16/0x76 [11009.908396] Memory state around the buggy address: [11009.908398] ffff8803bd78aa00: 00 00 fc fc fc fc fc fc fc fc fc fc fc fc fc fc [11009.908401] ffff8803bd78aa80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [11009.908403] >ffff8803bd78ab00: fc fc fc fc fc fc fc fc 00 00 fc fc fc fc fc fc [11009.908405] ^ [11009.908407] ffff8803bd78ab80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [11009.908409] ffff8803bd78ac00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [11009.908411] ================================================================== In order to avoid it, let's set the cached value of the firmware name to NULL after freeing it. While here, return an error if the memory allocation fails. Signed-off-by: Mauro Carvalho Chehab <[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 XMLHttpRequest::didFailRedirectCheck() { networkError(); } Commit Message: Don't dispatch events when XHR is set to sync mode Any of readystatechange, progress, abort, error, timeout and loadend event are not specified to be dispatched in sync mode in the latest spec. Just an exception corresponding to the failure is thrown. Clean up for readability done in this CL - factor out dispatchEventAndLoadEnd calling code - make didTimeout() private - give error handling methods more descriptive names - set m_exceptionCode in failure type specific methods -- Note that for didFailRedirectCheck, m_exceptionCode was not set in networkError(), but was set at the end of createRequest() This CL is prep for fixing crbug.com/292422 BUG=292422 Review URL: https://chromiumcodereview.appspot.com/24225002 git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: null_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int length = h->len; u_int caplen = h->caplen; u_int family; if (caplen < NULL_HDRLEN) { ND_PRINT((ndo, "[|null]")); return (NULL_HDRLEN); } memcpy((char *)&family, (const char *)p, sizeof(family)); /* * This isn't necessarily in our host byte order; if this is * a DLT_LOOP capture, it's in network byte order, and if * this is a DLT_NULL capture from a machine with the opposite * byte-order, it's in the opposite byte order from ours. * * If the upper 16 bits aren't all zero, assume it's byte-swapped. */ if ((family & 0xFFFF0000) != 0) family = SWAPLONG(family); if (ndo->ndo_eflag) null_hdr_print(ndo, family, length); length -= NULL_HDRLEN; caplen -= NULL_HDRLEN; p += NULL_HDRLEN; switch (family) { case BSD_AFNUM_INET: ip_print(ndo, p, length); break; case BSD_AFNUM_INET6_BSD: case BSD_AFNUM_INET6_FREEBSD: case BSD_AFNUM_INET6_DARWIN: ip6_print(ndo, p, length); break; case BSD_AFNUM_ISO: isoclns_print(ndo, p, length, caplen); break; case BSD_AFNUM_APPLETALK: atalk_print(ndo, p, length); break; case BSD_AFNUM_IPX: ipx_print(ndo, p, length); break; default: /* unknown AF_ value */ if (!ndo->ndo_eflag) null_hdr_print(ndo, family, length + NULL_HDRLEN); if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); } return (NULL_HDRLEN); } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: static void vmw_user_surface_free(struct vmw_resource *res) { struct vmw_surface *srf = vmw_res_to_srf(res); struct vmw_user_surface *user_srf = container_of(srf, struct vmw_user_surface, srf); struct vmw_private *dev_priv = srf->res.dev_priv; uint32_t size = user_srf->size; if (user_srf->master) drm_master_put(&user_srf->master); kfree(srf->offsets); kfree(srf->sizes); kfree(srf->snooper.image); ttm_prime_object_kfree(user_srf, prime); ttm_mem_global_free(vmw_mem_glob(dev_priv), size); } Commit Message: drm/vmwgfx: Make sure backup_handle is always valid When vmw_gb_surface_define_ioctl() is called with an existing buffer, we end up returning an uninitialized variable in the backup_handle. The fix is to first initialize backup_handle to 0 just to be sure, and second, when a user-provided buffer is found, we will use the req->buffer_handle as the backup_handle. Cc: <[email protected]> Reported-by: Murray McAllister <[email protected]> Signed-off-by: Sinclair Yeh <[email protected]> Reviewed-by: Deepak Rawat <[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 cluster_finish(void) { hash_clean(cluster_hash, (void (*)(void *))cluster_free); hash_free(cluster_hash); cluster_hash = NULL; } 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: 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: SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len, unsigned int, flags, struct sockaddr __user *, addr, int, addr_len) { struct socket *sock; struct sockaddr_storage address; int err; struct msghdr msg; struct iovec iov; int fput_needed; if (len > INT_MAX) len = INT_MAX; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; iov.iov_base = buff; iov.iov_len = len; msg.msg_name = NULL; iov_iter_init(&msg.msg_iter, WRITE, &iov, 1, len); msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_namelen = 0; if (addr) { err = move_addr_to_kernel(addr, addr_len, &address); if (err < 0) goto out_put; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = addr_len; } if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; msg.msg_flags = flags; err = sock_sendmsg(sock, &msg, len); out_put: fput_light(sock->file, fput_needed); out: return err; } Commit Message: net: validate the range we feed to iov_iter_init() in sys_sendto/sys_recvfrom Cc: [email protected] # v3.19 Signed-off-by: Al Viro <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: void AutomationProvider::SaveAsAsync(int tab_handle) { NavigationController* tab = NULL; TabContents* tab_contents = GetTabContentsForHandle(tab_handle, &tab); if (tab_contents) tab_contents->OnSavePage(); } 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: bool V8TestEventTarget::HasInstance(v8::Handle<v8::Value> value) { return GetRawTemplate()->HasInstance(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: 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 ExtensionTtsController::IsSpeaking() const { return current_utterance_ != NULL; } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: ofputil_decode_ofp10_table_stats(struct ofpbuf *msg, struct ofputil_table_stats *stats, struct ofputil_table_features *features) { struct ofp10_table_stats *ots; ots = ofpbuf_try_pull(msg, sizeof *ots); if (!ots) { return OFPERR_OFPBRC_BAD_LEN; } features->table_id = ots->table_id; ovs_strlcpy(features->name, ots->name, sizeof features->name); features->max_entries = ntohl(ots->max_entries); features->match = features->wildcard = mf_bitmap_from_of10(ots->wildcards); stats->table_id = ots->table_id; stats->active_count = ntohl(ots->active_count); stats->lookup_count = ntohll(get_32aligned_be64(&ots->lookup_count)); stats->matched_count = ntohll(get_32aligned_be64(&ots->matched_count)); return 0; } Commit Message: ofp-group: Don't assert-fail decoding bad OF1.5 group mod type or command. When decoding a group mod, the current code validates the group type and command after the whole group mod has been decoded. The OF1.5 decoder, however, tries to use the type and command earlier, when it might still be invalid. This caused an assertion failure (via OVS_NOT_REACHED). This commit fixes the problem. ovs-vswitchd does not enable support for OpenFlow 1.5 by default. Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9249 Signed-off-by: Ben Pfaff <[email protected]> Reviewed-by: Yifeng Sun <[email protected]> CWE ID: CWE-617 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 PaymentRequest::Complete(mojom::PaymentComplete result) { if (!client_.is_bound()) return; if (result == mojom::PaymentComplete::FAIL) { delegate_->ShowErrorMessage(); } else { DCHECK(!has_recorded_completion_); journey_logger_.SetCompleted(); has_recorded_completion_ = true; delegate_->GetPrefService()->SetBoolean(kPaymentsFirstTransactionCompleted, true); client_->OnComplete(); state_->RecordUseStats(); } } Commit Message: [Payment Request][Desktop] Prevent use after free. Before this patch, a compromised renderer on desktop could make IPC methods into Payment Request in an unexpected ordering and cause use after free in the browser. This patch will disconnect the IPC pipes if: - Init() is called more than once. - Any other method is called before Init(). - Show() is called more than once. - Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or Complete() are called before Show(). This patch re-orders the IPC methods in payment_request.cc to match the order in payment_request.h, which eases verifying correctness of their error handling. This patch prints more errors to the developer console, if available, to improve debuggability by web developers, who rarely check where LOG prints. After this patch, unexpected ordering of calls into the Payment Request IPC from the renderer to the browser on desktop will print an error in the developer console and disconnect the IPC pipes. The binary might increase slightly in size because more logs are included in the release version instead of being stripped at compile time. Bug: 912947 Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a Reviewed-on: https://chromium-review.googlesource.com/c/1370198 Reviewed-by: anthonyvd <[email protected]> Commit-Queue: Rouslan Solomakhin <[email protected]> Cr-Commit-Position: refs/heads/master@{#616822} 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 test_show_object(struct object *object, struct strbuf *path, const char *last, void *data) { struct bitmap_test_data *tdata = data; int bitmap_pos; bitmap_pos = bitmap_position(object->oid.hash); if (bitmap_pos < 0) die("Object not in bitmap: %s\n", oid_to_hex(&object->oid)); bitmap_set(tdata->base, bitmap_pos); display_progress(tdata->prg, ++tdata->seen); } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static int sha1_neon_init(struct shash_desc *desc) { struct sha1_state *sctx = shash_desc_ctx(desc); *sctx = (struct sha1_state){ .state = { SHA1_H0, SHA1_H1, SHA1_H2, SHA1_H3, SHA1_H4 }, }; return 0; } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[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 NOINLINE int send_select(uint32_t xid, uint32_t server, uint32_t requested) { struct dhcp_packet packet; struct in_addr temp_addr; /* * RFC 2131 4.3.2 DHCPREQUEST message * ... * If the DHCPREQUEST message contains a 'server identifier' * option, the message is in response to a DHCPOFFER message. * Otherwise, the message is a request to verify or extend an * existing lease. If the client uses a 'client identifier' * in a DHCPREQUEST message, it MUST use that same 'client identifier' * in all subsequent messages. If the client included a list * of requested parameters in a DHCPDISCOVER message, it MUST * include that list in all subsequent messages. */ /* Fill in: op, htype, hlen, cookie, chaddr fields, * random xid field (we override it below), * client-id option (unless -C), message type option: */ init_packet(&packet, DHCPREQUEST); packet.xid = xid; udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested); udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server); /* Add options: maxsize, * optionally: hostname, fqdn, vendorclass, * "param req" option according to -O, and options specified with -x */ add_client_options(&packet); temp_addr.s_addr = requested; bb_error_msg("sending select for %s", inet_ntoa(temp_addr)); return raw_bcast_from_client_config_ifindex(&packet, INADDR_ANY); } Commit Message: 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: WORD32 ih264d_parse_nal_unit(iv_obj_t *dec_hdl, ivd_video_decode_op_t *ps_dec_op, UWORD8 *pu1_buf, UWORD32 u4_length) { dec_bit_stream_t *ps_bitstrm; dec_struct_t *ps_dec = (dec_struct_t *)dec_hdl->pv_codec_handle; ivd_video_decode_ip_t *ps_dec_in = (ivd_video_decode_ip_t *)ps_dec->pv_dec_in; dec_slice_params_t * ps_cur_slice = ps_dec->ps_cur_slice; UWORD8 u1_first_byte, u1_nal_ref_idc; UWORD8 u1_nal_unit_type; WORD32 i_status = OK; ps_bitstrm = ps_dec->ps_bitstrm; if(pu1_buf) { if(u4_length) { ps_dec_op->u4_frame_decoded_flag = 0; ih264d_process_nal_unit(ps_dec->ps_bitstrm, pu1_buf, u4_length); SWITCHOFFTRACE; u1_first_byte = ih264d_get_bits_h264(ps_bitstrm, 8); if(NAL_FORBIDDEN_BIT(u1_first_byte)) { H264_DEC_DEBUG_PRINT("\nForbidden bit set in Nal Unit, Let's try\n"); } u1_nal_unit_type = NAL_UNIT_TYPE(u1_first_byte); if ((ps_dec->u4_slice_start_code_found == 1) && (ps_dec->u1_pic_decode_done != 1) && (u1_nal_unit_type > IDR_SLICE_NAL)) { return ERROR_INCOMPLETE_FRAME; } ps_dec->u1_nal_unit_type = u1_nal_unit_type; u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_first_byte)); switch(u1_nal_unit_type) { case SLICE_DATA_PARTITION_A_NAL: case SLICE_DATA_PARTITION_B_NAL: case SLICE_DATA_PARTITION_C_NAL: if(!ps_dec->i4_decode_header) ih264d_parse_slice_partition(ps_dec, ps_bitstrm); break; case IDR_SLICE_NAL: case SLICE_NAL: /* ! */ DEBUG_THREADS_PRINTF("Decoding a slice NAL\n"); if(!ps_dec->i4_decode_header) { if(ps_dec->i4_header_decoded == 3) { /* ! */ ps_dec->u4_slice_start_code_found = 1; ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_decode_slice( (UWORD8)(u1_nal_unit_type == IDR_SLICE_NAL), u1_nal_ref_idc, ps_dec); if((ps_dec->u4_first_slice_in_pic != 0)&& ((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0)) { /* if the first slice header was not valid set to 1 */ ps_dec->u4_first_slice_in_pic = 1; } if(i_status != OK) { return i_status; } } else { H264_DEC_DEBUG_PRINT( "\nSlice NAL Supplied but no header has been supplied\n"); } } break; case SEI_NAL: if(!ps_dec->i4_decode_header) { ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_sei_message(ps_dec, ps_bitstrm); if(i_status != OK) return i_status; ih264d_parse_sei(ps_dec, ps_bitstrm); } break; case SEQ_PARAM_NAL: /* ! */ ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_sps(ps_dec, ps_bitstrm); if(i_status == ERROR_INV_SPS_PPS_T) return i_status; if(!i_status) ps_dec->i4_header_decoded |= 0x1; break; case PIC_PARAM_NAL: /* ! */ ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_pps(ps_dec, ps_bitstrm); if(i_status == ERROR_INV_SPS_PPS_T) return i_status; if(!i_status) ps_dec->i4_header_decoded |= 0x2; break; case ACCESS_UNIT_DELIMITER_RBSP: if(!ps_dec->i4_decode_header) { ih264d_access_unit_delimiter_rbsp(ps_dec); } break; case END_OF_STREAM_RBSP: if(!ps_dec->i4_decode_header) { ih264d_parse_end_of_stream(ps_dec); } break; case FILLER_DATA_NAL: if(!ps_dec->i4_decode_header) { ih264d_parse_filler_data(ps_dec, ps_bitstrm); } break; default: H264_DEC_DEBUG_PRINT("\nUnknown NAL type %d\n", u1_nal_unit_type); break; } } } return i_status; } 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 Target: 1 Example 2: Code: Shader* CreateShader( GLuint client_id, GLuint service_id, GLenum shader_type) { return shader_manager()->CreateShader( client_id, service_id, shader_type); } Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled. This is when we expose DrawBuffers extension. BUG=376951 TEST=the attached test case, webgl conformance [email protected],[email protected] Review URL: https://codereview.chromium.org/315283002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98 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: BGD_DECLARE(gdImagePtr) gdImageScale(const gdImagePtr src, const unsigned int new_width, const unsigned int new_height) { gdImagePtr im_scaled = NULL; if (src == NULL || (uintmax_t)src->interpolation_id >= GD_METHOD_COUNT) { return NULL; } if (new_width == 0 || new_height == 0) { return NULL; } if (new_width == gdImageSX(src) && new_height == gdImageSY(src)) { return gdImageClone(src); } switch (src->interpolation_id) { /*Special cases, optimized implementations */ case GD_NEAREST_NEIGHBOUR: im_scaled = gdImageScaleNearestNeighbour(src, new_width, new_height); break; case GD_BILINEAR_FIXED: case GD_LINEAR: im_scaled = gdImageScaleBilinear(src, new_width, new_height); break; case GD_BICUBIC_FIXED: case GD_BICUBIC: im_scaled = gdImageScaleBicubicFixed(src, new_width, new_height); break; /* generic */ default: if (src->interpolation == NULL) { return NULL; } im_scaled = gdImageScaleTwoPass(src, new_width, new_height); break; } return im_scaled; } Commit Message: Fix potential unsigned underflow No need to decrease `u`, so we don't do it. While we're at it, we also factor out the overflow check of the loop, what improves performance and readability. This issue has been reported by Stefan Esser to [email protected]. CWE ID: CWE-191 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 long Cluster::GetLastTime() const { const BlockEntry* pEntry; const long status = GetLast(pEntry); if (status < 0) //error return status; if (pEntry == NULL) //empty cluster return GetTime(); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); return pBlock->GetTime(this); } 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 reclaim_dma_bufs(void) { unsigned long flags; struct port_buffer *buf, *tmp; LIST_HEAD(tmp_list); if (list_empty(&pending_free_dma_bufs)) return; /* Create a copy of the pending_free_dma_bufs while holding the lock */ spin_lock_irqsave(&dma_bufs_lock, flags); list_cut_position(&tmp_list, &pending_free_dma_bufs, pending_free_dma_bufs.prev); spin_unlock_irqrestore(&dma_bufs_lock, flags); /* Release the dma buffers, without irqs enabled */ list_for_each_entry_safe(buf, tmp, &tmp_list, list) { list_del(&buf->list); free_buf(buf, true); } } Commit Message: virtio-console: avoid DMA from stack put_chars() stuffs the buffer it gets into an sg, but that buffer may be on the stack. This breaks with CONFIG_VMAP_STACK=y (for me, it manifested as printks getting turned into NUL bytes). Signed-off-by: Omar Sandoval <[email protected]> Signed-off-by: Michael S. Tsirkin <[email protected]> Reviewed-by: Amit Shah <[email protected]> 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 void init_predictor_decoder(APEContext *ctx) { APEPredictor *p = &ctx->predictor; /* Zero the history buffers */ memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer)); p->buf = p->historybuffer; /* Initialize and zero the coefficients */ if (ctx->fileversion < 3930) { if (ctx->compression_level == COMPRESSION_LEVEL_FAST) { memcpy(p->coeffsA[0], initial_coeffs_fast_3320, sizeof(initial_coeffs_fast_3320)); memcpy(p->coeffsA[1], initial_coeffs_fast_3320, sizeof(initial_coeffs_fast_3320)); } else { memcpy(p->coeffsA[0], initial_coeffs_a_3800, sizeof(initial_coeffs_a_3800)); memcpy(p->coeffsA[1], initial_coeffs_a_3800, sizeof(initial_coeffs_a_3800)); } } else { memcpy(p->coeffsA[0], initial_coeffs_3930, sizeof(initial_coeffs_3930)); memcpy(p->coeffsA[1], initial_coeffs_3930, sizeof(initial_coeffs_3930)); } memset(p->coeffsB, 0, sizeof(p->coeffsB)); if (ctx->fileversion < 3930) { memcpy(p->coeffsB[0], initial_coeffs_b_3800, sizeof(initial_coeffs_b_3800)); memcpy(p->coeffsB[1], initial_coeffs_b_3800, sizeof(initial_coeffs_b_3800)); } p->filterA[0] = p->filterA[1] = 0; p->filterB[0] = p->filterB[1] = 0; p->lastA[0] = p->lastA[1] = 0; p->sample_pos = 0; } 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 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 chase_port(struct edgeport_port *port, unsigned long timeout, int flush) { int baud_rate; struct tty_struct *tty = tty_port_tty_get(&port->port->port); struct usb_serial *serial = port->port->serial; wait_queue_t wait; unsigned long flags; if (!timeout) timeout = (HZ * EDGE_CLOSING_WAIT)/100; /* wait for data to drain from the buffer */ spin_lock_irqsave(&port->ep_lock, flags); init_waitqueue_entry(&wait, current); add_wait_queue(&tty->write_wait, &wait); for (;;) { set_current_state(TASK_INTERRUPTIBLE); if (kfifo_len(&port->write_fifo) == 0 || timeout == 0 || signal_pending(current) || serial->disconnected) /* disconnect */ break; spin_unlock_irqrestore(&port->ep_lock, flags); timeout = schedule_timeout(timeout); spin_lock_irqsave(&port->ep_lock, flags); } set_current_state(TASK_RUNNING); remove_wait_queue(&tty->write_wait, &wait); if (flush) kfifo_reset_out(&port->write_fifo); spin_unlock_irqrestore(&port->ep_lock, flags); tty_kref_put(tty); /* wait for data to drain from the device */ timeout += jiffies; while ((long)(jiffies - timeout) < 0 && !signal_pending(current) && !serial->disconnected) { /* not disconnected */ if (!tx_active(port)) break; msleep(10); } /* disconnected */ if (serial->disconnected) return; /* wait one more character time, based on baud rate */ /* (tx_active doesn't seem to wait for the last byte) */ baud_rate = port->baud_rate; if (baud_rate == 0) baud_rate = 50; msleep(max(1, DIV_ROUND_UP(10000, baud_rate))); } Commit Message: USB: io_ti: Fix NULL dereference in chase_port() The tty is NULL when the port is hanging up. chase_port() needs to check for this. This patch is intended for stable series. The behavior was observed and tested in Linux 3.2 and 3.7.1. Johan Hovold submitted a more elaborate patch for the mainline kernel. [ 56.277883] usb 1-1: edge_bulk_in_callback - nonzero read bulk status received: -84 [ 56.278811] usb 1-1: USB disconnect, device number 3 [ 56.278856] usb 1-1: edge_bulk_in_callback - stopping read! [ 56.279562] BUG: unable to handle kernel NULL pointer dereference at 00000000000001c8 [ 56.280536] IP: [<ffffffff8144e62a>] _raw_spin_lock_irqsave+0x19/0x35 [ 56.281212] PGD 1dc1b067 PUD 1e0f7067 PMD 0 [ 56.282085] Oops: 0002 [#1] SMP [ 56.282744] Modules linked in: [ 56.283512] CPU 1 [ 56.283512] Pid: 25, comm: khubd Not tainted 3.7.1 #1 innotek GmbH VirtualBox/VirtualBox [ 56.283512] RIP: 0010:[<ffffffff8144e62a>] [<ffffffff8144e62a>] _raw_spin_lock_irqsave+0x19/0x35 [ 56.283512] RSP: 0018:ffff88001fa99ab0 EFLAGS: 00010046 [ 56.283512] RAX: 0000000000000046 RBX: 00000000000001c8 RCX: 0000000000640064 [ 56.283512] RDX: 0000000000010000 RSI: ffff88001fa99b20 RDI: 00000000000001c8 [ 56.283512] RBP: ffff88001fa99b20 R08: 0000000000000000 R09: 0000000000000000 [ 56.283512] R10: 0000000000000000 R11: ffffffff812fcb4c R12: ffff88001ddf53c0 [ 56.283512] R13: 0000000000000000 R14: 00000000000001c8 R15: ffff88001e19b9f4 [ 56.283512] FS: 0000000000000000(0000) GS:ffff88001fd00000(0000) knlGS:0000000000000000 [ 56.283512] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b [ 56.283512] CR2: 00000000000001c8 CR3: 000000001dc51000 CR4: 00000000000006e0 [ 56.283512] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 [ 56.283512] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400 [ 56.283512] Process khubd (pid: 25, threadinfo ffff88001fa98000, task ffff88001fa94f80) [ 56.283512] Stack: [ 56.283512] 0000000000000046 00000000000001c8 ffffffff810578ec ffffffff812fcb4c [ 56.283512] ffff88001e19b980 0000000000002710 ffffffff812ffe81 0000000000000001 [ 56.283512] ffff88001fa94f80 0000000000000202 ffffffff00000001 0000000000000296 [ 56.283512] Call Trace: [ 56.283512] [<ffffffff810578ec>] ? add_wait_queue+0x12/0x3c [ 56.283512] [<ffffffff812fcb4c>] ? usb_serial_port_work+0x28/0x28 [ 56.283512] [<ffffffff812ffe81>] ? chase_port+0x84/0x2d6 [ 56.283512] [<ffffffff81063f27>] ? try_to_wake_up+0x199/0x199 [ 56.283512] [<ffffffff81263a5c>] ? tty_ldisc_hangup+0x222/0x298 [ 56.283512] [<ffffffff81300171>] ? edge_close+0x64/0x129 [ 56.283512] [<ffffffff810612f7>] ? __wake_up+0x35/0x46 [ 56.283512] [<ffffffff8106135b>] ? should_resched+0x5/0x23 [ 56.283512] [<ffffffff81264916>] ? tty_port_shutdown+0x39/0x44 [ 56.283512] [<ffffffff812fcb4c>] ? usb_serial_port_work+0x28/0x28 [ 56.283512] [<ffffffff8125d38c>] ? __tty_hangup+0x307/0x351 [ 56.283512] [<ffffffff812e6ddc>] ? usb_hcd_flush_endpoint+0xde/0xed [ 56.283512] [<ffffffff8144e625>] ? _raw_spin_lock_irqsave+0x14/0x35 [ 56.283512] [<ffffffff812fd361>] ? usb_serial_disconnect+0x57/0xc2 [ 56.283512] [<ffffffff812ea99b>] ? usb_unbind_interface+0x5c/0x131 [ 56.283512] [<ffffffff8128d738>] ? __device_release_driver+0x7f/0xd5 [ 56.283512] [<ffffffff8128d9cd>] ? device_release_driver+0x1a/0x25 [ 56.283512] [<ffffffff8128d393>] ? bus_remove_device+0xd2/0xe7 [ 56.283512] [<ffffffff8128b7a3>] ? device_del+0x119/0x167 [ 56.283512] [<ffffffff812e8d9d>] ? usb_disable_device+0x6a/0x180 [ 56.283512] [<ffffffff812e2ae0>] ? usb_disconnect+0x81/0xe6 [ 56.283512] [<ffffffff812e4435>] ? hub_thread+0x577/0xe82 [ 56.283512] [<ffffffff8144daa7>] ? __schedule+0x490/0x4be [ 56.283512] [<ffffffff8105798f>] ? abort_exclusive_wait+0x79/0x79 [ 56.283512] [<ffffffff812e3ebe>] ? usb_remote_wakeup+0x2f/0x2f [ 56.283512] [<ffffffff812e3ebe>] ? usb_remote_wakeup+0x2f/0x2f [ 56.283512] [<ffffffff810570b4>] ? kthread+0x81/0x89 [ 56.283512] [<ffffffff81057033>] ? __kthread_parkme+0x5c/0x5c [ 56.283512] [<ffffffff8145387c>] ? ret_from_fork+0x7c/0xb0 [ 56.283512] [<ffffffff81057033>] ? __kthread_parkme+0x5c/0x5c [ 56.283512] Code: 8b 7c 24 08 e8 17 0b c3 ff 48 8b 04 24 48 83 c4 10 c3 53 48 89 fb 41 50 e8 e0 0a c3 ff 48 89 04 24 e8 e7 0a c3 ff ba 00 00 01 00 <f0> 0f c1 13 48 8b 04 24 89 d1 c1 ea 10 66 39 d1 74 07 f3 90 66 [ 56.283512] RIP [<ffffffff8144e62a>] _raw_spin_lock_irqsave+0x19/0x35 [ 56.283512] RSP <ffff88001fa99ab0> [ 56.283512] CR2: 00000000000001c8 [ 56.283512] ---[ end trace 49714df27e1679ce ]--- Signed-off-by: Wolfgang Frisch <[email protected]> Cc: Johan Hovold <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: base::TimeTicks TabLifecycleUnitSource::TabLifecycleUnit::GetLastFocusedTime() const { return last_focused_time_; } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} 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: SYSCALL_DEFINE3(mincore, unsigned long, start, size_t, len, unsigned char __user *, vec) { long retval; unsigned long pages; unsigned char *tmp; /* Check the start address: needs to be page-aligned.. */ if (start & ~PAGE_MASK) return -EINVAL; /* ..and we need to be passed a valid user-space range */ if (!access_ok((void __user *) start, len)) return -ENOMEM; /* This also avoids any overflows on PAGE_ALIGN */ pages = len >> PAGE_SHIFT; pages += (offset_in_page(len)) != 0; if (!access_ok(vec, pages)) return -EFAULT; tmp = (void *) __get_free_page(GFP_USER); if (!tmp) return -EAGAIN; retval = 0; while (pages) { /* * Do at most PAGE_SIZE entries per iteration, due to * the temporary buffer size. */ down_read(&current->mm->mmap_sem); retval = do_mincore(start, min(pages, PAGE_SIZE), tmp); up_read(&current->mm->mmap_sem); if (retval <= 0) break; if (copy_to_user(vec, tmp, retval)) { retval = -EFAULT; break; } pages -= retval; vec += retval; start += retval << PAGE_SHIFT; retval = 0; } free_page((unsigned long) tmp); return retval; } Commit Message: Change mincore() to count "mapped" pages rather than "cached" pages The semantics of what "in core" means for the mincore() system call are somewhat unclear, but Linux has always (since 2.3.52, which is when mincore() was initially done) treated it as "page is available in page cache" rather than "page is mapped in the mapping". The problem with that traditional semantic is that it exposes a lot of system cache state that it really probably shouldn't, and that users shouldn't really even care about. So let's try to avoid that information leak by simply changing the semantics to be that mincore() counts actual mapped pages, not pages that might be cheaply mapped if they were faulted (note the "might be" part of the old semantics: being in the cache doesn't actually guarantee that you can access them without IO anyway, since things like network filesystems may have to revalidate the cache before use). In many ways the old semantics were somewhat insane even aside from the information leak issue. From the very beginning (and that beginning is a long time ago: 2.3.52 was released in March 2000, I think), the code had a comment saying Later we can get more picky about what "in core" means precisely. and this is that "later". Admittedly it is much later than is really comfortable. NOTE! This is a real semantic change, and it is for example known to change the output of "fincore", since that program literally does a mmmap without populating it, and then doing "mincore()" on that mapping that doesn't actually have any pages in it. I'm hoping that nobody actually has any workflow that cares, and the info leak is real. We may have to do something different if it turns out that people have valid reasons to want the old semantics, and if we can limit the information leak sanely. Cc: Kevin Easton <[email protected]> Cc: Jiri Kosina <[email protected]> Cc: Masatake YAMATO <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Greg KH <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Michal Hocko <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> 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: header_put_le_int (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 4) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 24) ; } ; } /* header_put_le_int */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119 Target: 1 Example 2: Code: static void smtp_to_smtps(struct connectdata *conn) { /* Change the connection handler */ conn->handler = &Curl_handler_smtps; /* Set the connection's upgraded to TLS flag */ conn->tls_upgraded = TRUE; } Commit Message: smtp: use the upload buffer size for scratch buffer malloc ... not the read buffer size, as that can be set smaller and thus cause a buffer overflow! CVE-2018-0500 Reported-by: Peter Wu Bug: https://curl.haxx.se/docs/adv_2018-70a2.html 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: gs_pdf14_clist_device_push(gs_memory_t *mem, gs_gstate *pgs, gx_device **pcdev, gx_device *dev, const gs_pdf14trans_t *pdf14pct) { int code; pdf14_clist_device *p14dev; gx_device_clist_writer * const cdev = &((gx_device_clist *)dev)->writer; code = pdf14_create_clist_device(mem, pgs, pcdev, dev, pdf14pct); /* * Set the color_info of the clist device to match the compositing * device. We will restore it when the compositor is popped. * See pdf14_clist_create_compositor for the restore. Do the * same with the gs_gstate's get_cmap_procs. We do not want * the gs_gstate to use transfer functions on our color values. * The transfer functions will be applied at the end after we * have done our PDF 1.4 blend operations. */ p14dev = (pdf14_clist_device *)(*pcdev); p14dev->saved_target_color_info = dev->color_info; dev->color_info = (*pcdev)->color_info; /* Make sure that we keep the anti-alias information though */ dev->color_info.anti_alias = p14dev->saved_target_color_info.anti_alias; p14dev->color_info.anti_alias = dev->color_info.anti_alias; /* adjust the clist_color_info now */ cdev->clist_color_info.depth = p14dev->color_info.depth; cdev->clist_color_info.polarity = p14dev->color_info.polarity; cdev->clist_color_info.num_components = p14dev->color_info.num_components; cdev->clist_color_info.max_color = p14dev->color_info.max_color; cdev->clist_color_info.max_gray = p14dev->color_info.max_gray; p14dev->saved_target_encode_color = dev->procs.encode_color; p14dev->saved_target_decode_color = dev->procs.decode_color; dev->procs.encode_color = p14dev->procs.encode_color = p14dev->my_encode_color; dev->procs.decode_color = p14dev->procs.decode_color = p14dev->my_decode_color; p14dev->saved_target_get_color_mapping_procs = dev->procs.get_color_mapping_procs; p14dev->saved_target_get_color_comp_index = dev->procs.get_color_comp_index; dev->procs.get_color_mapping_procs = p14dev->procs.get_color_mapping_procs = p14dev->my_get_color_mapping_procs; dev->procs.get_color_comp_index = p14dev->procs.get_color_comp_index = p14dev->my_get_color_comp_index; p14dev->save_get_cmap_procs = pgs->get_cmap_procs; pgs->get_cmap_procs = pdf14_get_cmap_procs; gx_set_cmap_procs(pgs, dev); return code; } Commit Message: CWE ID: CWE-476 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_rcv(struct sk_buff *skb) { const struct tcphdr *th; const struct ipv6hdr *hdr; bool refcounted; struct sock *sk; int ret; struct net *net = dev_net(skb->dev); if (skb->pkt_type != PACKET_HOST) goto discard_it; /* * Count it even if it's bad. */ __TCP_INC_STATS(net, TCP_MIB_INSEGS); if (!pskb_may_pull(skb, sizeof(struct tcphdr))) goto discard_it; th = (const struct tcphdr *)skb->data; if (unlikely(th->doff < sizeof(struct tcphdr)/4)) goto bad_packet; if (!pskb_may_pull(skb, th->doff*4)) goto discard_it; if (skb_checksum_init(skb, IPPROTO_TCP, ip6_compute_pseudo)) goto csum_error; th = (const struct tcphdr *)skb->data; hdr = ipv6_hdr(skb); lookup: sk = __inet6_lookup_skb(&tcp_hashinfo, skb, __tcp_hdrlen(th), th->source, th->dest, inet6_iif(skb), &refcounted); if (!sk) goto no_tcp_socket; process: if (sk->sk_state == TCP_TIME_WAIT) goto do_time_wait; if (sk->sk_state == TCP_NEW_SYN_RECV) { struct request_sock *req = inet_reqsk(sk); struct sock *nsk; sk = req->rsk_listener; tcp_v6_fill_cb(skb, hdr, th); if (tcp_v6_inbound_md5_hash(sk, skb)) { sk_drops_add(sk, skb); reqsk_put(req); goto discard_it; } if (unlikely(sk->sk_state != TCP_LISTEN)) { inet_csk_reqsk_queue_drop_and_put(sk, req); goto lookup; } sock_hold(sk); refcounted = true; nsk = tcp_check_req(sk, skb, req, false); if (!nsk) { reqsk_put(req); goto discard_and_relse; } if (nsk == sk) { reqsk_put(req); tcp_v6_restore_cb(skb); } else if (tcp_child_process(sk, nsk, skb)) { tcp_v6_send_reset(nsk, skb); goto discard_and_relse; } else { sock_put(sk); return 0; } } if (hdr->hop_limit < inet6_sk(sk)->min_hopcount) { __NET_INC_STATS(net, LINUX_MIB_TCPMINTTLDROP); goto discard_and_relse; } if (!xfrm6_policy_check(sk, XFRM_POLICY_IN, skb)) goto discard_and_relse; tcp_v6_fill_cb(skb, hdr, th); if (tcp_v6_inbound_md5_hash(sk, skb)) goto discard_and_relse; if (sk_filter(sk, skb)) goto discard_and_relse; skb->dev = NULL; if (sk->sk_state == TCP_LISTEN) { ret = tcp_v6_do_rcv(sk, skb); goto put_and_return; } sk_incoming_cpu_update(sk); bh_lock_sock_nested(sk); tcp_segs_in(tcp_sk(sk), skb); ret = 0; if (!sock_owned_by_user(sk)) { if (!tcp_prequeue(sk, skb)) ret = tcp_v6_do_rcv(sk, skb); } else if (tcp_add_backlog(sk, skb)) { goto discard_and_relse; } bh_unlock_sock(sk); put_and_return: if (refcounted) sock_put(sk); return ret ? -1 : 0; no_tcp_socket: if (!xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb)) goto discard_it; tcp_v6_fill_cb(skb, hdr, th); if (tcp_checksum_complete(skb)) { csum_error: __TCP_INC_STATS(net, TCP_MIB_CSUMERRORS); bad_packet: __TCP_INC_STATS(net, TCP_MIB_INERRS); } else { tcp_v6_send_reset(NULL, skb); } discard_it: kfree_skb(skb); return 0; discard_and_relse: sk_drops_add(sk, skb); if (refcounted) sock_put(sk); goto discard_it; do_time_wait: if (!xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb)) { inet_twsk_put(inet_twsk(sk)); goto discard_it; } tcp_v6_fill_cb(skb, hdr, th); if (tcp_checksum_complete(skb)) { inet_twsk_put(inet_twsk(sk)); goto csum_error; } switch (tcp_timewait_state_process(inet_twsk(sk), skb, th)) { case TCP_TW_SYN: { struct sock *sk2; sk2 = inet6_lookup_listener(dev_net(skb->dev), &tcp_hashinfo, skb, __tcp_hdrlen(th), &ipv6_hdr(skb)->saddr, th->source, &ipv6_hdr(skb)->daddr, ntohs(th->dest), tcp_v6_iif(skb)); if (sk2) { struct inet_timewait_sock *tw = inet_twsk(sk); inet_twsk_deschedule_put(tw); sk = sk2; tcp_v6_restore_cb(skb); refcounted = false; goto process; } /* Fall through to ACK */ } case TCP_TW_ACK: tcp_v6_timewait_ack(sk, skb); break; case TCP_TW_RST: tcp_v6_restore_cb(skb); tcp_v6_send_reset(sk, skb); inet_twsk_deschedule_put(inet_twsk(sk)); goto discard_it; case TCP_TW_SUCCESS: ; } goto discard_it; } 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: void ChromotingInstance::PauseVideo(bool pause) { if (!IsConnected()) { return; } protocol::VideoControl video_control; video_control.set_enable(!pause); host_connection_->host_stub()->ControlVideo(video_control); } Commit Message: Restrict the Chromoting client plugin to use by extensions & apps. BUG=160456 Review URL: https://chromiumcodereview.appspot.com/11365276 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@168289 0039d316-1c4b-4281-b951-d872f2087c98 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: dispatch_cmd(conn c) { int r, i, timeout = -1; size_t z; unsigned int count; job j; unsigned char type; char *size_buf, *delay_buf, *ttr_buf, *pri_buf, *end_buf, *name; unsigned int pri, body_size; usec delay, ttr; uint64_t id; tube t = NULL; /* NUL-terminate this string so we can use strtol and friends */ c->cmd[c->cmd_len - 2] = '\0'; /* check for possible maliciousness */ if (strlen(c->cmd) != c->cmd_len - 2) { return reply_msg(c, MSG_BAD_FORMAT); } type = which_cmd(c); dprintf("got %s command: \"%s\"\n", op_names[(int) type], c->cmd); switch (type) { case OP_PUT: r = read_pri(&pri, c->cmd + 4, &delay_buf); if (r) return reply_msg(c, MSG_BAD_FORMAT); r = read_delay(&delay, delay_buf, &ttr_buf); if (r) return reply_msg(c, MSG_BAD_FORMAT); r = read_ttr(&ttr, ttr_buf, &size_buf); if (r) return reply_msg(c, MSG_BAD_FORMAT); errno = 0; body_size = strtoul(size_buf, &end_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); if (body_size > job_data_size_limit) { return reply_msg(c, MSG_JOB_TOO_BIG); } /* don't allow trailing garbage */ if (end_buf[0] != '\0') return reply_msg(c, MSG_BAD_FORMAT); conn_set_producer(c); c->in_job = make_job(pri, delay, ttr ? : 1, body_size + 2, c->use); /* OOM? */ if (!c->in_job) { /* throw away the job body and respond with OUT_OF_MEMORY */ twarnx("server error: " MSG_OUT_OF_MEMORY); return skip(c, body_size + 2, MSG_OUT_OF_MEMORY); } fill_extra_data(c); /* it's possible we already have a complete job */ maybe_enqueue_incoming_job(c); break; case OP_PEEK_READY: /* don't allow trailing garbage */ if (c->cmd_len != CMD_PEEK_READY_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; j = job_copy(pq_peek(&c->use->ready)); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); reply_job(c, j, MSG_FOUND); break; case OP_PEEK_DELAYED: /* don't allow trailing garbage */ if (c->cmd_len != CMD_PEEK_DELAYED_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; j = job_copy(pq_peek(&c->use->delay)); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); reply_job(c, j, MSG_FOUND); break; case OP_PEEK_BURIED: /* don't allow trailing garbage */ if (c->cmd_len != CMD_PEEK_BURIED_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; j = job_copy(buried_job_p(c->use)? j = c->use->buried.next : NULL); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); reply_job(c, j, MSG_FOUND); break; case OP_PEEKJOB: errno = 0; id = strtoull(c->cmd + CMD_PEEKJOB_LEN, &end_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; /* So, peek is annoying, because some other connection might free the * job while we are still trying to write it out. So we copy it and * then free the copy when it's done sending. */ j = job_copy(peek_job(id)); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); reply_job(c, j, MSG_FOUND); break; case OP_RESERVE_TIMEOUT: errno = 0; timeout = strtol(c->cmd + CMD_RESERVE_TIMEOUT_LEN, &end_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); case OP_RESERVE: /* FALLTHROUGH */ /* don't allow trailing garbage */ if (type == OP_RESERVE && c->cmd_len != CMD_RESERVE_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; conn_set_worker(c); if (conn_has_close_deadline(c) && !conn_ready(c)) { return reply_msg(c, MSG_DEADLINE_SOON); } /* try to get a new job for this guy */ wait_for_job(c, timeout); process_queue(); break; case OP_DELETE: errno = 0; id = strtoull(c->cmd + CMD_DELETE_LEN, &end_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; j = job_find(id); j = remove_reserved_job(c, j) ? : remove_ready_job(j) ? : remove_buried_job(j); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); j->state = JOB_STATE_INVALID; r = binlog_write_job(j); job_free(j); if (!r) return reply_serr(c, MSG_INTERNAL_ERROR); reply(c, MSG_DELETED, MSG_DELETED_LEN, STATE_SENDWORD); break; case OP_RELEASE: errno = 0; id = strtoull(c->cmd + CMD_RELEASE_LEN, &pri_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); r = read_pri(&pri, pri_buf, &delay_buf); if (r) return reply_msg(c, MSG_BAD_FORMAT); r = read_delay(&delay, delay_buf, NULL); if (r) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; j = remove_reserved_job(c, job_find(id)); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); /* We want to update the delay deadline on disk, so reserve space for * that. */ if (delay) { z = binlog_reserve_space_update(j); if (!z) return reply_serr(c, MSG_OUT_OF_MEMORY); j->reserved_binlog_space += z; } j->pri = pri; j->delay = delay; j->release_ct++; r = enqueue_job(j, delay, !!delay); if (r < 0) return reply_serr(c, MSG_INTERNAL_ERROR); if (r == 1) { return reply(c, MSG_RELEASED, MSG_RELEASED_LEN, STATE_SENDWORD); } /* out of memory trying to grow the queue, so it gets buried */ bury_job(j, 0); reply(c, MSG_BURIED, MSG_BURIED_LEN, STATE_SENDWORD); break; case OP_BURY: errno = 0; id = strtoull(c->cmd + CMD_BURY_LEN, &pri_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); r = read_pri(&pri, pri_buf, NULL); if (r) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; j = remove_reserved_job(c, job_find(id)); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); j->pri = pri; r = bury_job(j, 1); if (!r) return reply_serr(c, MSG_INTERNAL_ERROR); reply(c, MSG_BURIED, MSG_BURIED_LEN, STATE_SENDWORD); break; case OP_KICK: errno = 0; count = strtoul(c->cmd + CMD_KICK_LEN, &end_buf, 10); if (end_buf == c->cmd + CMD_KICK_LEN) { return reply_msg(c, MSG_BAD_FORMAT); } if (errno) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; i = kick_jobs(c->use, count); return reply_line(c, STATE_SENDWORD, "KICKED %u\r\n", i); case OP_TOUCH: errno = 0; id = strtoull(c->cmd + CMD_TOUCH_LEN, &end_buf, 10); if (errno) return twarn("strtoull"), reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; j = touch_job(c, job_find(id)); if (j) { reply(c, MSG_TOUCHED, MSG_TOUCHED_LEN, STATE_SENDWORD); } else { return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); } break; case OP_STATS: /* don't allow trailing garbage */ if (c->cmd_len != CMD_STATS_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; do_stats(c, fmt_stats, NULL); break; case OP_JOBSTATS: errno = 0; id = strtoull(c->cmd + CMD_JOBSTATS_LEN, &end_buf, 10); if (errno) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; j = peek_job(id); if (!j) return reply(c, MSG_NOTFOUND, MSG_NOTFOUND_LEN, STATE_SENDWORD); if (!j->tube) return reply_serr(c, MSG_INTERNAL_ERROR); do_stats(c, (fmt_fn) fmt_job_stats, j); break; case OP_STATS_TUBE: name = c->cmd + CMD_STATS_TUBE_LEN; if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; t = tube_find(name); if (!t) return reply_msg(c, MSG_NOTFOUND); do_stats(c, (fmt_fn) fmt_stats_tube, t); t = NULL; break; case OP_LIST_TUBES: /* don't allow trailing garbage */ if (c->cmd_len != CMD_LIST_TUBES_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; do_list_tubes(c, &tubes); break; case OP_LIST_TUBE_USED: /* don't allow trailing garbage */ if (c->cmd_len != CMD_LIST_TUBE_USED_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; reply_line(c, STATE_SENDWORD, "USING %s\r\n", c->use->name); break; case OP_LIST_TUBES_WATCHED: /* don't allow trailing garbage */ if (c->cmd_len != CMD_LIST_TUBES_WATCHED_LEN + 2) { return reply_msg(c, MSG_BAD_FORMAT); } op_ct[type]++; do_list_tubes(c, &c->watch); break; case OP_USE: name = c->cmd + CMD_USE_LEN; if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; TUBE_ASSIGN(t, tube_find_or_make(name)); if (!t) return reply_serr(c, MSG_OUT_OF_MEMORY); c->use->using_ct--; TUBE_ASSIGN(c->use, t); TUBE_ASSIGN(t, NULL); c->use->using_ct++; reply_line(c, STATE_SENDWORD, "USING %s\r\n", c->use->name); break; case OP_WATCH: name = c->cmd + CMD_WATCH_LEN; if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; TUBE_ASSIGN(t, tube_find_or_make(name)); if (!t) return reply_serr(c, MSG_OUT_OF_MEMORY); r = 1; if (!ms_contains(&c->watch, t)) r = ms_append(&c->watch, t); TUBE_ASSIGN(t, NULL); if (!r) return reply_serr(c, MSG_OUT_OF_MEMORY); reply_line(c, STATE_SENDWORD, "WATCHING %d\r\n", c->watch.used); break; case OP_IGNORE: name = c->cmd + CMD_IGNORE_LEN; if (!name_is_ok(name, 200)) return reply_msg(c, MSG_BAD_FORMAT); op_ct[type]++; t = NULL; for (i = 0; i < c->watch.used; i++) { t = c->watch.items[i]; if (strncmp(t->name, name, MAX_TUBE_NAME_LEN) == 0) break; t = NULL; } if (t && c->watch.used < 2) return reply_msg(c, MSG_NOT_IGNORED); if (t) ms_remove(&c->watch, t); /* may free t if refcount => 0 */ t = NULL; reply_line(c, STATE_SENDWORD, "WATCHING %d\r\n", c->watch.used); break; case OP_QUIT: conn_close(c); break; case OP_PAUSE_TUBE: op_ct[type]++; r = read_tube_name(&name, c->cmd + CMD_PAUSE_TUBE_LEN, &delay_buf); if (r) return reply_msg(c, MSG_BAD_FORMAT); r = read_delay(&delay, delay_buf, NULL); if (r) return reply_msg(c, MSG_BAD_FORMAT); *delay_buf = '\0'; t = tube_find(name); if (!t) return reply_msg(c, MSG_NOTFOUND); t->deadline_at = now_usec() + delay; t->pause = delay; t->stat.pause_ct++; set_main_delay_timeout(); reply_line(c, STATE_SENDWORD, "PAUSED\r\n"); break; default: return reply_msg(c, MSG_UNKNOWN_COMMAND); } } Commit Message: Discard job body bytes if the job is too big. Previously, a malicious user could craft a job payload and inject beanstalk commands without the client application knowing. (An extra-careful client library could check the size of the job body before sending the put command, but most libraries do not do this, nor should they have to.) Reported by Graham Barr. 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 PlatformSensorProviderAndroid::CreateAbsoluteOrientationEulerAnglesSensor( JNIEnv* env, mojo::ScopedSharedBufferMapping mapping, const CreateSensorCallback& callback) { if (static_cast<bool>(Java_PlatformSensorProvider_hasSensorType( env, j_object_, static_cast<jint>( mojom::SensorType::ABSOLUTE_ORIENTATION_QUATERNION)))) { auto sensor_fusion_algorithm = std::make_unique<OrientationEulerAnglesFusionAlgorithmUsingQuaternion>( true /* absolute */); PlatformSensorFusion::Create(std::move(mapping), this, std::move(sensor_fusion_algorithm), callback); } else { auto sensor_fusion_algorithm = std::make_unique< AbsoluteOrientationEulerAnglesFusionAlgorithmUsingAccelerometerAndMagnetometer>(); PlatformSensorFusion::Create(std::move(mapping), this, std::move(sensor_fusion_algorithm), callback); } } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732 Target: 1 Example 2: Code: xfs_da_grow_inode_int( struct xfs_da_args *args, xfs_fileoff_t *bno, int count) { struct xfs_trans *tp = args->trans; struct xfs_inode *dp = args->dp; int w = args->whichfork; xfs_drfsbno_t nblks = dp->i_d.di_nblocks; struct xfs_bmbt_irec map, *mapp; int nmap, error, got, i, mapi; /* * Find a spot in the file space to put the new block. */ error = xfs_bmap_first_unused(tp, dp, count, bno, w); if (error) return error; /* * Try mapping it in one filesystem block. */ nmap = 1; ASSERT(args->firstblock != NULL); error = xfs_bmapi_write(tp, dp, *bno, count, xfs_bmapi_aflag(w)|XFS_BMAPI_METADATA|XFS_BMAPI_CONTIG, args->firstblock, args->total, &map, &nmap, args->flist); if (error) return error; ASSERT(nmap <= 1); if (nmap == 1) { mapp = &map; mapi = 1; } else if (nmap == 0 && count > 1) { xfs_fileoff_t b; int c; /* * If we didn't get it and the block might work if fragmented, * try without the CONTIG flag. Loop until we get it all. */ mapp = kmem_alloc(sizeof(*mapp) * count, KM_SLEEP); for (b = *bno, mapi = 0; b < *bno + count; ) { nmap = MIN(XFS_BMAP_MAX_NMAP, count); c = (int)(*bno + count - b); error = xfs_bmapi_write(tp, dp, b, c, xfs_bmapi_aflag(w)|XFS_BMAPI_METADATA, args->firstblock, args->total, &mapp[mapi], &nmap, args->flist); if (error) goto out_free_map; if (nmap < 1) break; mapi += nmap; b = mapp[mapi - 1].br_startoff + mapp[mapi - 1].br_blockcount; } } else { mapi = 0; mapp = NULL; } /* * Count the blocks we got, make sure it matches the total. */ for (i = 0, got = 0; i < mapi; i++) got += mapp[i].br_blockcount; if (got != count || mapp[0].br_startoff != *bno || mapp[mapi - 1].br_startoff + mapp[mapi - 1].br_blockcount != *bno + count) { error = XFS_ERROR(ENOSPC); goto out_free_map; } /* account for newly allocated blocks in reserved blocks total */ args->total -= dp->i_d.di_nblocks - nblks; out_free_map: if (mapp != &map) kmem_free(mapp); return error; } Commit Message: xfs: fix directory hash ordering bug Commit f5ea1100 ("xfs: add CRCs to dir2/da node blocks") introduced in 3.10 incorrectly converted the btree hash index array pointer in xfs_da3_fixhashpath(). It resulted in the the current hash always being compared against the first entry in the btree rather than the current block index into the btree block's hash entry array. As a result, it was comparing the wrong hashes, and so could misorder the entries in the btree. For most cases, this doesn't cause any problems as it requires hash collisions to expose the ordering problem. However, when there are hash collisions within a directory there is a very good probability that the entries will be ordered incorrectly and that actually matters when duplicate hashes are placed into or removed from the btree block hash entry array. This bug results in an on-disk directory corruption and that results in directory verifier functions throwing corruption warnings into the logs. While no data or directory entries are lost, access to them may be compromised, and attempts to remove entries from a directory that has suffered from this corruption may result in a filesystem shutdown. xfs_repair will fix the directory hash ordering without data loss occuring. [dchinner: wrote useful a commit message] cc: <[email protected]> Reported-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: Mark Tinguely <[email protected]> Reviewed-by: Ben Myers <[email protected]> Signed-off-by: Dave Chinner <[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: nsPluginInstance::NewStream(NPMIMEType /*type*/, NPStream* stream, NPBool /*seekable*/, uint16_t* /*stype*/) { if (_childpid) { return NPERR_GENERIC_ERROR; } _swf_url = stream->url; if (!_swf_url.empty() && _window) { return startProc(); } return NPERR_NO_ERROR; } Commit Message: 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: bool CanCommitURL(const GURL& url) { SchemeMap::const_iterator judgment(scheme_policy_.find(url.scheme())); if (judgment != scheme_policy_.end()) return judgment->second; if (url.SchemeIs(url::kFileScheme)) { base::FilePath path; if (net::FileURLToFilePath(url, &path)) return ContainsKey(request_file_set_, path); } return false; // Unmentioned schemes are disallowed. } Commit Message: This patch implements a mechanism for more granular link URL permissions (filtering on scheme/host). This fixes the bug that allowed PDFs to have working links to any "chrome://" URLs. BUG=528505,226927 Review URL: https://codereview.chromium.org/1362433002 Cr-Commit-Position: refs/heads/master@{#351705} CWE ID: CWE-264 Target: 1 Example 2: Code: static enum TIFFReadDirEntryErr TIFFReadDirEntryLong8Array(TIFF* tif, TIFFDirEntry* direntry, uint64** value) { enum TIFFReadDirEntryErr err; uint32 count; void* origdata; uint64* data; switch (direntry->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: case TIFF_LONG: case TIFF_SLONG: case TIFF_LONG8: case TIFF_SLONG8: break; default: return(TIFFReadDirEntryErrType); } err=TIFFReadDirEntryArray(tif,direntry,&count,8,&origdata); if ((err!=TIFFReadDirEntryErrOk)||(origdata==0)) { *value=0; return(err); } switch (direntry->tdir_type) { case TIFF_LONG8: *value=(uint64*)origdata; if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong8(*value,count); return(TIFFReadDirEntryErrOk); case TIFF_SLONG8: { int64* m; uint32 n; m=(int64*)origdata; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)m); err=TIFFReadDirEntryCheckRangeLong8Slong8(*m); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(origdata); return(err); } m++; } *value=(uint64*)origdata; return(TIFFReadDirEntryErrOk); } } data=(uint64*)_TIFFmalloc(count*8); if (data==0) { _TIFFfree(origdata); return(TIFFReadDirEntryErrAlloc); } switch (direntry->tdir_type) { case TIFF_BYTE: { uint8* ma; uint64* mb; uint32 n; ma=(uint8*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(uint64)(*ma++); } break; case TIFF_SBYTE: { int8* ma; uint64* mb; uint32 n; ma=(int8*)origdata; mb=data; for (n=0; n<count; n++) { err=TIFFReadDirEntryCheckRangeLong8Sbyte(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint64)(*ma++); } } break; case TIFF_SHORT: { uint16* ma; uint64* mb; uint32 n; ma=(uint16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort(ma); *mb++=(uint64)(*ma++); } } break; case TIFF_SSHORT: { int16* ma; uint64* mb; uint32 n; ma=(int16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)ma); err=TIFFReadDirEntryCheckRangeLong8Sshort(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint64)(*ma++); } } break; case TIFF_LONG: { uint32* ma; uint64* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); *mb++=(uint64)(*ma++); } } break; case TIFF_SLONG: { int32* ma; uint64* mb; uint32 n; ma=(int32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)ma); err=TIFFReadDirEntryCheckRangeLong8Slong(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint64)(*ma++); } } break; } _TIFFfree(origdata); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(data); return(err); } *value=data; return(TIFFReadDirEntryErrOk); } Commit Message: * libtiff/tif_dirread.c: modify ChopUpSingleUncompressedStrip() to instanciate compute ntrips as TIFFhowmany_32(td->td_imagelength, rowsperstrip), instead of a logic based on the total size of data. Which is faulty is the total size of data is not sufficient to fill the whole image, and thus results in reading outside of the StripByCounts/StripOffsets arrays when using TIFFReadScanline(). Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2608. * libtiff/tif_strip.c: revert the change in TIFFNumberOfStrips() done for http://bugzilla.maptools.org/show_bug.cgi?id=2587 / CVE-2016-9273 since the above change is a better fix that makes it unnecessary. 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: GLboolean WebGLRenderingContextBase::isProgram(WebGLProgram* program) { if (!program || isContextLost()) return 0; return ContextGL()->IsProgram(program->Object()); } Commit Message: Validate all incoming WebGLObjects. A few entry points were missing the correct validation. Tested with improved conformance tests in https://github.com/KhronosGroup/WebGL/pull/2654 . Bug: 848914 Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008 Reviewed-on: https://chromium-review.googlesource.com/1086718 Reviewed-by: Kai Ninomiya <[email protected]> Reviewed-by: Antoine Labour <[email protected]> Commit-Queue: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#565016} 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: InspectorResourceAgent::InspectorResourceAgent(InspectorPageAgent* pageAgent, InspectorClient* client) : InspectorBaseAgent<InspectorResourceAgent>("Network") , m_pageAgent(pageAgent) , m_client(client) , m_frontend(0) , m_resourcesData(adoptPtr(new NetworkResourcesData())) , m_isRecalculatingStyle(false) { } Commit Message: [4/4] Process clearBrowserCahce/cookies commands in browser. BUG=366585 Review URL: https://codereview.chromium.org/251183005 git-svn-id: svn://svn.chromium.org/blink/trunk@172984 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: void usbnet_tx_timeout (struct net_device *net) { struct usbnet *dev = netdev_priv(net); unlink_urbs (dev, &dev->txq); tasklet_schedule (&dev->bh); /* this needs to be handled individually because the generic layer * doesn't know what is sufficient and could not restore private * information if a remedy of an unconditional reset were used. */ if (dev->driver_info->recover) (dev->driver_info->recover)(dev); } 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: void kvm_arch_hardware_disable(void *garbage) { } Commit Message: ARM: KVM: prevent NULL pointer dereferences with KVM VCPU ioctl Some ARM KVM VCPU ioctls require the vCPU to be properly initialized with the KVM_ARM_VCPU_INIT ioctl before being used with further requests. KVM_RUN checks whether this initialization has been done, but other ioctls do not. Namely KVM_GET_REG_LIST will dereference an array with index -1 without initialization and thus leads to a kernel oops. Fix this by adding checks before executing the ioctl handlers. [ Removed superflous comment from static function - Christoffer ] Changes from v1: * moved check into a static function with a meaningful name Signed-off-by: Andre Przywara <[email protected]> Signed-off-by: Christoffer Dall <[email protected]> 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: void CrosLibrary::TestApi::SetNetworkLibrary( NetworkLibrary* library, bool own) { library_->network_lib_.SetImpl(library, own); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 Target: 1 Example 2: Code: generic_load_microcode_early(struct microcode_intel **mc_saved_p, unsigned int mc_saved_count, struct ucode_cpu_info *uci) { struct microcode_intel *ucode_ptr, *new_mc = NULL; int new_rev = uci->cpu_sig.rev; enum ucode_state state = UCODE_OK; unsigned int mc_size; struct microcode_header_intel *mc_header; unsigned int csig = uci->cpu_sig.sig; unsigned int cpf = uci->cpu_sig.pf; int i; for (i = 0; i < mc_saved_count; i++) { ucode_ptr = mc_saved_p[i]; mc_header = (struct microcode_header_intel *)ucode_ptr; mc_size = get_totalsize(mc_header); if (get_matching_microcode(csig, cpf, ucode_ptr, new_rev)) { new_rev = mc_header->rev; new_mc = ucode_ptr; } } if (!new_mc) { state = UCODE_NFOUND; goto out; } uci->mc = (struct microcode_intel *)new_mc; out: return state; } Commit Message: x86/microcode/intel: Guard against stack overflow in the loader mc_saved_tmp is a static array allocated on the stack, we need to make sure mc_saved_count stays within its bounds, otherwise we're overflowing the stack in _save_mc(). A specially crafted microcode header could lead to a kernel crash or potentially kernel execution. Signed-off-by: Quentin Casasnovas <[email protected]> Cc: "H. Peter Anvin" <[email protected]> Cc: Fenghua Yu <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Borislav Petkov <[email protected]> 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 void set_own_dir(const char *argv0) { size_t l = strlen(argv0); while(l && argv0[l - 1] != '/') l--; if(l == 0) memcpy(own_dir, ".", 2); else { memcpy(own_dir, argv0, l - 1); own_dir[l] = 0; } } Commit Message: fix for CVE-2015-3887 closes #60 CWE ID: CWE-426 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 DownloadItemImpl::OnDownloadRenamedToFinalName( DownloadFileManager* file_manager, const FilePath& full_path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); VLOG(20) << __FUNCTION__ << "()" << " full_path = \"" << full_path.value() << "\"" << " needed rename = " << NeedsRename() << " " << DebugString(false); DCHECK(NeedsRename()); if (!full_path.empty()) { target_path_ = full_path; SetFullPath(full_path); delegate_->DownloadRenamedToFinalName(this); if (delegate_->ShouldOpenDownload(this)) Completed(); else delegate_delayed_complete_ = true; BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&DownloadFileManager::CompleteDownload, file_manager, GetGlobalId())); } } Commit Message: Refactors to simplify rename pathway in DownloadFileManager. This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted due to CrOS failure) with the completion logic moved to after the auto-opening. The tests that test the auto-opening (for web store install) were waiting for download completion to check install, and hence were failing when completion was moved earlier. Doing this right would probably require another state (OPENED). BUG=123998 BUG-134930 [email protected] Review URL: https://chromiumcodereview.appspot.com/10701040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: void DevToolsWindow::StopIndexing(int request_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); IndexingJobsMap::iterator it = indexing_jobs_.find(request_id); if (it == indexing_jobs_.end()) return; it->second->Stop(); indexing_jobs_.erase(it); } Commit Message: DevTools: handle devtools renderer unresponsiveness during beforeunload event interception This patch fixes the crash which happenes under the following conditions: 1. DevTools window is in undocked state 2. DevTools renderer is unresponsive 3. User attempts to close inspected page BUG=322380 Review URL: https://codereview.chromium.org/84883002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@237611 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 int ext4_split_extent_at(handle_t *handle, struct inode *inode, struct ext4_ext_path *path, ext4_lblk_t split, int split_flag, int flags) { ext4_fsblk_t newblock; ext4_lblk_t ee_block; struct ext4_extent *ex, newex, orig_ex; struct ext4_extent *ex2 = NULL; unsigned int ee_len, depth; int err = 0; ext_debug("ext4_split_extents_at: inode %lu, logical" "block %llu\n", inode->i_ino, (unsigned long long)split); ext4_ext_show_leaf(inode, path); depth = ext_depth(inode); ex = path[depth].p_ext; ee_block = le32_to_cpu(ex->ee_block); ee_len = ext4_ext_get_actual_len(ex); newblock = split - ee_block + ext4_ext_pblock(ex); BUG_ON(split < ee_block || split >= (ee_block + ee_len)); err = ext4_ext_get_access(handle, inode, path + depth); if (err) goto out; if (split == ee_block) { /* * case b: block @split is the block that the extent begins with * then we just change the state of the extent, and splitting * is not needed. */ if (split_flag & EXT4_EXT_MARK_UNINIT2) ext4_ext_mark_uninitialized(ex); else ext4_ext_mark_initialized(ex); if (!(flags & EXT4_GET_BLOCKS_PRE_IO)) ext4_ext_try_to_merge(handle, inode, path, ex); err = ext4_ext_dirty(handle, inode, path + path->p_depth); goto out; } /* case a */ memcpy(&orig_ex, ex, sizeof(orig_ex)); ex->ee_len = cpu_to_le16(split - ee_block); if (split_flag & EXT4_EXT_MARK_UNINIT1) ext4_ext_mark_uninitialized(ex); /* * path may lead to new leaf, not to original leaf any more * after ext4_ext_insert_extent() returns, */ err = ext4_ext_dirty(handle, inode, path + depth); if (err) goto fix_extent_len; ex2 = &newex; ex2->ee_block = cpu_to_le32(split); ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block)); ext4_ext_store_pblock(ex2, newblock); if (split_flag & EXT4_EXT_MARK_UNINIT2) ext4_ext_mark_uninitialized(ex2); err = ext4_ext_insert_extent(handle, inode, path, &newex, flags); if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) { err = ext4_ext_zeroout(inode, &orig_ex); if (err) goto fix_extent_len; /* update the extent length and mark as initialized */ ex->ee_len = cpu_to_le16(ee_len); ext4_ext_try_to_merge(handle, inode, path, ex); err = ext4_ext_dirty(handle, inode, path + path->p_depth); goto out; } else if (err) goto fix_extent_len; out: ext4_ext_show_leaf(inode, path); return err; fix_extent_len: ex->ee_len = orig_ex.ee_len; ext4_ext_dirty(handle, inode, path + depth); return err; } 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:
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: v8::Local<v8::Value> V8Debugger::collectionEntries(v8::Local<v8::Context> context, v8::Local<v8::Object> object) { if (!enabled()) { NOTREACHED(); return v8::Undefined(m_isolate); } v8::Local<v8::Value> argv[] = { object }; v8::Local<v8::Value> entriesValue = callDebuggerMethod("getCollectionEntries", 1, argv).ToLocalChecked(); if (!entriesValue->IsArray()) return v8::Undefined(m_isolate); v8::Local<v8::Array> entries = entriesValue.As<v8::Array>(); if (!markArrayEntriesAsInternal(context, entries, V8InternalValueType::kEntry)) return v8::Undefined(m_isolate); if (!entries->SetPrototype(context, v8::Null(m_isolate)).FromMaybe(false)) return v8::Undefined(m_isolate); return entries; } Commit Message: [DevTools] Copy objects from debugger context to inspected context properly. BUG=637594 Review-Url: https://codereview.chromium.org/2253643002 Cr-Commit-Position: refs/heads/master@{#412436} CWE ID: CWE-79 Target: 1 Example 2: Code: unsigned short js_touint16(js_State *J, int idx) { return jsV_numbertouint16(jsV_tonumber(J, stackidx(J, idx))); } 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: void ResetVLogInitialized() { UninitializeStatisticsRecorder(); StatisticsRecorder::is_vlog_initialized_ = false; } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} 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: main (int argc, char **argv) { mode_t old_umask; cleanup_free char *base_path = NULL; int clone_flags; char *old_cwd = NULL; pid_t pid; int event_fd = -1; int child_wait_fd = -1; const char *new_cwd; uid_t ns_uid; gid_t ns_gid; struct stat sbuf; uint64_t val; int res UNUSED; real_uid = getuid (); real_gid = getgid (); /* Get the (optional) privileges we need */ acquire_privs (); /* Never gain any more privs during exec */ if (prctl (PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) die_with_error ("prctl(PR_SET_NO_NEW_CAPS) failed"); /* The initial code is run with high permissions (i.e. CAP_SYS_ADMIN), so take lots of care. */ read_overflowids (); argv0 = argv[0]; if (isatty (1)) host_tty_dev = ttyname (1); argv++; argc--; if (argc == 0) usage (EXIT_FAILURE, stderr); parse_args (&argc, &argv); /* We have to do this if we weren't installed setuid (and we're not * root), so let's just DWIM */ if (!is_privileged && getuid () != 0) opt_unshare_user = TRUE; if (opt_unshare_user_try && stat ("/proc/self/ns/user", &sbuf) == 0) { bool disabled = FALSE; /* RHEL7 has a kernel module parameter that lets you enable user namespaces */ if (stat ("/sys/module/user_namespace/parameters/enable", &sbuf) == 0) { cleanup_free char *enable = NULL; enable = load_file_at (AT_FDCWD, "/sys/module/user_namespace/parameters/enable"); if (enable != NULL && enable[0] == 'N') disabled = TRUE; } /* Debian lets you disable *unprivileged* user namespaces. However this is not a problem if we're privileged, and if we're not opt_unshare_user is TRUE already, and there is not much we can do, its just a non-working setup. */ if (!disabled) opt_unshare_user = TRUE; } if (argc == 0) usage (EXIT_FAILURE, stderr); __debug__ (("Creating root mount point\n")); if (opt_sandbox_uid == -1) opt_sandbox_uid = real_uid; if (opt_sandbox_gid == -1) opt_sandbox_gid = real_gid; if (!opt_unshare_user && opt_sandbox_uid != real_uid) die ("Specifying --uid requires --unshare-user"); if (!opt_unshare_user && opt_sandbox_gid != real_gid) die ("Specifying --gid requires --unshare-user"); if (!opt_unshare_uts && opt_sandbox_hostname != NULL) die ("Specifying --hostname requires --unshare-uts"); /* We need to read stuff from proc during the pivot_root dance, etc. Lets keep a fd to it open */ proc_fd = open ("/proc", O_RDONLY | O_PATH); if (proc_fd == -1) die_with_error ("Can't open /proc"); /* We need *some* mountpoint where we can mount the root tmpfs. We first try in /run, and if that fails, try in /tmp. */ base_path = xasprintf ("/run/user/%d/.bubblewrap", real_uid); if (mkdir (base_path, 0755) && errno != EEXIST) { free (base_path); base_path = xasprintf ("/tmp/.bubblewrap-%d", real_uid); if (mkdir (base_path, 0755) && errno != EEXIST) die_with_error ("Creating root mountpoint failed"); } __debug__ (("creating new namespace\n")); if (opt_unshare_pid) { event_fd = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK); if (event_fd == -1) die_with_error ("eventfd()"); } /* We block sigchild here so that we can use signalfd in the monitor. */ block_sigchild (); clone_flags = SIGCHLD | CLONE_NEWNS; if (opt_unshare_user) clone_flags |= CLONE_NEWUSER; if (opt_unshare_pid) clone_flags |= CLONE_NEWPID; if (opt_unshare_net) clone_flags |= CLONE_NEWNET; if (opt_unshare_ipc) clone_flags |= CLONE_NEWIPC; if (opt_unshare_uts) clone_flags |= CLONE_NEWUTS; if (opt_unshare_cgroup) { if (stat ("/proc/self/ns/cgroup", &sbuf)) { if (errno == ENOENT) die ("Cannot create new cgroup namespace because the kernel does not support it"); else die_with_error ("stat on /proc/self/ns/cgroup failed"); } clone_flags |= CLONE_NEWCGROUP; } if (opt_unshare_cgroup_try) if (!stat ("/proc/self/ns/cgroup", &sbuf)) clone_flags |= CLONE_NEWCGROUP; child_wait_fd = eventfd (0, EFD_CLOEXEC); if (child_wait_fd == -1) die_with_error ("eventfd()"); pid = raw_clone (clone_flags, NULL); if (pid == -1) { if (opt_unshare_user) { if (errno == EINVAL) die ("Creating new namespace failed, likely because the kernel does not support user namespaces. bwrap must be installed setuid on such systems."); else if (errno == EPERM && !is_privileged) die ("No permissions to creating new namespace, likely because the kernel does not allow non-privileged user namespaces. On e.g. debian this can be enabled with 'sysctl kernel.unprivileged_userns_clone=1'."); } die_with_error ("Creating new namespace failed"); } ns_uid = opt_sandbox_uid; ns_gid = opt_sandbox_gid; if (pid != 0) { /* Parent, outside sandbox, privileged (initially) */ if (is_privileged && opt_unshare_user) { /* We're running as euid 0, but the uid we want to map is * not 0. This means we're not allowed to write this from * the child user namespace, so we do it from the parent. * * Also, we map uid/gid 0 in the namespace (to overflowuid) * if opt_needs_devpts is true, because otherwise the mount * of devpts fails due to root not being mapped. */ write_uid_gid_map (ns_uid, real_uid, ns_gid, real_gid, pid, TRUE, opt_needs_devpts); } /* Initial launched process, wait for exec:ed command to exit */ /* We don't need any privileges in the launcher, drop them immediately. */ drop_privs (); /* Let child run now that the uid maps are set up */ val = 1; res = write (child_wait_fd, &val, 8); /* Ignore res, if e.g. the child died and closed child_wait_fd we don't want to error out here */ close (child_wait_fd); if (opt_info_fd != -1) { cleanup_free char *output = xasprintf ("{\n \"child-pid\": %i\n}\n", pid); size_t len = strlen (output); if (write (opt_info_fd, output, len) != len) die_with_error ("Write to info_fd"); close (opt_info_fd); } monitor_child (event_fd); exit (0); /* Should not be reached, but better safe... */ } /* Child, in sandbox, privileged in the parent or in the user namespace (if --unshare-user). * * Note that for user namespaces we run as euid 0 during clone(), so * the child user namespace is owned by euid 0., This means that the * regular user namespace parent (with uid != 0) doesn't have any * capabilities in it, which is nice as we can't exploit those. In * particular the parent user namespace doesn't have CAP_PTRACE * which would otherwise allow the parent to hijack of the child * after this point. * * Unfortunately this also means you can't ptrace the final * sandboxed process from outside the sandbox either. */ if (opt_info_fd != -1) close (opt_info_fd); /* Wait for the parent to init uid/gid maps and drop caps */ res = read (child_wait_fd, &val, 8); close (child_wait_fd); /* At this point we can completely drop root uid, but retain the * required permitted caps. This allow us to do full setup as * the user uid, which makes e.g. fuse access work. */ switch_to_user_with_privs (); if (opt_unshare_net && loopback_setup () != 0) die ("Can't create loopback device"); ns_uid = opt_sandbox_uid; ns_gid = opt_sandbox_gid; if (!is_privileged && opt_unshare_user) { /* In the unprivileged case we have to write the uid/gid maps in * the child, because we have no caps in the parent */ if (opt_needs_devpts) { /* This is a bit hacky, but we need to first map the real uid/gid to 0, otherwise we can't mount the devpts filesystem because root is not mapped. Later we will create another child user namespace and map back to the real uid */ ns_uid = 0; ns_gid = 0; } write_uid_gid_map (ns_uid, real_uid, ns_gid, real_gid, -1, TRUE, FALSE); } old_umask = umask (0); /* Need to do this before the chroot, but after we're the real uid */ resolve_symlinks_in_ops (); /* Mark everything as slave, so that we still * receive mounts from the real root, but don't * propagate mounts to the real root. */ if (mount (NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) die_with_error ("Failed to make / slave"); /* Create a tmpfs which we will use as / in the namespace */ if (mount ("", base_path, "tmpfs", MS_NODEV | MS_NOSUID, NULL) != 0) die_with_error ("Failed to mount tmpfs"); old_cwd = get_current_dir_name (); /* Chdir to the new root tmpfs mount. This will be the CWD during the entire setup. Access old or new root via "oldroot" and "newroot". */ if (chdir (base_path) != 0) die_with_error ("chdir base_path"); /* We create a subdir "$base_path/newroot" for the new root, that * way we can pivot_root to base_path, and put the old root at * "$base_path/oldroot". This avoids problems accessing the oldroot * dir if the user requested to bind mount something over / */ if (mkdir ("newroot", 0755)) die_with_error ("Creating newroot failed"); if (mkdir ("oldroot", 0755)) die_with_error ("Creating oldroot failed"); if (pivot_root (base_path, "oldroot")) die_with_error ("pivot_root"); if (chdir ("/") != 0) die_with_error ("chdir / (base path)"); if (is_privileged) { pid_t child; int privsep_sockets[2]; if (socketpair (AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, privsep_sockets) != 0) die_with_error ("Can't create privsep socket"); child = fork (); if (child == -1) die_with_error ("Can't fork unprivileged helper"); if (child == 0) { /* Unprivileged setup process */ drop_privs (); close (privsep_sockets[0]); setup_newroot (opt_unshare_pid, privsep_sockets[1]); exit (0); } else { int status; uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */ uint32_t op, flags; const char *arg1, *arg2; cleanup_fd int unpriv_socket = -1; unpriv_socket = privsep_sockets[0]; close (privsep_sockets[1]); do { op = read_priv_sec_op (unpriv_socket, buffer, sizeof (buffer), &flags, &arg1, &arg2); privileged_op (-1, op, flags, arg1, arg2); if (write (unpriv_socket, buffer, 1) != 1) die ("Can't write to op_socket"); } while (op != PRIV_SEP_OP_DONE); waitpid (child, &status, 0); /* Continue post setup */ } } else { setup_newroot (opt_unshare_pid, -1); } /* The old root better be rprivate or we will send unmount events to the parent namespace */ if (mount ("oldroot", "oldroot", NULL, MS_REC | MS_PRIVATE, NULL) != 0) die_with_error ("Failed to make old root rprivate"); if (umount2 ("oldroot", MNT_DETACH)) die_with_error ("unmount old root"); if (opt_unshare_user && (ns_uid != opt_sandbox_uid || ns_gid != opt_sandbox_gid)) { /* Now that devpts is mounted and we've no need for mount permissions we can create a new userspace and map our uid 1:1 */ if (unshare (CLONE_NEWUSER)) die_with_error ("unshare user ns"); write_uid_gid_map (opt_sandbox_uid, ns_uid, opt_sandbox_gid, ns_gid, -1, FALSE, FALSE); } /* Now make /newroot the real root */ if (chdir ("/newroot") != 0) die_with_error ("chdir newroot"); if (chroot ("/newroot") != 0) die_with_error ("chroot /newroot"); if (chdir ("/") != 0) die_with_error ("chdir /"); /* All privileged ops are done now, so drop it */ drop_privs (); if (opt_block_fd != -1) { char b[1]; read (opt_block_fd, b, 1); close (opt_block_fd); } if (opt_seccomp_fd != -1) { cleanup_free char *seccomp_data = NULL; size_t seccomp_len; struct sock_fprog prog; seccomp_data = load_file_data (opt_seccomp_fd, &seccomp_len); if (seccomp_data == NULL) die_with_error ("Can't read seccomp data"); if (seccomp_len % 8 != 0) die ("Invalid seccomp data, must be multiple of 8"); prog.len = seccomp_len / 8; prog.filter = (struct sock_filter *) seccomp_data; close (opt_seccomp_fd); if (prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog) != 0) die_with_error ("prctl(PR_SET_SECCOMP)"); } umask (old_umask); new_cwd = "/"; if (opt_chdir_path) { if (chdir (opt_chdir_path)) die_with_error ("Can't chdir to %s", opt_chdir_path); new_cwd = opt_chdir_path; } else if (chdir (old_cwd) == 0) { /* If the old cwd is mapped in the sandbox, go there */ new_cwd = old_cwd; } else { /* If the old cwd is not mapped, go to home */ const char *home = getenv ("HOME"); if (home != NULL && chdir (home) == 0) new_cwd = home; } xsetenv ("PWD", new_cwd, 1); free (old_cwd); __debug__ (("forking for child\n")); if (opt_unshare_pid || lock_files != NULL || opt_sync_fd != -1) { /* We have to have a pid 1 in the pid namespace, because * otherwise we'll get a bunch of zombies as nothing reaps * them. Alternatively if we're using sync_fd or lock_files we * need some process to own these. */ pid = fork (); if (pid == -1) die_with_error ("Can't fork for pid 1"); if (pid != 0) { /* Close fds in pid 1, except stdio and optionally event_fd (for syncing pid 2 lifetime with monitor_child) and opt_sync_fd (for syncing sandbox lifetime with outside process). Any other fds will been passed on to the child though. */ { int dont_close[3]; int j = 0; if (event_fd != -1) dont_close[j++] = event_fd; if (opt_sync_fd != -1) dont_close[j++] = opt_sync_fd; dont_close[j++] = -1; fdwalk (proc_fd, close_extra_fds, dont_close); } return do_init (event_fd, pid); } } __debug__ (("launch executable %s\n", argv[0])); if (proc_fd != -1) close (proc_fd); if (opt_sync_fd != -1) close (opt_sync_fd); /* We want sigchild in the child */ unblock_sigchild (); if (label_exec (opt_exec_label) == -1) die_with_error ("label_exec %s", argv[0]); if (execvp (argv[0], argv) == -1) die_with_error ("execvp %s", argv[0]); return 0; } Commit Message: Call setsid() before executing sandboxed code (CVE-2017-5226) This prevents the sandboxed code from getting a controlling tty, which in turn prevents it from accessing the TIOCSTI ioctl and hence faking terminal input. Fixes: #142 Closes: #143 Approved by: cgwalters CWE ID: CWE-20 Target: 1 Example 2: Code: FLAC__StreamDecoderTellStatus FLACParser::tell_callback( const FLAC__StreamDecoder * /* decoder */, FLAC__uint64 *absolute_byte_offset, void *client_data) { return ((FLACParser *) client_data)->tellCallback(absolute_byte_offset); } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 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 ProcessStateChangesPlanB(WebRtcSetDescriptionObserver::States states) { DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kPlanB); std::vector<RTCRtpReceiver*> removed_receivers; for (auto it = handler_->rtp_receivers_.begin(); it != handler_->rtp_receivers_.end(); ++it) { if (ReceiverWasRemoved(*(*it), states.transceiver_states)) removed_receivers.push_back(it->get()); } for (auto& transceiver_state : states.transceiver_states) { if (ReceiverWasAdded(transceiver_state)) { handler_->OnAddReceiverPlanB(transceiver_state.MoveReceiverState()); } } for (auto* removed_receiver : removed_receivers) { handler_->OnRemoveReceiverPlanB(RTCRtpReceiver::getId( removed_receiver->state().webrtc_receiver().get())); } } Commit Message: Check weak pointers in RTCPeerConnectionHandler::WebRtcSetDescriptionObserverImpl Bug: 912074 Change-Id: I8ba86751f5d5bf12db51520f985ef0d3dae63ed8 Reviewed-on: https://chromium-review.googlesource.com/c/1411916 Commit-Queue: Guido Urdaneta <[email protected]> Reviewed-by: Henrik Boström <[email protected]> Cr-Commit-Position: refs/heads/master@{#622945} 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: ShellContentUtilityClient::ShellContentUtilityClient() { if (base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kProcessType) == switches::kUtilityProcess) network_service_test_helper_ = std::make_unique<NetworkServiceTestHelper>(); } Commit Message: Fix content_shell with network service enabled not loading pages. This regressed in my earlier cl r528763. This is a reland of r547221. Bug: 833612 Change-Id: I4c2649414d42773f2530e1abe5912a04fcd0ed9b Reviewed-on: https://chromium-review.googlesource.com/1064702 Reviewed-by: Jay Civelli <[email protected]> Commit-Queue: John Abd-El-Malek <[email protected]> Cr-Commit-Position: refs/heads/master@{#560011} CWE ID: CWE-264 Target: 1 Example 2: Code: static int muscle_delete_mscfs_file(sc_card_t *card, mscfs_file_t *file_data) { mscfs_t *fs = MUSCLE_FS(card); msc_id id = file_data->objectId; u8* oid = id.id; int r; if(!file_data->ef) { int x; mscfs_file_t *childFile; /* Delete children */ mscfs_check_cache(fs); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "DELETING Children of: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); for(x = 0; x < fs->cache.size; x++) { msc_id objectId; childFile = &fs->cache.array[x]; objectId = childFile->objectId; if(0 == memcmp(oid + 2, objectId.id, 2)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "DELETING: %02X%02X%02X%02X\n", objectId.id[0],objectId.id[1], objectId.id[2],objectId.id[3]); r = muscle_delete_mscfs_file(card, childFile); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } } oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; /* ??? objectId = objectId >> 16; */ } if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4)) || (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) { } r = msc_delete_object(card, id, 1); /* Check if its the root... this file generally is virtual * So don't return an error if it fails */ if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4)) || (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) return 0; if(r < 0) { printf("ID: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } return 0; } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. 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: bool RenderFrameImpl::UniqueNameFrameAdapter::IsCandidateUnique( base::StringPiece name) const { DCHECK(!name.empty()); for (blink::WebFrame* frame = GetWebFrame()->Top(); frame; frame = frame->TraverseNext()) { if (UniqueNameForWebFrame(frame) == name) return false; } return true; } 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: produce_output() { char *str; FILE *mailer; MyString subject,szTmp; subject.sprintf("condor_preen results %s: %d old file%s found", my_full_hostname(), BadFiles->number(), (BadFiles->number() > 1)?"s":""); if( MailFlag ) { if( (mailer=email_open(PreenAdmin, subject.Value())) == NULL ) { EXCEPT( "Can't do email_open(\"%s\", \"%s\")\n",PreenAdmin,subject.Value()); } } else { mailer = stdout; } szTmp.sprintf("The condor_preen process has found the following stale condor files on <%s>:\n\n", get_local_hostname().Value()); dprintf(D_ALWAYS, szTmp.Value()); if( MailFlag ) { fprintf( mailer, "\n" ); fprintf( mailer, szTmp.Value()); } for( BadFiles->rewind(); (str = BadFiles->next()); ) { szTmp.sprintf(" %s\n", str); dprintf(D_ALWAYS, szTmp.Value() ); fprintf( mailer, szTmp.Value() ); } if( MailFlag ) { const char *explanation = "\n\nWhat is condor_preen?\n\n" "The condor_preen tool examines the directories belonging to Condor, and\n" "removes extraneous files and directories which may be left over from Condor\n" "processes which terminated abnormally either due to internal errors or a\n" "system crash. The directories checked are the LOG, EXECUTE, and SPOOL\n" "directories as defined in the Condor configuration files. The condor_preen\n" "tool is intended to be run as user root (or user condor) periodically as a\n" "backup method to ensure reasonable file system cleanliness in the face of\n" "errors. This is done automatically by default by the condor_master daemon.\n" "It may also be explicitly invoked on an as needed basis.\n\n" "See the Condor manual section on condor_preen for more details.\n"; fprintf( mailer, "%s\n", explanation ); email_close( mailer ); } } Commit Message: CWE ID: CWE-134 Target: 1 Example 2: Code: bool CSSPaintValue::Equals(const CSSPaintValue& other) const { return GetName() == other.GetName() && CustomCSSText() == other.CustomCSSText(); } Commit Message: [PaintWorklet] Do not paint when paint target is associated with a link When the target element of a paint worklet has an associated link, then the 'paint' function will be invoked when the link's href is changed from a visited URL to an unvisited URL (or vice versa). This CL changes the behavior by detecting whether the target element of a paint worklet has an associated link or not. If it does, then don't paint. [email protected] Bug: 835589 Change-Id: I5fdf85685f863c960a6f48cc9a345dda787bece1 Reviewed-on: https://chromium-review.googlesource.com/1035524 Reviewed-by: Xida Chen <[email protected]> Reviewed-by: Ian Kilpatrick <[email protected]> Reviewed-by: Stephen McGruer <[email protected]> Commit-Queue: Xida Chen <[email protected]> Cr-Commit-Position: refs/heads/master@{#555788} 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: io_set_process_status(mrb_state *mrb, pid_t pid, int status) { struct RClass *c_process, *c_status; mrb_value v; c_status = NULL; if (mrb_class_defined(mrb, "Process")) { c_process = mrb_module_get(mrb, "Process"); if (mrb_const_defined(mrb, mrb_obj_value(c_process), mrb_intern_cstr(mrb, "Status"))) { c_status = mrb_class_get_under(mrb, c_process, "Status"); } } if (c_status != NULL) { v = mrb_funcall(mrb, mrb_obj_value(c_status), "new", 2, mrb_fixnum_value(pid), mrb_fixnum_value(status)); } else { v = mrb_fixnum_value(WEXITSTATUS(status)); } mrb_gv_set(mrb, mrb_intern_cstr(mrb, "$?"), v); } Commit Message: Fix `use after free in File#initilialize_copy`; fix #4001 The bug and the fix were reported by https://hackerone.com/pnoltof CWE ID: CWE-416 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 _gd2GetHeader(gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx) { int i; int ch; char id[5]; t_chunk_info *cidx; int sidx; int nc; GD2_DBG(php_gd_error("Reading gd2 header info")); for (i = 0; i < 4; i++) { ch = gdGetC(in); if (ch == EOF) { goto fail1; } id[i] = ch; } id[4] = 0; GD2_DBG(php_gd_error("Got file code: %s", id)); /* Equiv. of 'magick'. */ if (strcmp(id, GD2_ID) != 0) { GD2_DBG(php_gd_error("Not a valid gd2 file")); goto fail1; } /* Version */ if (gdGetWord(vers, in) != 1) { goto fail1; } GD2_DBG(php_gd_error("Version: %d", *vers)); if ((*vers != 1) && (*vers != 2)) { GD2_DBG(php_gd_error("Bad version: %d", *vers)); goto fail1; } /* Image Size */ if (!gdGetWord(sx, in)) { GD2_DBG(php_gd_error("Could not get x-size")); goto fail1; } if (!gdGetWord(sy, in)) { GD2_DBG(php_gd_error("Could not get y-size")); goto fail1; } GD2_DBG(php_gd_error("Image is %dx%d", *sx, *sy)); /* Chunk Size (pixels, not bytes!) */ if (gdGetWord(cs, in) != 1) { goto fail1; } GD2_DBG(php_gd_error("ChunkSize: %d", *cs)); if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) { GD2_DBG(php_gd_error("Bad chunk size: %d", *cs)); goto fail1; } /* Data Format */ if (gdGetWord(fmt, in) != 1) { goto fail1; } GD2_DBG(php_gd_error("Format: %d", *fmt)); if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) { GD2_DBG(php_gd_error("Bad data format: %d", *fmt)); goto fail1; } /* # of chunks wide */ if (gdGetWord(ncx, in) != 1) { goto fail1; } GD2_DBG(php_gd_error("%d Chunks Wide", *ncx)); /* # of chunks high */ if (gdGetWord(ncy, in) != 1) { goto fail1; } GD2_DBG(php_gd_error("%d Chunks vertically", *ncy)); if (gd2_compressed(*fmt)) { nc = (*ncx) * (*ncy); GD2_DBG(php_gd_error("Reading %d chunk index entries", nc)); sidx = sizeof(t_chunk_info) * nc; if (sidx <= 0) { goto fail1; } cidx = gdCalloc(sidx, 1); for (i = 0; i < nc; i++) { if (gdGetInt(&cidx[i].offset, in) != 1) { gdFree(cidx); goto fail1; } if (gdGetInt(&cidx[i].size, in) != 1) { gdFree(cidx); goto fail1; } if (cidx[i].offset < 0 || cidx[i].size < 0) { gdFree(cidx); goto fail1; } } *chunkIdx = cidx; } GD2_DBG(php_gd_error("gd2 header complete")); return 1; fail1: return 0; } Commit Message: Fixed #72339 Integer Overflow in _gd2GetHeader() resulting in heap overflow CWE ID: CWE-190 Target: 1 Example 2: Code: void InspectorNetworkAgent::DetachClientRequest( ThreadableLoaderClient* client) { if (pending_request_ == client) { pending_request_ = nullptr; if (pending_request_type_ == InspectorPageAgent::kXHRResource) { pending_xhr_replay_data_.Clear(); } } known_request_id_map_.erase(client); } 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: PassRefPtrWillBeRawPtr<DocumentParser> Document::implicitOpen(ParserSynchronizationPolicy parserSyncPolicy) { cancelParsing(); removeChildren(); ASSERT(!m_focusedElement); setCompatibilityMode(NoQuirksMode); m_parserSyncPolicy = parserSyncPolicy; m_parser = createParser(); setParsingState(Parsing); setReadyState(Loading); return m_parser; } 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: int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len) { struct super_block *sb = inode->i_sb; ext4_lblk_t punch_start, punch_stop; handle_t *handle; unsigned int credits; loff_t new_size, ioffset; int ret; /* * We need to test this early because xfstests assumes that a * collapse range of (0, 1) will return EOPNOTSUPP if the file * system does not support collapse range. */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) return -EOPNOTSUPP; /* Collapse range works only on fs block size aligned offsets. */ if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) || len & (EXT4_CLUSTER_SIZE(sb) - 1)) return -EINVAL; if (!S_ISREG(inode->i_mode)) return -EINVAL; trace_ext4_collapse_range(inode, offset, len); punch_start = offset >> EXT4_BLOCK_SIZE_BITS(sb); punch_stop = (offset + len) >> EXT4_BLOCK_SIZE_BITS(sb); /* Call ext4_force_commit to flush all data in case of data=journal. */ if (ext4_should_journal_data(inode)) { ret = ext4_force_commit(inode->i_sb); if (ret) return ret; } /* * Need to round down offset to be aligned with page size boundary * for page size > block size. */ ioffset = round_down(offset, PAGE_SIZE); /* Write out all dirty pages */ ret = filemap_write_and_wait_range(inode->i_mapping, ioffset, LLONG_MAX); if (ret) return ret; /* Take mutex lock */ mutex_lock(&inode->i_mutex); /* * There is no need to overlap collapse range with EOF, in which case * it is effectively a truncate operation */ if (offset + len >= i_size_read(inode)) { ret = -EINVAL; goto out_mutex; } /* Currently just for extent based files */ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { ret = -EOPNOTSUPP; goto out_mutex; } truncate_pagecache(inode, ioffset); /* Wait for existing dio to complete */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); credits = ext4_writepage_trans_blocks(inode); handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out_dio; } down_write(&EXT4_I(inode)->i_data_sem); ext4_discard_preallocations(inode); ret = ext4_es_remove_extent(inode, punch_start, EXT_MAX_BLOCKS - punch_start); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } ret = ext4_ext_remove_space(inode, punch_start, punch_stop - 1); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } ext4_discard_preallocations(inode); ret = ext4_ext_shift_extents(inode, handle, punch_stop, punch_stop - punch_start, SHIFT_LEFT); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } new_size = i_size_read(inode) - len; i_size_write(inode, new_size); EXT4_I(inode)->i_disksize = new_size; up_write(&EXT4_I(inode)->i_data_sem); if (IS_SYNC(inode)) ext4_handle_sync(handle); inode->i_mtime = inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); out_stop: ext4_journal_stop(handle); out_dio: ext4_inode_resume_unlocked_dio(inode); out_mutex: mutex_unlock(&inode->i_mutex); return ret; } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: static int do_maps_open(struct inode *inode, struct file *file, const struct seq_operations *ops) { return proc_maps_open(inode, file, ops, sizeof(struct proc_maps_private)); } Commit Message: pagemap: do not leak physical addresses to non-privileged userspace As pointed by recent post[1] on exploiting DRAM physical imperfection, /proc/PID/pagemap exposes sensitive information which can be used to do attacks. This disallows anybody without CAP_SYS_ADMIN to read the pagemap. [1] http://googleprojectzero.blogspot.com/2015/03/exploiting-dram-rowhammer-bug-to-gain.html [ Eventually we might want to do anything more finegrained, but for now this is the simple model. - Linus ] Signed-off-by: Kirill A. Shutemov <[email protected]> Acked-by: Konstantin Khlebnikov <[email protected]> Acked-by: Andy Lutomirski <[email protected]> Cc: Pavel Emelyanov <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Mark Seaborn <[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: MagickExport MagickBooleanType SetImageProfile(Image *image,const char *name, const StringInfo *profile,ExceptionInfo *exception) { return(SetImageProfileInternal(image,name,profile,MagickFalse,exception)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/280 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: ft_var_readpackedpoints( FT_Stream stream, FT_UInt *point_cnt ) { FT_UShort *points; FT_Int n; FT_Int runcnt; FT_Int i; FT_Int j; FT_Int first; FT_Memory memory = stream->memory; FT_Error error = TT_Err_Ok; FT_UNUSED( error ); *point_cnt = n = FT_GET_BYTE(); if ( n == 0 ) return ALL_POINTS; if ( n & GX_PT_POINTS_ARE_WORDS ) n = FT_GET_BYTE() | ( ( n & GX_PT_POINT_RUN_COUNT_MASK ) << 8 ); if ( FT_NEW_ARRAY( points, n ) ) return NULL; i = 0; while ( i < n ) { runcnt = FT_GET_BYTE(); if ( runcnt & GX_PT_POINTS_ARE_WORDS ) { runcnt = runcnt & GX_PT_POINT_RUN_COUNT_MASK; first = points[i++] = FT_GET_USHORT(); if ( runcnt < 1 ) goto Exit; /* first point not included in runcount */ for ( j = 0; j < runcnt; ++j ) points[i++] = (FT_UShort)( first += FT_GET_USHORT() ); } else { first = points[i++] = FT_GET_BYTE(); if ( runcnt < 1 ) goto Exit; for ( j = 0; j < runcnt; ++j ) points[i++] = (FT_UShort)( first += FT_GET_BYTE() ); } } Exit: return points; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: QuarantineLinuxTest() : source_url_("http://www.source.com"), referrer_url_("http://www.referrer.com"), is_xattr_supported_(false) {} Commit Message: Disable setxattr calls from quarantine subsystem on Chrome OS. BUG=733943 Change-Id: I6e743469a8dc91536e180ecf4ff0df0cf427037c Reviewed-on: https://chromium-review.googlesource.com/c/1380571 Commit-Queue: Will Harris <[email protected]> Reviewed-by: Raymes Khoury <[email protected]> Reviewed-by: David Trainor <[email protected]> Reviewed-by: Thiemo Nagel <[email protected]> Cr-Commit-Position: refs/heads/master@{#617961} 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 LoadsFromCacheOnly(const ResourceRequest& request) { switch (request.GetCachePolicy()) { case WebCachePolicy::kUseProtocolCachePolicy: case WebCachePolicy::kValidatingCacheData: case WebCachePolicy::kBypassingCache: case WebCachePolicy::kReturnCacheDataElseLoad: return false; case WebCachePolicy::kReturnCacheDataDontLoad: case WebCachePolicy::kReturnCacheDataIfValid: case WebCachePolicy::kBypassCacheLoadOnlyFromCache: return true; } NOTREACHED(); return false; } 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 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::~ContentEncoding() { ContentCompression** comp_i = compression_entries_; ContentCompression** const comp_j = compression_entries_end_; while (comp_i != comp_j) { ContentCompression* const comp = *comp_i++; delete comp; } delete [] compression_entries_; ContentEncryption** enc_i = encryption_entries_; ContentEncryption** const enc_j = encryption_entries_end_; while (enc_i != enc_j) { ContentEncryption* const enc = *enc_i++; delete enc; } delete [] encryption_entries_; } 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: hook_fd_set (fd_set *read_fds, fd_set *write_fds, fd_set *exception_fds) { struct t_hook *ptr_hook; int max_fd; max_fd = 0; for (ptr_hook = weechat_hooks[HOOK_TYPE_FD]; ptr_hook; ptr_hook = ptr_hook->next_hook) { if (!ptr_hook->deleted) { /* skip invalid file descriptors */ if ((fcntl (HOOK_FD(ptr_hook,fd), F_GETFD) == -1) && (errno == EBADF)) { if (HOOK_FD(ptr_hook, error) == 0) { HOOK_FD(ptr_hook, error) = errno; gui_chat_printf (NULL, _("%sError: bad file descriptor (%d) " "used in hook_fd"), gui_chat_prefix[GUI_CHAT_PREFIX_ERROR], HOOK_FD(ptr_hook, fd)); } } else { if (HOOK_FD(ptr_hook, flags) & HOOK_FD_FLAG_READ) { FD_SET (HOOK_FD(ptr_hook, fd), read_fds); if (HOOK_FD(ptr_hook, fd) > max_fd) max_fd = HOOK_FD(ptr_hook, fd); } if (HOOK_FD(ptr_hook, flags) & HOOK_FD_FLAG_WRITE) { FD_SET (HOOK_FD(ptr_hook, fd), write_fds); if (HOOK_FD(ptr_hook, fd) > max_fd) max_fd = HOOK_FD(ptr_hook, fd); } if (HOOK_FD(ptr_hook, flags) & HOOK_FD_FLAG_EXCEPTION) { FD_SET (HOOK_FD(ptr_hook, fd), exception_fds); if (HOOK_FD(ptr_hook, fd) > max_fd) max_fd = HOOK_FD(ptr_hook, fd); } } } } return max_fd; } Commit Message: 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 ExecuteMoveToBeginningOfParagraphAndModifySelection( LocalFrame& frame, Event*, EditorCommandSource, const String&) { frame.Selection().Modify( SelectionModifyAlteration::kExtend, SelectionModifyDirection::kBackward, TextGranularity::kParagraphBoundary, SetSelectionBy::kUser); return true; } Commit Message: Move Editor::Transpose() out of Editor class This patch moves |Editor::Transpose()| out of |Editor| class as preparation of expanding it into |ExecutTranspose()| in "EditorCommand.cpp" to make |Editor| class simpler for improving code health. Following patch will expand |Transpose()| into |ExecutTranspose()|. Bug: 672405 Change-Id: Icde253623f31813d2b4517c4da7d4798bd5fadf6 Reviewed-on: https://chromium-review.googlesource.com/583880 Reviewed-by: Xiaocheng Hu <[email protected]> Commit-Queue: Yoshifumi Inoue <[email protected]> Cr-Commit-Position: refs/heads/master@{#489518} 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: ssize_t nbd_receive_reply(QIOChannel *ioc, NBDReply *reply) { uint8_t buf[NBD_REPLY_SIZE]; uint32_t magic; ssize_t ret; ret = read_sync(ioc, buf, sizeof(buf)); if (ret < 0) { return ret; } if (ret != sizeof(buf)) { LOG("read failed"); return -EINVAL; } /* Reply [ 0 .. 3] magic (NBD_REPLY_MAGIC) [ 4 .. 7] error (0 == no error) [ 7 .. 15] handle */ magic = ldl_be_p(buf); reply->error = ldl_be_p(buf + 4); reply->handle = ldq_be_p(buf + 8); reply->error = nbd_errno_to_system_errno(reply->error); if (reply->error == ESHUTDOWN) { /* This works even on mingw which lacks a native ESHUTDOWN */ LOG("server shutting down"); return -EINVAL; } TRACE("Got reply: { magic = 0x%" PRIx32 ", .error = % " PRId32 ", handle = %" PRIu64" }", magic, reply->error, reply->handle); if (magic != NBD_REPLY_MAGIC) { LOG("invalid magic (got 0x%" PRIx32 ")", magic); return -EINVAL; } return 0; } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: static void __init evm_init_config(void) { #ifdef CONFIG_EVM_ATTR_FSUUID evm_hmac_attrs |= EVM_ATTR_FSUUID; #endif pr_info("HMAC attrs: 0x%x\n", evm_hmac_attrs); } Commit Message: EVM: Use crypto_memneq() for digest comparisons This patch fixes vulnerability CVE-2016-2085. The problem exists because the vm_verify_hmac() function includes a use of memcmp(). Unfortunately, this allows timing side channel attacks; specifically a MAC forgery complexity drop from 2^128 to 2^12. This patch changes the memcmp() to the cryptographically safe crypto_memneq(). Reported-by: Xiaofei Rex Guo <[email protected]> Signed-off-by: Ryan Ware <[email protected]> Cc: [email protected] Signed-off-by: Mimi Zohar <[email protected]> Signed-off-by: James Morris <[email protected]> CWE ID: CWE-19 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: xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { xmlChar limit = 0; xmlChar *buf = NULL; xmlChar *rep = NULL; int len = 0; int buf_size = 0; int c, l, in_space = 0; xmlChar *current = NULL; xmlEntityPtr ent; if (NXT(0) == '"') { ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; limit = '"'; NEXT; } else if (NXT(0) == '\'') { limit = '\''; ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; NEXT; } else { xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL); return(NULL); } /* * allocate a translation buffer. */ buf_size = XML_PARSER_BUFFER_SIZE; buf = (xmlChar *) xmlMallocAtomic(buf_size * sizeof(xmlChar)); if (buf == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. */ c = CUR_CHAR(l); while ((NXT(0) != limit) && /* checked */ (IS_CHAR(c)) && (c != '<')) { if (c == 0) break; if (c == '&') { in_space = 0; if (NXT(1) == '#') { int val = xmlParseCharRef(ctxt); if (val == '&') { if (ctxt->replaceEntities) { if (len > buf_size - 10) { growBuffer(buf, 10); } buf[len++] = '&'; } else { /* * The reparsing will be done in xmlStringGetNodeList() * called by the attribute() function in SAX.c */ if (len > buf_size - 10) { growBuffer(buf, 10); } buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } } else if (val != 0) { if (len > buf_size - 10) { growBuffer(buf, 10); } len += xmlCopyChar(0, &buf[len], val); } } else { ent = xmlParseEntityRef(ctxt); ctxt->nbentities++; if (ent != NULL) ctxt->nbentities += ent->owner; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (len > buf_size - 10) { growBuffer(buf, 10); } if ((ctxt->replaceEntities == 0) && (ent->content[0] == '&')) { buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } else { buf[len++] = ent->content[0]; } } else if ((ent != NULL) && (ctxt->replaceEntities != 0)) { if (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) { rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming */ if ((*current == 0xD) || (*current == 0xA) || (*current == 0x9)) { buf[len++] = 0x20; current++; } else buf[len++] = *current++; if (len > buf_size - 10) { growBuffer(buf, 10); } } xmlFree(rep); rep = NULL; } } else { if (len > buf_size - 10) { growBuffer(buf, 10); } if (ent->content != NULL) buf[len++] = ent->content[0]; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; /* * This may look absurd but is needed to detect * entities problems */ if ((ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && (ent->content != NULL)) { rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); if (rep != NULL) { xmlFree(rep); rep = NULL; } } /* * Just output the reference */ buf[len++] = '&'; while (len > buf_size - i - 10) { growBuffer(buf, i + 10); } for (;i > 0;i--) buf[len++] = *cur++; buf[len++] = ';'; } } } else { if ((c == 0x20) || (c == 0xD) || (c == 0xA) || (c == 0x9)) { if ((len != 0) || (!normalize)) { if ((!normalize) || (!in_space)) { COPY_BUF(l,buf,len,0x20); while (len > buf_size - 10) { growBuffer(buf, 10); } } in_space = 1; } } else { in_space = 0; COPY_BUF(l,buf,len,c); if (len > buf_size - 10) { growBuffer(buf, 10); } } NEXTL(l); } GROW; c = CUR_CHAR(l); } if ((in_space) && (normalize)) { while ((len > 0) && (buf[len - 1] == 0x20)) len--; } buf[len] = 0; if (RAW == '<') { xmlFatalErr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, NULL); } else if (RAW != limit) { if ((c != 0) && (!IS_CHAR(c))) { xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR, "invalid character in attribute value\n"); } else { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, "AttValue: ' expected\n"); } } else NEXT; if (attlen != NULL) *attlen = len; return(buf); mem_error: xmlErrMemory(ctxt, NULL); if (buf != NULL) xmlFree(buf); if (rep != NULL) xmlFree(rep); return(NULL); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 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: struct task_struct * __cpuinit fork_idle(int cpu) { struct task_struct *task; struct pt_regs regs; task = copy_process(CLONE_VM, 0, idle_regs(&regs), 0, NULL, &init_struct_pid, 0); if (!IS_ERR(task)) init_idle(task, cpu); return task; } Commit Message: pids: fix fork_idle() to setup ->pids correctly copy_process(pid => &init_struct_pid) doesn't do attach_pid/etc. It shouldn't, but this means that the idle threads run with the wrong pids copied from the caller's task_struct. In x86 case the caller is either kernel_init() thread or keventd. In particular, this means that after the series of cpu_up/cpu_down an idle thread (which never exits) can run with .pid pointing to nowhere. Change fork_idle() to initialize idle->pids[] correctly. We only set .pid = &init_struct_pid but do not add .node to list, INIT_TASK() does the same for the boot-cpu idle thread (swapper). Signed-off-by: Oleg Nesterov <[email protected]> Cc: Cedric Le Goater <[email protected]> Cc: Dave Hansen <[email protected]> Cc: Eric Biederman <[email protected]> Cc: Herbert Poetzl <[email protected]> Cc: Mathias Krause <[email protected]> Acked-by: Roland McGrath <[email protected]> Acked-by: Serge Hallyn <[email protected]> Cc: Sukadev Bhattiprolu <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: void RenderFrameHostImpl::DispatchBeforeUnload(BeforeUnloadType type, bool is_reload) { bool for_navigation = type == BeforeUnloadType::BROWSER_INITIATED_NAVIGATION || type == BeforeUnloadType::RENDERER_INITIATED_NAVIGATION; DCHECK(for_navigation || !is_reload); DCHECK(type == BeforeUnloadType::BROWSER_INITIATED_NAVIGATION || type == BeforeUnloadType::RENDERER_INITIATED_NAVIGATION || frame_tree_node_->IsMainFrame()); if (!for_navigation) { if (frame_tree_node_->navigation_request() && frame_tree_node_->navigation_request()->navigation_handle()) { frame_tree_node_->navigation_request() ->navigation_handle() ->set_net_error_code(net::ERR_ABORTED); } frame_tree_node_->ResetNavigationRequest(false, true); } bool check_subframes_only = type == BeforeUnloadType::RENDERER_INITIATED_NAVIGATION; if (!ShouldDispatchBeforeUnload(check_subframes_only)) { DCHECK(!for_navigation); base::OnceClosure task = base::BindOnce( [](base::WeakPtr<RenderFrameHostImpl> self) { if (!self) return; self->frame_tree_node_->render_manager()->OnBeforeUnloadACK( true, base::TimeTicks::Now()); }, weak_ptr_factory_.GetWeakPtr()); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(task)); return; } TRACE_EVENT_ASYNC_BEGIN1("navigation", "RenderFrameHostImpl BeforeUnload", this, "&RenderFrameHostImpl", (void*)this); if (is_waiting_for_beforeunload_ack_) { unload_ack_is_for_navigation_ = unload_ack_is_for_navigation_ && for_navigation; } else { is_waiting_for_beforeunload_ack_ = true; beforeunload_dialog_request_cancels_unload_ = false; unload_ack_is_for_navigation_ = for_navigation; send_before_unload_start_time_ = base::TimeTicks::Now(); if (render_view_host_->GetDelegate()->IsJavaScriptDialogShowing()) { SimulateBeforeUnloadAck(type != BeforeUnloadType::DISCARD); } else { if (beforeunload_timeout_) beforeunload_timeout_->Start(beforeunload_timeout_delay_); beforeunload_pending_replies_.clear(); beforeunload_dialog_request_cancels_unload_ = (type == BeforeUnloadType::DISCARD); CheckOrDispatchBeforeUnloadForSubtree(check_subframes_only, true /* send_ipc */, is_reload); } } } 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 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: InspectorFileReaderLoaderClient( RefPtr<BlobDataHandle> blob, const String& mime_type, const String& text_encoding_name, std::unique_ptr<GetResponseBodyCallback> callback) : blob_(std::move(blob)), mime_type_(mime_type), text_encoding_name_(text_encoding_name), callback_(std::move(callback)) { loader_ = FileReaderLoader::Create(FileReaderLoader::kReadByClient, this); } 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 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 HttpProxyClientSocket::DoReadHeadersComplete(int result) { if (result < 0) return result; if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0)) return ERR_TUNNEL_CONNECTION_FAILED; net_log_.AddEvent( NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS, base::Bind(&HttpResponseHeaders::NetLogCallback, response_.headers)); if (proxy_delegate_) { proxy_delegate_->OnTunnelHeadersReceived( HostPortPair::FromURL(request_.url), proxy_server_, *response_.headers); } switch (response_.headers->response_code()) { case 200: // OK if (http_stream_parser_->IsMoreDataBuffered()) return ERR_TUNNEL_CONNECTION_FAILED; next_state_ = STATE_DONE; return OK; case 302: // Found / Moved Temporarily if (is_https_proxy_ && SanitizeProxyRedirect(&response_, request_.url)) { bool is_connection_reused = http_stream_parser_->IsConnectionReused(); redirect_has_load_timing_info_ = transport_->GetLoadTimingInfo( is_connection_reused, &redirect_load_timing_info_); transport_.reset(); http_stream_parser_.reset(); return ERR_HTTPS_PROXY_TUNNEL_RESPONSE; } LogBlockedTunnelResponse(); return ERR_TUNNEL_CONNECTION_FAILED; case 407: // Proxy Authentication Required return HandleProxyAuthChallenge(auth_.get(), &response_, net_log_); default: LogBlockedTunnelResponse(); return ERR_TUNNEL_CONNECTION_FAILED; } } Commit Message: Sanitize headers in Proxy Authentication Required responses BUG=431504 Review URL: https://codereview.chromium.org/769043003 Cr-Commit-Position: refs/heads/master@{#310014} CWE ID: CWE-19 Target: 1 Example 2: Code: ChromeExtensionsAPIClient::CreateMimeHandlerViewGuestDelegate( MimeHandlerViewGuest* guest) const { return base::MakeUnique<ChromeMimeHandlerViewGuestDelegate>(); } Commit Message: Hide DevTools frontend from webRequest API Prevent extensions from observing requests for remote DevTools frontends and add regression tests. And update ExtensionTestApi to support initializing the embedded test server and port from SetUpCommandLine (before SetUpOnMainThread). BUG=797497,797500 TEST=browser_test --gtest_filter=DevToolsFrontendInWebRequestApiTest.HiddenRequests Cq-Include-Trybots: master.tryserver.chromium.linux:linux_mojo Change-Id: Ic8f44b5771f2d5796f8c3de128f0a7ab88a77735 Reviewed-on: https://chromium-review.googlesource.com/844316 Commit-Queue: Rob Wu <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#528187} 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: circle_box(PG_FUNCTION_ARGS) { CIRCLE *circle = PG_GETARG_CIRCLE_P(0); BOX *box; double delta; box = (BOX *) palloc(sizeof(BOX)); delta = circle->radius / sqrt(2.0); box->high.x = circle->center.x + delta; box->low.x = circle->center.x - delta; box->high.y = circle->center.y + delta; box->low.y = circle->center.y - delta; PG_RETURN_BOX_P(box); } Commit Message: Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064 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 opj_bool pi_next_rpcl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { goto LABEL_SKIP; } else { int compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } Commit Message: [MJ2] To avoid divisions by zero / undefined behaviour on shift Signed-off-by: Young_X <[email protected]> CWE ID: CWE-369 Target: 1 Example 2: Code: static void vhost_net_tx_packet(struct vhost_net *net) { ++net->tx_packets; if (net->tx_packets < 1024) return; net->tx_packets = 0; net->tx_zcopy_err = 0; } Commit Message: vhost-net: fix use-after-free in vhost_net_flush vhost_net_ubuf_put_and_wait has a confusing name: it will actually also free it's argument. Thus since commit 1280c27f8e29acf4af2da914e80ec27c3dbd5c01 "vhost-net: flush outstanding DMAs on memory change" vhost_net_flush tries to use the argument after passing it to vhost_net_ubuf_put_and_wait, this results in use after free. To fix, don't free the argument in vhost_net_ubuf_put_and_wait, add an new API for callers that want to free ubufs. Acked-by: Asias He <[email protected]> Acked-by: Jason Wang <[email protected]> Signed-off-by: Michael S. Tsirkin <[email protected]> Signed-off-by: David S. Miller <[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: int virtio_load(VirtIODevice *vdev, QEMUFile *f) { int i, ret; uint32_t num; uint32_t features; uint32_t supported_features; VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus); if (k->load_config) { ret = k->load_config(qbus->parent, f); if (ret) return ret; } qemu_get_8s(f, &vdev->status); qemu_get_8s(f, &vdev->isr); qemu_get_be16s(f, &vdev->queue_sel); if (vdev->queue_sel >= VIRTIO_PCI_QUEUE_MAX) { return -1; } qemu_get_be32s(f, &features); if (virtio_set_features(vdev, features) < 0) { supported_features = k->get_features(qbus->parent); error_report("Features 0x%x unsupported. Allowed features: 0x%x", features, supported_features); features, supported_features); return -1; } vdev->config_len = qemu_get_be32(f); qemu_get_buffer(f, vdev->config, vdev->config_len); num = qemu_get_be32(f); for (i = 0; i < num; i++) { vdev->vq[i].vring.num = qemu_get_be32(f); if (k->has_variable_vring_alignment) { vdev->vq[i].vring.align = qemu_get_be32(f); } vdev->vq[i].pa = qemu_get_be64(f); qemu_get_be16s(f, &vdev->vq[i].last_avail_idx); vdev->vq[i].signalled_used_valid = false; vdev->vq[i].notification = true; if (vdev->vq[i].pa) { uint16_t nheads; virtqueue_init(&vdev->vq[i]); nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx; /* Check it isn't doing very strange things with descriptor numbers. */ if (nheads > vdev->vq[i].vring.num) { error_report("VQ %d size 0x%x Guest index 0x%x " "inconsistent with Host index 0x%x: delta 0x%x", i, vdev->vq[i].vring.num, vring_avail_idx(&vdev->vq[i]), vdev->vq[i].last_avail_idx, nheads); return -1; } } else if (vdev->vq[i].last_avail_idx) { error_report("VQ %d address 0x0 " "inconsistent with Host index 0x%x", i, vdev->vq[i].last_avail_idx); return -1; } if (k->load_queue) { ret = k->load_queue(qbus->parent, i, f); if (ret) return ret; } } virtio_notify_vector(vdev, VIRTIO_NO_VECTOR); return 0; } 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: void RenderWidgetHostViewAura::SetSurfaceNotInUseByCompositor(ui::Compositor*) { if (current_surface_ || !host_->is_hidden()) return; current_surface_in_use_by_compositor_ = false; AdjustSurfaceProtection(); } 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: Target: 1 Example 2: Code: static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track) { struct sgpd_entry { int count; int16_t roll_distance; int group_description_index; }; struct sgpd_entry *sgpd_entries = NULL; int entries = -1; int group = 0; int i, j; const int OPUS_SEEK_PREROLL_MS = 80; int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS, (AVRational){1, 1000}, (AVRational){1, 48000}); if (!track->entry) return 0; sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries)); if (!sgpd_entries) return AVERROR(ENOMEM); av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC); if (track->par->codec_id == AV_CODEC_ID_OPUS) { for (i = 0; i < track->entry; i++) { int roll_samples_remaining = roll_samples; int distance = 0; for (j = i - 1; j >= 0; j--) { roll_samples_remaining -= get_cluster_duration(track, j); distance++; if (roll_samples_remaining <= 0) break; } /* We don't have enough preceeding samples to compute a valid roll_distance here, so this sample can't be independently decoded. */ if (roll_samples_remaining > 0) distance = 0; /* Verify distance is a minimum of 2 (60ms) packets and a maximum of 32 (2.5ms) packets. */ av_assert0(distance == 0 || (distance >= 2 && distance <= 32)); if (i && distance == sgpd_entries[entries].roll_distance) { sgpd_entries[entries].count++; } else { entries++; sgpd_entries[entries].count = 1; sgpd_entries[entries].roll_distance = distance; sgpd_entries[entries].group_description_index = distance ? ++group : 0; } } } else { entries++; sgpd_entries[entries].count = track->sample_count; sgpd_entries[entries].roll_distance = 1; sgpd_entries[entries].group_description_index = ++group; } entries++; if (!group) { av_free(sgpd_entries); return 0; } /* Write sgpd tag */ avio_wb32(pb, 24 + (group * 2)); /* size */ ffio_wfourcc(pb, "sgpd"); avio_wb32(pb, 1 << 24); /* fullbox */ ffio_wfourcc(pb, "roll"); avio_wb32(pb, 2); /* default_length */ avio_wb32(pb, group); /* entry_count */ for (i = 0; i < entries; i++) { if (sgpd_entries[i].group_description_index) { avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */ } } /* Write sbgp tag */ avio_wb32(pb, 20 + (entries * 8)); /* size */ ffio_wfourcc(pb, "sbgp"); avio_wb32(pb, 0); /* fullbox */ ffio_wfourcc(pb, "roll"); avio_wb32(pb, entries); /* entry_count */ for (i = 0; i < entries; i++) { avio_wb32(pb, sgpd_entries[i].count); /* sample_count */ avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */ } av_free(sgpd_entries); return 0; } Commit Message: avformat/movenc: Write version 2 of audio atom if channels is not known The version 1 needs the channel count and would divide by 0 Fixes: division by 0 Fixes: fpe_movenc.c_1108_1.ogg Fixes: fpe_movenc.c_1108_2.ogg Fixes: fpe_movenc.c_1108_3.wav Found-by: #CHEN HONGXU# <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-369 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 long VideoTrack::GetHeight() const { return m_height; } 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 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 DevToolsAgentHostImpl::ForceAttachClient(DevToolsAgentHostClient* client) { if (SessionByClient(client)) return; scoped_refptr<DevToolsAgentHostImpl> protect(this); if (!sessions_.empty()) ForceDetachAllClients(); DCHECK(sessions_.empty()); InnerAttachClient(client); } 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: 1 Example 2: Code: GF_Err name_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_NameBox *ptr = (GF_NameBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; if (ptr->string) { gf_bs_write_data(bs, ptr->string, (u32) strlen(ptr->string) + 1); } return GF_OK; } 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: NO_INLINE JsVar *jspeFactor() { if (lex->tk==LEX_ID) { JsVar *a = jspGetNamedVariable(jslGetTokenValueAsString(lex)); JSP_ASSERT_MATCH(LEX_ID); #ifndef SAVE_ON_FLASH if (lex->tk==LEX_TEMPLATE_LITERAL) jsExceptionHere(JSET_SYNTAXERROR, "Tagged template literals not supported"); else if (lex->tk==LEX_ARROW_FUNCTION && jsvIsName(a)) { JsVar *funcVar = jspeArrowFunction(0,a); jsvUnLock(a); a=funcVar; } #endif return a; } else if (lex->tk==LEX_INT) { JsVar *v = 0; if (JSP_SHOULD_EXECUTE) { v = jsvNewFromLongInteger(stringToInt(jslGetTokenValueAsString(lex))); } JSP_ASSERT_MATCH(LEX_INT); return v; } else if (lex->tk==LEX_FLOAT) { JsVar *v = 0; if (JSP_SHOULD_EXECUTE) { v = jsvNewFromFloat(stringToFloat(jslGetTokenValueAsString(lex))); } JSP_ASSERT_MATCH(LEX_FLOAT); return v; } else if (lex->tk=='(') { JSP_ASSERT_MATCH('('); if (!jspCheckStackPosition()) return 0; #ifdef SAVE_ON_FLASH JsVar *a = jspeExpression(); if (!JSP_SHOULDNT_PARSE) JSP_MATCH_WITH_RETURN(')',a); return a; #else return jspeExpressionOrArrowFunction(); #endif } else if (lex->tk==LEX_R_TRUE) { JSP_ASSERT_MATCH(LEX_R_TRUE); return JSP_SHOULD_EXECUTE ? jsvNewFromBool(true) : 0; } else if (lex->tk==LEX_R_FALSE) { JSP_ASSERT_MATCH(LEX_R_FALSE); return JSP_SHOULD_EXECUTE ? jsvNewFromBool(false) : 0; } else if (lex->tk==LEX_R_NULL) { JSP_ASSERT_MATCH(LEX_R_NULL); return JSP_SHOULD_EXECUTE ? jsvNewWithFlags(JSV_NULL) : 0; } else if (lex->tk==LEX_R_UNDEFINED) { JSP_ASSERT_MATCH(LEX_R_UNDEFINED); return 0; } else if (lex->tk==LEX_STR) { JsVar *a = 0; if (JSP_SHOULD_EXECUTE) a = jslGetTokenValueAsVar(lex); JSP_ASSERT_MATCH(LEX_STR); return a; #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_TEMPLATE_LITERAL) { return jspeTemplateLiteral(); #endif } else if (lex->tk==LEX_REGEX) { JsVar *a = 0; #ifdef SAVE_ON_FLASH jsExceptionHere(JSET_SYNTAXERROR, "RegEx are not supported in this version of Espruino\n"); #else JsVar *regex = jslGetTokenValueAsVar(lex); size_t regexEnd = 0, regexLen = 0; JsvStringIterator it; jsvStringIteratorNew(&it, regex, 0); while (jsvStringIteratorHasChar(&it)) { regexLen++; if (jsvStringIteratorGetChar(&it)=='/') regexEnd = regexLen; jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); JsVar *flags = 0; if (regexEnd < regexLen) flags = jsvNewFromStringVar(regex, regexEnd, JSVAPPENDSTRINGVAR_MAXLENGTH); JsVar *regexSource = jsvNewFromStringVar(regex, 1, regexEnd-2); a = jswrap_regexp_constructor(regexSource, flags); jsvUnLock3(regex, flags, regexSource); #endif JSP_ASSERT_MATCH(LEX_REGEX); return a; } else if (lex->tk=='{') { if (!jspCheckStackPosition()) return 0; return jspeFactorObject(); } else if (lex->tk=='[') { if (!jspCheckStackPosition()) return 0; return jspeFactorArray(); } else if (lex->tk==LEX_R_FUNCTION) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_FUNCTION); return jspeFunctionDefinition(true); #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_R_CLASS) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_CLASS); return jspeClassDefinition(true); } else if (lex->tk==LEX_R_SUPER) { JSP_ASSERT_MATCH(LEX_R_SUPER); /* This is kind of nasty, since super appears to do three different things. * In the constructor it references the extended class's constructor * in a method it references the constructor's prototype. * in a static method it references the extended class's constructor (but this is different) */ if (jsvIsObject(execInfo.thisVar)) { JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_INHERITS_VAR, 0); // if we're in a method, get __proto__ first JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; // still in method, get __proto__.__proto__ jsvUnLock(proto1); if (!proto2) { jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; } if (lex->tk=='(') return proto2; // eg. used in a constructor JsVar *proto3 = jsvIsFunction(proto2) ? jsvObjectGetChild(proto2, JSPARSE_PROTOTYPE_VAR, 0) : 0; jsvUnLock(proto2); return proto3; } else if (jsvIsFunction(execInfo.thisVar)) { JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_PROTOTYPE_VAR, 0); JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; jsvUnLock(proto1); if (!proto2) { jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; } return proto2; } jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; #endif } else if (lex->tk==LEX_R_THIS) { JSP_ASSERT_MATCH(LEX_R_THIS); return jsvLockAgain( execInfo.thisVar ? execInfo.thisVar : execInfo.root ); } else if (lex->tk==LEX_R_DELETE) { if (!jspCheckStackPosition()) return 0; return jspeFactorDelete(); } else if (lex->tk==LEX_R_TYPEOF) { if (!jspCheckStackPosition()) return 0; return jspeFactorTypeOf(); } else if (lex->tk==LEX_R_VOID) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_VOID); jsvUnLock(jspeUnaryExpression()); return 0; } JSP_MATCH(LEX_EOF); jsExceptionHere(JSET_SYNTAXERROR, "Unexpected end of Input\n"); return 0; } NO_INLINE JsVar *__jspePostfixExpression(JsVar *a) { while (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { int op = lex->tk; JSP_ASSERT_MATCH(op); if (JSP_SHOULD_EXECUTE) { JsVar *one = jsvNewFromInteger(1); JsVar *oldValue = jsvAsNumberAndUnLock(jsvSkipName(a)); // keep the old value (but convert to number) JsVar *res = jsvMathsOpSkipNames(oldValue, one, op==LEX_PLUSPLUS ? '+' : '-'); jsvUnLock(one); jsvReplaceWith(a, res); jsvUnLock(res); jsvUnLock(a); a = oldValue; } } return a; } NO_INLINE JsVar *jspePostfixExpression() { JsVar *a; if (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { int op = lex->tk; JSP_ASSERT_MATCH(op); a = jspePostfixExpression(); if (JSP_SHOULD_EXECUTE) { JsVar *one = jsvNewFromInteger(1); JsVar *res = jsvMathsOpSkipNames(a, one, op==LEX_PLUSPLUS ? '+' : '-'); jsvUnLock(one); jsvReplaceWith(a, res); jsvUnLock(res); } } else a = jspeFactorFunctionCall(); return __jspePostfixExpression(a); } NO_INLINE JsVar *jspeUnaryExpression() { if (lex->tk=='!' || lex->tk=='~' || lex->tk=='-' || lex->tk=='+') { short tk = lex->tk; JSP_ASSERT_MATCH(tk); if (!JSP_SHOULD_EXECUTE) { return jspeUnaryExpression(); } if (tk=='!') { // logical not return jsvNewFromBool(!jsvGetBoolAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); } else if (tk=='~') { // bitwise not return jsvNewFromInteger(~jsvGetIntegerAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); } else if (tk=='-') { // unary minus return jsvNegateAndUnLock(jspeUnaryExpression()); // names already skipped } else if (tk=='+') { // unary plus (convert to number) JsVar *v = jsvSkipNameAndUnLock(jspeUnaryExpression()); JsVar *r = jsvAsNumber(v); // names already skipped jsvUnLock(v); return r; } assert(0); return 0; } else return jspePostfixExpression(); } unsigned int jspeGetBinaryExpressionPrecedence(int op) { switch (op) { case LEX_OROR: return 1; break; case LEX_ANDAND: return 2; break; case '|' : return 3; break; case '^' : return 4; break; case '&' : return 5; break; case LEX_EQUAL: case LEX_NEQUAL: case LEX_TYPEEQUAL: case LEX_NTYPEEQUAL: return 6; case LEX_LEQUAL: case LEX_GEQUAL: case '<': case '>': case LEX_R_INSTANCEOF: return 7; case LEX_R_IN: return (execInfo.execute&EXEC_FOR_INIT)?0:7; case LEX_LSHIFT: case LEX_RSHIFT: case LEX_RSHIFTUNSIGNED: return 8; case '+': case '-': return 9; case '*': case '/': case '%': return 10; default: return 0; } } NO_INLINE JsVar *__jspeBinaryExpression(JsVar *a, unsigned int lastPrecedence) { /* This one's a bit strange. Basically all the ops have their own precedence, it's not * like & and | share the same precedence. We don't want to recurse for each one, * so instead we do this. * * We deal with an expression in recursion ONLY if it's of higher precedence * than the current one, otherwise we stick in the while loop. */ unsigned int precedence = jspeGetBinaryExpressionPrecedence(lex->tk); while (precedence && precedence>lastPrecedence) { int op = lex->tk; JSP_ASSERT_MATCH(op); if (op==LEX_ANDAND || op==LEX_OROR) { bool aValue = jsvGetBoolAndUnLock(jsvSkipName(a)); if ((!aValue && op==LEX_ANDAND) || (aValue && op==LEX_OROR)) { JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(__jspeBinaryExpression(jspeUnaryExpression(),precedence)); JSP_RESTORE_EXECUTE(); } else { jsvUnLock(a); a = __jspeBinaryExpression(jspeUnaryExpression(),precedence); } } else { // else it's a more 'normal' logical expression - just use Maths JsVar *b = __jspeBinaryExpression(jspeUnaryExpression(),precedence); if (JSP_SHOULD_EXECUTE) { if (op==LEX_R_IN) { JsVar *av = jsvSkipName(a); // needle JsVar *bv = jsvSkipName(b); // haystack if (jsvIsArray(bv) || jsvIsObject(bv)) { // search keys, NOT values av = jsvAsArrayIndexAndUnLock(av); JsVar *varFound = jspGetVarNamedField( bv, av, true); jsvUnLock(a); a = jsvNewFromBool(varFound!=0); jsvUnLock(varFound); } else {// else it will be undefined jsExceptionHere(JSET_ERROR, "Cannot use 'in' operator to search a %t", bv); jsvUnLock(a); a = 0; } jsvUnLock2(av, bv); } else if (op==LEX_R_INSTANCEOF) { bool inst = false; JsVar *av = jsvSkipName(a); JsVar *bv = jsvSkipName(b); if (!jsvIsFunction(bv)) { jsExceptionHere(JSET_ERROR, "Expecting a function on RHS in instanceof check, got %t", bv); } else { if (jsvIsObject(av) || jsvIsFunction(av)) { JsVar *bproto = jspGetNamedField(bv, JSPARSE_PROTOTYPE_VAR, false); JsVar *proto = jsvObjectGetChild(av, JSPARSE_INHERITS_VAR, 0); while (proto) { if (proto == bproto) inst=true; JsVar *childProto = jsvObjectGetChild(proto, JSPARSE_INHERITS_VAR, 0); jsvUnLock(proto); proto = childProto; } if (jspIsConstructor(bv, "Object")) inst = true; jsvUnLock(bproto); } if (!inst) { const char *name = jswGetBasicObjectName(av); if (name) { inst = jspIsConstructor(bv, name); } if (!inst && (jsvIsArray(av) || jsvIsArrayBuffer(av)) && jspIsConstructor(bv, "Object")) inst = true; } } jsvUnLock3(av, bv, a); a = jsvNewFromBool(inst); } else { // --------------------------------------------- NORMAL JsVar *res = jsvMathsOpSkipNames(a, b, op); jsvUnLock(a); a = res; } } jsvUnLock(b); } precedence = jspeGetBinaryExpressionPrecedence(lex->tk); } return a; } JsVar *jspeBinaryExpression() { return __jspeBinaryExpression(jspeUnaryExpression(),0); } NO_INLINE JsVar *__jspeConditionalExpression(JsVar *lhs) { if (lex->tk=='?') { JSP_ASSERT_MATCH('?'); if (!JSP_SHOULD_EXECUTE) { jsvUnLock(jspeAssignmentExpression()); JSP_MATCH(':'); jsvUnLock(jspeAssignmentExpression()); } else { bool first = jsvGetBoolAndUnLock(jsvSkipName(lhs)); jsvUnLock(lhs); if (first) { lhs = jspeAssignmentExpression(); JSP_MATCH(':'); JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(jspeAssignmentExpression()); JSP_RESTORE_EXECUTE(); } else { JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(jspeAssignmentExpression()); JSP_RESTORE_EXECUTE(); JSP_MATCH(':'); lhs = jspeAssignmentExpression(); } } } return lhs; } JsVar *jspeConditionalExpression() { return __jspeConditionalExpression(jspeBinaryExpression()); } NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) { if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL || lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL || lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL || lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL || lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) { JsVar *rhs; int op = lex->tk; JSP_ASSERT_MATCH(op); rhs = jspeAssignmentExpression(); rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS if (JSP_SHOULD_EXECUTE && lhs) { if (op=='=') { jsvReplaceWithOrAddToRoot(lhs, rhs); } else { if (op==LEX_PLUSEQUAL) op='+'; else if (op==LEX_MINUSEQUAL) op='-'; else if (op==LEX_MULEQUAL) op='*'; else if (op==LEX_DIVEQUAL) op='/'; else if (op==LEX_MODEQUAL) op='%'; else if (op==LEX_ANDEQUAL) op='&'; else if (op==LEX_OREQUAL) op='|'; else if (op==LEX_XOREQUAL) op='^'; else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT; else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT; else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED; if (op=='+' && jsvIsName(lhs)) { JsVar *currentValue = jsvSkipName(lhs); if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) { /* A special case for string += where this is the only use of the string * and we're not appending to ourselves. In this case we can do a * simple append (rather than clone + append)*/ JsVar *str = jsvAsString(rhs, false); jsvAppendStringVarComplete(currentValue, str); jsvUnLock(str); op = 0; } jsvUnLock(currentValue); } if (op) { /* Fallback which does a proper add */ JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op); jsvReplaceWith(lhs, res); jsvUnLock(res); } } } jsvUnLock(rhs); } return lhs; } JsVar *jspeAssignmentExpression() { return __jspeAssignmentExpression(jspeConditionalExpression()); } NO_INLINE JsVar *jspeExpression() { while (!JSP_SHOULDNT_PARSE) { JsVar *a = jspeAssignmentExpression(); if (lex->tk!=',') return a; jsvCheckReferenceError(a); jsvUnLock(a); JSP_ASSERT_MATCH(','); } return 0; } /** Parse a block `{ ... }` */ NO_INLINE void jspeSkipBlock() { int brackets = 1; while (lex->tk && brackets) { if (lex->tk == '{') brackets++; else if (lex->tk == '}') { brackets--; if (!brackets) return; } JSP_ASSERT_MATCH(lex->tk); } } /** Parse a block `{ ... }` but assume brackets are already parsed */ NO_INLINE void jspeBlockNoBrackets() { if (JSP_SHOULD_EXECUTE) { while (lex->tk && lex->tk!='}') { JsVar *a = jspeStatement(); jsvCheckReferenceError(a); jsvUnLock(a); if (JSP_HAS_ERROR) { if (lex && !(execInfo.execute&EXEC_ERROR_LINE_REPORTED)) { execInfo.execute = (JsExecFlags)(execInfo.execute | EXEC_ERROR_LINE_REPORTED); JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0); if (stackTrace) { jsvAppendPrintf(stackTrace, "at "); jspAppendStackTrace(stackTrace); jsvUnLock(stackTrace); } } } if (JSP_SHOULDNT_PARSE) return; if (!JSP_SHOULD_EXECUTE) { jspeSkipBlock(); return; } } } else { jspeSkipBlock(); } return; } Commit Message: Fix stack overflow if interpreting a file full of '{' (fix #1448) CWE ID: CWE-674 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 recv_files(int f_in, int f_out, char *local_name) { int fd1,fd2; STRUCT_STAT st; int iflags, xlen; char *fname, fbuf[MAXPATHLEN]; char xname[MAXPATHLEN]; char fnametmp[MAXPATHLEN]; char *fnamecmp, *partialptr; char fnamecmpbuf[MAXPATHLEN]; uchar fnamecmp_type; struct file_struct *file; int itemizing = am_server ? logfile_format_has_i : stdout_format_has_i; enum logcode log_code = log_before_transfer ? FLOG : FINFO; int max_phase = protocol_version >= 29 ? 2 : 1; int dflt_perms = (ACCESSPERMS & ~orig_umask); #ifdef SUPPORT_ACLS const char *parent_dirname = ""; #endif int ndx, recv_ok; if (DEBUG_GTE(RECV, 1)) rprintf(FINFO, "recv_files(%d) starting\n", cur_flist->used); if (delay_updates) delayed_bits = bitbag_create(cur_flist->used + 1); while (1) { cleanup_disable(); /* This call also sets cur_flist. */ ndx = read_ndx_and_attrs(f_in, f_out, &iflags, &fnamecmp_type, xname, &xlen); if (ndx == NDX_DONE) { if (!am_server && INFO_GTE(PROGRESS, 2) && cur_flist) { set_current_file_index(NULL, 0); end_progress(0); } if (inc_recurse && first_flist) { if (read_batch) { ndx = first_flist->used + first_flist->ndx_start; gen_wants_ndx(ndx, first_flist->flist_num); } flist_free(first_flist); if (first_flist) continue; } else if (read_batch && first_flist) { ndx = first_flist->used; gen_wants_ndx(ndx, first_flist->flist_num); } if (++phase > max_phase) break; if (DEBUG_GTE(RECV, 1)) rprintf(FINFO, "recv_files phase=%d\n", phase); if (phase == 2 && delay_updates) handle_delayed_updates(local_name); write_int(f_out, NDX_DONE); continue; } if (ndx - cur_flist->ndx_start >= 0) file = cur_flist->files[ndx - cur_flist->ndx_start]; else file = dir_flist->files[cur_flist->parent_ndx]; fname = local_name ? local_name : f_name(file, fbuf); if (daemon_filter_list.head && check_filter(&daemon_filter_list, FLOG, fname, 0) < 0) { rprintf(FERROR, "attempt to hack rsync failed.\n"); exit_cleanup(RERR_PROTOCOL); } if (DEBUG_GTE(RECV, 1)) rprintf(FINFO, "recv_files(%s)\n", fname); #ifdef SUPPORT_XATTRS if (preserve_xattrs && iflags & ITEM_REPORT_XATTR && do_xfers && !(want_xattr_optim && BITS_SET(iflags, ITEM_XNAME_FOLLOWS|ITEM_LOCAL_CHANGE))) recv_xattr_request(file, f_in); #endif if (!(iflags & ITEM_TRANSFER)) { maybe_log_item(file, iflags, itemizing, xname); #ifdef SUPPORT_XATTRS if (preserve_xattrs && iflags & ITEM_REPORT_XATTR && do_xfers && !BITS_SET(iflags, ITEM_XNAME_FOLLOWS|ITEM_LOCAL_CHANGE)) set_file_attrs(fname, file, NULL, fname, 0); #endif if (iflags & ITEM_IS_NEW) { stats.created_files++; if (S_ISREG(file->mode)) { /* Nothing further to count. */ } else if (S_ISDIR(file->mode)) stats.created_dirs++; #ifdef SUPPORT_LINKS else if (S_ISLNK(file->mode)) stats.created_symlinks++; #endif else if (IS_DEVICE(file->mode)) stats.created_devices++; else stats.created_specials++; } continue; } if (phase == 2) { rprintf(FERROR, "got transfer request in phase 2 [%s]\n", who_am_i()); exit_cleanup(RERR_PROTOCOL); } if (file->flags & FLAG_FILE_SENT) { if (csum_length == SHORT_SUM_LENGTH) { if (keep_partial && !partial_dir) make_backups = -make_backups; /* prevents double backup */ if (append_mode) sparse_files = -sparse_files; append_mode = -append_mode; csum_length = SUM_LENGTH; redoing = 1; } } else { if (csum_length != SHORT_SUM_LENGTH) { if (keep_partial && !partial_dir) make_backups = -make_backups; if (append_mode) sparse_files = -sparse_files; append_mode = -append_mode; csum_length = SHORT_SUM_LENGTH; redoing = 0; } if (iflags & ITEM_IS_NEW) stats.created_files++; } if (!am_server && INFO_GTE(PROGRESS, 1)) set_current_file_index(file, ndx); stats.xferred_files++; stats.total_transferred_size += F_LENGTH(file); cleanup_got_literal = 0; if (read_batch) { int wanted = redoing ? we_want_redo(ndx) : gen_wants_ndx(ndx, cur_flist->flist_num); if (!wanted) { rprintf(FINFO, "(Skipping batched update for%s \"%s\")\n", redoing ? " resend of" : "", fname); discard_receive_data(f_in, F_LENGTH(file)); file->flags |= FLAG_FILE_SENT; continue; } } remember_initial_stats(); if (!do_xfers) { /* log the transfer */ log_item(FCLIENT, file, iflags, NULL); if (read_batch) discard_receive_data(f_in, F_LENGTH(file)); continue; } if (write_batch < 0) { log_item(FCLIENT, file, iflags, NULL); if (!am_server) discard_receive_data(f_in, F_LENGTH(file)); if (inc_recurse) send_msg_int(MSG_SUCCESS, ndx); continue; } partialptr = partial_dir ? partial_dir_fname(fname) : fname; if (protocol_version >= 29) { switch (fnamecmp_type) { case FNAMECMP_FNAME: fnamecmp = fname; break; case FNAMECMP_PARTIAL_DIR: fnamecmp = partialptr; break; case FNAMECMP_BACKUP: fnamecmp = get_backup_name(fname); break; case FNAMECMP_FUZZY: if (file->dirname) { pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, file->dirname, xname); fnamecmp = fnamecmpbuf; } else fnamecmp = xname; break; default: if (fnamecmp_type > FNAMECMP_FUZZY && fnamecmp_type-FNAMECMP_FUZZY <= basis_dir_cnt) { fnamecmp_type -= FNAMECMP_FUZZY + 1; if (file->dirname) { stringjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[fnamecmp_type], "/", file->dirname, "/", xname, NULL); } else pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[fnamecmp_type], xname); } else if (fnamecmp_type >= basis_dir_cnt) { rprintf(FERROR, "invalid basis_dir index: %d.\n", fnamecmp_type); exit_cleanup(RERR_PROTOCOL); } else pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[fnamecmp_type], fname); fnamecmp = fnamecmpbuf; break; } if (!fnamecmp || (daemon_filter_list.head && check_filter(&daemon_filter_list, FLOG, fname, 0) < 0)) { fnamecmp = fname; fnamecmp_type = FNAMECMP_FNAME; } } else { /* Reminder: --inplace && --partial-dir are never * enabled at the same time. */ if (inplace && make_backups > 0) { if (!(fnamecmp = get_backup_name(fname))) fnamecmp = fname; else fnamecmp_type = FNAMECMP_BACKUP; } else if (partial_dir && partialptr) fnamecmp = partialptr; else fnamecmp = fname; } /* open the file */ fd1 = do_open(fnamecmp, O_RDONLY, 0); if (fd1 == -1 && protocol_version < 29) { if (fnamecmp != fname) { fnamecmp = fname; fd1 = do_open(fnamecmp, O_RDONLY, 0); } if (fd1 == -1 && basis_dir[0]) { /* pre-29 allowed only one alternate basis */ pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[0], fname); fnamecmp = fnamecmpbuf; fd1 = do_open(fnamecmp, O_RDONLY, 0); } } updating_basis_or_equiv = inplace && (fnamecmp == fname || fnamecmp_type == FNAMECMP_BACKUP); if (fd1 == -1) { st.st_mode = 0; st.st_size = 0; } else if (do_fstat(fd1,&st) != 0) { rsyserr(FERROR_XFER, errno, "fstat %s failed", full_fname(fnamecmp)); discard_receive_data(f_in, F_LENGTH(file)); close(fd1); if (inc_recurse) send_msg_int(MSG_NO_SEND, ndx); continue; } if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) { /* this special handling for directories * wouldn't be necessary if robust_rename() * and the underlying robust_unlink could cope * with directories */ rprintf(FERROR_XFER, "recv_files: %s is a directory\n", full_fname(fnamecmp)); discard_receive_data(f_in, F_LENGTH(file)); close(fd1); if (inc_recurse) send_msg_int(MSG_NO_SEND, ndx); continue; } if (fd1 != -1 && !S_ISREG(st.st_mode)) { close(fd1); fd1 = -1; } /* If we're not preserving permissions, change the file-list's * mode based on the local permissions and some heuristics. */ if (!preserve_perms) { int exists = fd1 != -1; #ifdef SUPPORT_ACLS const char *dn = file->dirname ? file->dirname : "."; if (parent_dirname != dn && strcmp(parent_dirname, dn) != 0) { dflt_perms = default_perms_for_dir(dn); parent_dirname = dn; } #endif file->mode = dest_mode(file->mode, st.st_mode, dflt_perms, exists); } /* We now check to see if we are writing the file "inplace" */ if (inplace) { fd2 = do_open(fname, O_WRONLY|O_CREAT, 0600); if (fd2 == -1) { rsyserr(FERROR_XFER, errno, "open %s failed", full_fname(fname)); } else if (updating_basis_or_equiv) cleanup_set(NULL, NULL, file, fd1, fd2); } else { fd2 = open_tmpfile(fnametmp, fname, file); if (fd2 != -1) cleanup_set(fnametmp, partialptr, file, fd1, fd2); } if (fd2 == -1) { discard_receive_data(f_in, F_LENGTH(file)); if (fd1 != -1) close(fd1); if (inc_recurse) send_msg_int(MSG_NO_SEND, ndx); continue; } /* log the transfer */ if (log_before_transfer) log_item(FCLIENT, file, iflags, NULL); else if (!am_server && INFO_GTE(NAME, 1) && INFO_EQ(PROGRESS, 1)) rprintf(FINFO, "%s\n", fname); /* recv file data */ recv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size, fname, fd2, F_LENGTH(file)); log_item(log_code, file, iflags, NULL); if (fd1 != -1) close(fd1); if (close(fd2) < 0) { rsyserr(FERROR, errno, "close failed on %s", full_fname(fnametmp)); exit_cleanup(RERR_FILEIO); } if ((recv_ok && (!delay_updates || !partialptr)) || inplace) { if (partialptr == fname) partialptr = NULL; if (!finish_transfer(fname, fnametmp, fnamecmp, partialptr, file, recv_ok, 1)) recv_ok = -1; else if (fnamecmp == partialptr) { do_unlink(partialptr); handle_partial_dir(partialptr, PDIR_DELETE); } } else if (keep_partial && partialptr) { if (!handle_partial_dir(partialptr, PDIR_CREATE)) { rprintf(FERROR, "Unable to create partial-dir for %s -- discarding %s.\n", local_name ? local_name : f_name(file, NULL), recv_ok ? "completed file" : "partial file"); do_unlink(fnametmp); recv_ok = -1; } else if (!finish_transfer(partialptr, fnametmp, fnamecmp, NULL, file, recv_ok, !partial_dir)) recv_ok = -1; else if (delay_updates && recv_ok) { bitbag_set_bit(delayed_bits, ndx); recv_ok = 2; } else partialptr = NULL; } else do_unlink(fnametmp); cleanup_disable(); if (read_batch) file->flags |= FLAG_FILE_SENT; switch (recv_ok) { case 2: break; case 1: if (remove_source_files || inc_recurse || (preserve_hard_links && F_IS_HLINKED(file))) send_msg_int(MSG_SUCCESS, ndx); break; case 0: { enum logcode msgtype = redoing ? FERROR_XFER : FWARNING; if (msgtype == FERROR_XFER || INFO_GTE(NAME, 1)) { char *errstr, *redostr, *keptstr; if (!(keep_partial && partialptr) && !inplace) keptstr = "discarded"; else if (partial_dir) keptstr = "put into partial-dir"; else keptstr = "retained"; if (msgtype == FERROR_XFER) { errstr = "ERROR"; redostr = ""; } else { errstr = "WARNING"; redostr = read_batch ? " (may try again)" : " (will try again)"; } rprintf(msgtype, "%s: %s failed verification -- update %s%s.\n", errstr, local_name ? f_name(file, NULL) : fname, keptstr, redostr); } if (!redoing) { if (read_batch) flist_ndx_push(&batch_redo_list, ndx); send_msg_int(MSG_REDO, ndx); file->flags |= FLAG_FILE_SENT; } else if (inc_recurse) send_msg_int(MSG_NO_SEND, ndx); break; } case -1: if (inc_recurse) send_msg_int(MSG_NO_SEND, ndx); break; } } if (make_backups < 0) make_backups = -make_backups; if (phase == 2 && delay_updates) /* for protocol_version < 29 */ handle_delayed_updates(local_name); if (DEBUG_GTE(RECV, 1)) rprintf(FINFO,"recv_files finished\n"); return 0; } Commit Message: CWE ID: Target: 1 Example 2: Code: DispatchResponse NetworkHandler::SetRequestInterception( std::unique_ptr<protocol::Array<protocol::Network::RequestPattern>> patterns) { WebContents* web_contents = WebContents::FromRenderFrameHost(host_); if (!web_contents) return Response::InternalError(); DevToolsInterceptorController* interceptor = DevToolsInterceptorController::FromBrowserContext( web_contents->GetBrowserContext()); if (!interceptor) return Response::Error("Interception not supported"); if (!patterns->length()) { interception_handle_.reset(); return Response::OK(); } std::vector<DevToolsURLRequestInterceptor::Pattern> interceptor_patterns; for (size_t i = 0; i < patterns->length(); ++i) { base::flat_set<ResourceType> resource_types; std::string resource_type = patterns->get(i)->GetResourceType(""); if (!resource_type.empty()) { if (!AddInterceptedResourceType(resource_type, &resource_types)) { return Response::InvalidParams(base::StringPrintf( "Cannot intercept resources of type '%s'", resource_type.c_str())); } } interceptor_patterns.push_back(DevToolsURLRequestInterceptor::Pattern( patterns->get(i)->GetUrlPattern("*"), std::move(resource_types), ToInterceptorStage(patterns->get(i)->GetInterceptionStage( protocol::Network::InterceptionStageEnum::Request)))); } if (interception_handle_) { interception_handle_->UpdatePatterns(std::move(interceptor_patterns)); } else { interception_handle_ = interceptor->StartInterceptingRequests( host_->frame_tree_node(), std::move(interceptor_patterns), base::Bind(&NetworkHandler::RequestIntercepted, weak_factory_.GetWeakPtr())); } return Response::OK(); } 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: insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params) { int i; png_uint_16 freq[256]; /* libpng takes the count from the PLTE count; we don't check it here but we * do set the array to 0 for unspecified entries. */ memset(freq, 0, sizeof freq); for (i=0; i<nparams; ++i) { char *endptr = NULL; unsigned long int l = strtoul(params[i], &endptr, 0/*base*/); if (params[i][0] && *endptr == 0 && l <= 65535) freq[i] = (png_uint_16)l; else { fprintf(stderr, "hIST[%d]: %s: invalid frequency\n", i, params[i]); exit(1); } } png_set_hIST(png_ptr, info_ptr, freq); } 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 NavigationObserver::PromptToEnableExtensionIfNecessary( NavigationController* nav_controller) { if (!in_progress_prompt_extension_id_.empty()) return; NavigationEntry* nav_entry = nav_controller->GetVisibleEntry(); if (!nav_entry) return; const GURL& url = (nav_entry->GetPageType() == content::PAGE_TYPE_ERROR && nav_entry->GetURL() == url::kAboutBlankURL && nav_entry->GetVirtualURL().SchemeIs(kExtensionScheme)) ? nav_entry->GetVirtualURL() : nav_entry->GetURL(); if (!url.SchemeIs(kExtensionScheme)) return; const Extension* extension = ExtensionRegistry::Get(profile_) ->disabled_extensions() .GetExtensionOrAppByURL(url); if (!extension) return; if (!prompted_extensions_.insert(extension->id()).second && !g_repeat_prompting) { return; } ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(profile_); if (extension_prefs->DidExtensionEscalatePermissions(extension->id())) { in_progress_prompt_extension_id_ = extension->id(); in_progress_prompt_navigation_controller_ = nav_controller; extension_install_prompt_.reset( new ExtensionInstallPrompt(nav_controller->GetWebContents())); ExtensionInstallPrompt::PromptType type = ExtensionInstallPrompt::GetReEnablePromptTypeForExtension(profile_, extension); extension_install_prompt_->ShowDialog( base::Bind(&NavigationObserver::OnInstallPromptDone, weak_factory_.GetWeakPtr()), extension, nullptr, base::MakeUnique<ExtensionInstallPrompt::Prompt>(type), ExtensionInstallPrompt::GetDefaultShowDialogCallback()); } } Commit Message: Do not use NavigationEntry to block history navigations. This is no longer necessary after r477371. BUG=777419 TEST=See bug for repro steps. Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation Change-Id: I701e4d4853858281b43e3743b12274dbeadfbf18 Reviewed-on: https://chromium-review.googlesource.com/733959 Reviewed-by: Devlin <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#511942} CWE ID: CWE-20 Target: 1 Example 2: Code: static void xmlGROW (xmlParserCtxtPtr ctxt) { unsigned long curEnd = ctxt->input->end - ctxt->input->cur; unsigned long curBase = ctxt->input->cur - ctxt->input->base; if (((curEnd > (unsigned long) XML_MAX_LOOKUP_LIMIT) || (curBase > (unsigned long) XML_MAX_LOOKUP_LIMIT)) && ((ctxt->input->buf) && (ctxt->input->buf->readcallback != (xmlInputReadCallback) xmlNop)) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "Huge input lookup"); xmlHaltParser(ctxt); return; } xmlParserInputGrow(ctxt->input, INPUT_CHUNK); if ((ctxt->input->cur > ctxt->input->end) || (ctxt->input->cur < ctxt->input->base)) { xmlHaltParser(ctxt); xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "cur index out of bound"); return; } if ((ctxt->input->cur != NULL) && (*ctxt->input->cur == 0) && (xmlParserInputGrow(ctxt->input, INPUT_CHUNK) <= 0)) xmlPopInput(ctxt); } Commit Message: DO NOT MERGE: Add validation for eternal enities https://bugzilla.gnome.org/show_bug.cgi?id=780691 Bug: 36556310 Change-Id: I9450743e167c3c73af5e4071f3fc85e81d061648 (cherry picked from commit bef9af3d89d241bcb518c20cba6da2a2fd9ba049) CWE ID: CWE-611 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 key *key_get_instantiation_authkey(key_serial_t target_id) { char description[16]; struct keyring_search_context ctx = { .index_key.type = &key_type_request_key_auth, .index_key.description = description, .cred = current_cred(), .match_data.cmp = user_match, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, }; struct key *authkey; key_ref_t authkey_ref; sprintf(description, "%x", target_id); authkey_ref = search_process_keyrings(&ctx); if (IS_ERR(authkey_ref)) { authkey = ERR_CAST(authkey_ref); if (authkey == ERR_PTR(-EAGAIN)) authkey = ERR_PTR(-ENOKEY); goto error; } authkey = key_ref_to_ptr(authkey_ref); if (test_bit(KEY_FLAG_REVOKED, &authkey->flags)) { key_put(authkey); authkey = ERR_PTR(-EKEYREVOKED); } error: return authkey; } Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <[email protected]> Acked-by: Vivek Goyal <[email protected]> CWE ID: CWE-476 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 ReportRequestHeaders(std::map<std::string, std::string>* request_headers, const std::string& url, const std::string& headers) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); EXPECT_FALSE(base::ContainsKey(*request_headers, url)); (*request_headers)[url] = headers; } Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service. The functionality worked, as part of converting DICE, however the test code didn't work since it depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to better match production, which removes the dependency on net/. Also: -make GetFilePathWithReplacements replace strings in the mock headers if they're present -add a global to google_util to ignore ports; that way other tests can be converted without having to modify each callsite to google_util Bug: 881976 Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058 Reviewed-on: https://chromium-review.googlesource.com/c/1328142 Commit-Queue: John Abd-El-Malek <[email protected]> Reviewed-by: Ramin Halavati <[email protected]> Reviewed-by: Maks Orlovich <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#607652} CWE ID: Target: 1 Example 2: Code: Browser::~Browser() { if (profile_->GetProfileSyncService()) profile_->GetProfileSyncService()->RemoveObserver(this); BrowserList::RemoveBrowser(this); #if !defined(OS_MACOSX) if (!BrowserList::HasBrowserWithProfile(profile_)) { TabRestoreServiceFactory::ResetForProfile(profile_); } #endif SessionService* session_service = SessionServiceFactory::GetForProfile(profile_); if (session_service) session_service->WindowClosed(session_id_); TabRestoreService* tab_restore_service = TabRestoreServiceFactory::GetForProfile(profile()); if (tab_restore_service) tab_restore_service->BrowserClosed(tab_restore_service_delegate()); profile_pref_registrar_.RemoveAll(); local_pref_registrar_.RemoveAll(); encoding_auto_detect_.Destroy(); use_vertical_tabs_.Destroy(); use_compact_navigation_bar_.Destroy(); if (profile_->IsOffTheRecord() && !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_)) { profile_->GetOriginalProfile()->DestroyOffTheRecordProfile(); } if (select_file_dialog_.get()) select_file_dialog_->ListenerDestroyed(); TabRestoreServiceDestroyed(tab_restore_service_); } Commit Message: Implement a bubble that appears at the top of the screen when a tab enters fullscreen mode via webkitRequestFullScreen(), telling the user how to exit fullscreen. This is implemented as an NSView rather than an NSWindow because the floating chrome that appears in presentation mode should overlap the bubble. Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac: the mode in which the UI is hidden, accessible by moving the cursor to the top of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode. On Lion, however, fullscreen mode does not imply presentation mode: in non-presentation fullscreen mode, the chrome is permanently shown. It is possible to switch between presentation mode and fullscreen mode using the presentation mode UI control. When a tab initiates fullscreen mode on Lion, we enter presentation mode if not in presentation mode already. When the user exits fullscreen mode using Chrome UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we return the user to the mode they were in before the tab entered fullscreen. BUG=14471 TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen. Need to test the Lion logic somehow, with no Lion trybots. BUG=96883 Original review http://codereview.chromium.org/7890056/ TBR=thakis Review URL: http://codereview.chromium.org/7920024 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98 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 void DeprecateAsOverloadedMethod2Method(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "DeprecateAsOverloadedMethod"); TestObject* impl = V8TestObject::ToImpl(info.Holder()); int32_t arg; arg = NativeValueTraits<IDLLong>::NativeValue(info.GetIsolate(), info[0], exception_state); if (exception_state.HadException()) return; impl->DeprecateAsOverloadedMethod(arg); } Commit Message: bindings: Support "attribute FrozenArray<T>?" Adds a quick hack to support a case of "attribute FrozenArray<T>?". Bug: 1028047 Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866 Reviewed-by: Hitoshi Yoshida <[email protected]> Commit-Queue: Yuki Shiino <[email protected]> Cr-Commit-Position: refs/heads/master@{#718676} 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 cJSON_AddItemReferenceToArray( cJSON *array, cJSON *item ) { cJSON_AddItemToArray( array, create_reference( item ) ); } 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: void tls1_free(SSL *s) { #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_session_ticket) { OPENSSL_free(s->tlsext_session_ticket); } #endif /* OPENSSL_NO_TLSEXT */ ssl3_free(s); } Commit Message: 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: DefragIPv4NoDataTest(void) { DefragContext *dc = NULL; Packet *p = NULL; int id = 12; int ret = 0; DefragInit(); dc = DefragContextNew(); if (dc == NULL) goto end; /* This packet has an offset > 0, more frags set to 0 and no data. */ p = BuildTestPacket(id, 1, 0, 'A', 0); if (p == NULL) goto end; /* We do not expect a packet returned. */ if (Defrag(NULL, NULL, p, NULL) != NULL) goto end; /* The fragment should have been ignored so no fragments should * have been allocated from the pool. */ if (dc->frag_pool->outstanding != 0) return 0; ret = 1; end: if (dc != NULL) DefragContextDestroy(dc); if (p != NULL) SCFree(p); DefragDestroy(); return ret; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358 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 mif_validate(jas_stream_t *in) { uchar buf[MIF_MAGICLEN]; uint_fast32_t magic; int i; int n; assert(JAS_STREAM_MAXPUTBACK >= MIF_MAGICLEN); /* Read the validation data (i.e., the data used for detecting the format). */ if ((n = jas_stream_read(in, buf, MIF_MAGICLEN)) < 0) { return -1; } /* Put the validation data back onto the stream, so that the stream position will not be changed. */ for (i = n - 1; i >= 0; --i) { if (jas_stream_ungetc(in, buf[i]) == EOF) { return -1; } } /* Was enough data read? */ if (n < MIF_MAGICLEN) { return -1; } /* Compute the signature value. */ magic = (JAS_CAST(uint_fast32_t, buf[0]) << 24) | (JAS_CAST(uint_fast32_t, buf[1]) << 16) | (JAS_CAST(uint_fast32_t, buf[2]) << 8) | buf[3]; /* Ensure that the signature is correct for this format. */ if (magic != MIF_MAGIC) { return -1; } 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 Target: 1 Example 2: Code: const Extension* ExtensionService::GetInstalledExtension( const std::string& id) const { return GetExtensionByIdInternal(id, true, true, true); } Commit Message: Limit extent of webstore app to just chrome.google.com/webstore. BUG=93497 TEST=Try installing extensions and apps from the webstore, starting both being initially logged in, and not. Review URL: http://codereview.chromium.org/7719003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97986 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: void LayoutNonRecursiveForTestingViewportIntersection( WebContents* web_contents) { static const char* script = "function relayoutNonRecursiveForTestingViewportIntersection() {\ var width = window.innerWidth;\ var height = window.innerHeight * 0.75;\ for (var i = 0; i < window.frames.length; i++) {\ child = document.getElementById(\"child-\" + i);\ child.width = width;\ child.height = height;\ }\ }\ relayoutNonRecursiveForTestingViewportIntersection();"; EXPECT_TRUE(ExecuteScript(web_contents, script)); } Commit Message: Add a check for disallowing remote frame navigations to local resources. Previously, RemoteFrame navigations did not perform any renderer-side checks and relied solely on the browser-side logic to block disallowed navigations via mechanisms like FilterURL. This means that blocked remote frame navigations were silently navigated to about:blank without any console error message. This CL adds a CanDisplay check to the remote navigation path to match an equivalent check done for local frame navigations. This way, the renderer can consistently block disallowed navigations in both cases and output an error message. Bug: 894399 Change-Id: I172f68f77c1676f6ca0172d2a6c78f7edc0e3b7a Reviewed-on: https://chromium-review.googlesource.com/c/1282390 Reviewed-by: Charlie Reis <[email protected]> Reviewed-by: Nate Chapin <[email protected]> Commit-Queue: Alex Moshchuk <[email protected]> Cr-Commit-Position: refs/heads/master@{#601022} CWE ID: CWE-732 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 do_remount(struct path *path, int flags, int mnt_flags, void *data) { int err; struct super_block *sb = path->mnt->mnt_sb; struct mount *mnt = real_mount(path->mnt); if (!check_mnt(mnt)) return -EINVAL; if (path->dentry != path->mnt->mnt_root) return -EINVAL; /* Don't allow changing of locked mnt flags. * * No locks need to be held here while testing the various * MNT_LOCK flags because those flags can never be cleared * once they are set. */ if ((mnt->mnt.mnt_flags & MNT_LOCK_READONLY) && !(mnt_flags & MNT_READONLY)) { return -EPERM; } err = security_sb_remount(sb, data); if (err) return err; down_write(&sb->s_umount); if (flags & MS_BIND) err = change_mount_flags(path->mnt, flags); else if (!capable(CAP_SYS_ADMIN)) err = -EPERM; else err = do_remount_sb(sb, flags, data, 0); if (!err) { lock_mount_hash(); mnt_flags |= mnt->mnt.mnt_flags & ~MNT_USER_SETTABLE_MASK; mnt->mnt.mnt_flags = mnt_flags; touch_mnt_namespace(mnt->mnt_ns); unlock_mount_hash(); } up_write(&sb->s_umount); return err; } Commit Message: mnt: Correct permission checks in do_remount While invesgiating the issue where in "mount --bind -oremount,ro ..." would result in later "mount --bind -oremount,rw" succeeding even if the mount started off locked I realized that there are several additional mount flags that should be locked and are not. In particular MNT_NOSUID, MNT_NODEV, MNT_NOEXEC, and the atime flags in addition to MNT_READONLY should all be locked. These flags are all per superblock, can all be changed with MS_BIND, and should not be changable if set by a more privileged user. The following additions to the current logic are added in this patch. - nosuid may not be clearable by a less privileged user. - nodev may not be clearable by a less privielged user. - noexec may not be clearable by a less privileged user. - atime flags may not be changeable by a less privileged user. The logic with atime is that always setting atime on access is a global policy and backup software and auditing software could break if atime bits are not updated (when they are configured to be updated), and serious performance degradation could result (DOS attack) if atime updates happen when they have been explicitly disabled. Therefore an unprivileged user should not be able to mess with the atime bits set by a more privileged user. The additional restrictions are implemented with the addition of MNT_LOCK_NOSUID, MNT_LOCK_NODEV, MNT_LOCK_NOEXEC, and MNT_LOCK_ATIME mnt flags. Taken together these changes and the fixes for MNT_LOCK_READONLY should make it safe for an unprivileged user to create a user namespace and to call "mount --bind -o remount,... ..." without the danger of mount flags being changed maliciously. Cc: [email protected] Acked-by: Serge E. Hallyn <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: static int snd_seq_ioctl_get_client_pool(struct snd_seq_client *client, void *arg) { struct snd_seq_client_pool *info = arg; struct snd_seq_client *cptr; cptr = snd_seq_client_use_ptr(info->client); if (cptr == NULL) return -ENOENT; memset(info, 0, sizeof(*info)); info->client = cptr->number; info->output_pool = cptr->pool->size; info->output_room = cptr->pool->room; info->output_free = info->output_pool; info->output_free = snd_seq_unused_cells(cptr->pool); if (cptr->type == USER_CLIENT) { info->input_pool = cptr->data.user.fifo_pool_size; info->input_free = info->input_pool; if (cptr->data.user.fifo) info->input_free = snd_seq_unused_cells(cptr->data.user.fifo->pool); } else { info->input_pool = 0; info->input_free = 0; } snd_seq_client_unlock(cptr); 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: void GetSuggestions(const autofill::PasswordFormFillData& fill_data, const base::string16& current_username, std::vector<autofill::Suggestion>* suggestions, bool show_all, bool is_password_field) { AppendSuggestionIfMatching(fill_data.username_field.value, current_username, fill_data.preferred_realm, show_all, is_password_field, suggestions); for (const auto& login : fill_data.additional_logins) { AppendSuggestionIfMatching(login.first, current_username, login.second.realm, show_all, is_password_field, suggestions); } for (const auto& usernames : fill_data.other_possible_usernames) { for (size_t i = 0; i < usernames.second.size(); ++i) { AppendSuggestionIfMatching(usernames.second[i], current_username, usernames.first.realm, show_all, is_password_field, suggestions); } } if (autofill::IsFeatureSubstringMatchEnabled()) { std::sort(suggestions->begin(), suggestions->end(), [](const autofill::Suggestion& a, const autofill::Suggestion& b) { return a.match < b.match; }); } } Commit Message: Fixing names of password_manager kEnableManualFallbacksFilling feature. Fixing names of password_manager kEnableManualFallbacksFilling feature as per the naming convention. Bug: 785953 Change-Id: I4a4baa1649fe9f02c3783a5e4c40bc75e717cc03 Reviewed-on: https://chromium-review.googlesource.com/900566 Reviewed-by: Vaclav Brozek <[email protected]> Commit-Queue: NIKHIL SAHNI <[email protected]> Cr-Commit-Position: refs/heads/master@{#534923} 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: void dtls1_free(SSL *s) { DTLS_RECORD_LAYER_free(&s->rlayer); { pqueue *buffered_messages; pqueue *sent_messages; unsigned int mtu; unsigned int link_mtu; DTLS_RECORD_LAYER_clear(&s->rlayer); if (s->d1) { buffered_messages = s->d1->buffered_messages; sent_messages = s->d1->sent_messages; mtu = s->d1->mtu; link_mtu = s->d1->link_mtu; dtls1_clear_queues(s); memset(s->d1, 0, sizeof(*s->d1)); if (s->server) { s->d1->cookie_len = sizeof(s->d1->cookie); } if (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU) { s->d1->mtu = mtu; s->d1->link_mtu = link_mtu; } s->d1->buffered_messages = buffered_messages; s->d1->sent_messages = sent_messages; } ssl3_clear(s); if (s->method->version == DTLS_ANY_VERSION) s->version = DTLS_MAX_VERSION; #ifndef OPENSSL_NO_DTLS1_METHOD else if (s->options & SSL_OP_CISCO_ANYCONNECT) s->client_version = s->version = DTLS1_BAD_VER; #endif else s->version = s->method->version; } long dtls1_ctrl(SSL *s, int cmd, long larg, void *parg) { int ret = 0; switch (cmd) { case DTLS_CTRL_GET_TIMEOUT: if (dtls1_get_timeout(s, (struct timeval *)parg) != NULL) { ret = 1; } break; case DTLS_CTRL_HANDLE_TIMEOUT: ret = dtls1_handle_timeout(s); break; case DTLS_CTRL_SET_LINK_MTU: if (larg < (long)dtls1_link_min_mtu()) return 0; s->d1->link_mtu = larg; return 1; case DTLS_CTRL_GET_LINK_MIN_MTU: return (long)dtls1_link_min_mtu(); case SSL_CTRL_SET_MTU: /* * We may not have a BIO set yet so can't call dtls1_min_mtu() * We'll have to make do with dtls1_link_min_mtu() and max overhead */ if (larg < (long)dtls1_link_min_mtu() - DTLS1_MAX_MTU_OVERHEAD) return 0; s->d1->mtu = larg; return larg; default: ret = ssl3_ctrl(s, cmd, larg, parg); break; } return (ret); } void dtls1_start_timer(SSL *s) { #ifndef OPENSSL_NO_SCTP /* Disable timer for SCTP */ if (BIO_dgram_is_sctp(SSL_get_wbio(s))) { memset(&s->d1->next_timeout, 0, sizeof(s->d1->next_timeout)); return; } #endif /* If timer is not set, initialize duration with 1 second */ if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) { s->d1->timeout_duration = 1; } /* Set timeout to current time */ get_current_time(&(s->d1->next_timeout)); /* Add duration to current time */ s->d1->next_timeout.tv_sec += s->d1->timeout_duration; BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &(s->d1->next_timeout)); } struct timeval *dtls1_get_timeout(SSL *s, struct timeval *timeleft) { struct timeval timenow; /* If no timeout is set, just return NULL */ if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) { return NULL; } /* Get current time */ get_current_time(&timenow); /* If timer already expired, set remaining time to 0 */ if (s->d1->next_timeout.tv_sec < timenow.tv_sec || (s->d1->next_timeout.tv_sec == timenow.tv_sec && s->d1->next_timeout.tv_usec <= timenow.tv_usec)) { memset(timeleft, 0, sizeof(*timeleft)); return timeleft; } /* Calculate time left until timer expires */ memcpy(timeleft, &(s->d1->next_timeout), sizeof(struct timeval)); timeleft->tv_sec -= timenow.tv_sec; timeleft->tv_usec -= timenow.tv_usec; if (timeleft->tv_usec < 0) { timeleft->tv_sec--; timeleft->tv_usec += 1000000; } /* * If remaining time is less than 15 ms, set it to 0 to prevent issues * because of small divergences with socket timeouts. */ if (timeleft->tv_sec == 0 && timeleft->tv_usec < 15000) { memset(timeleft, 0, sizeof(*timeleft)); } return timeleft; } int dtls1_is_timer_expired(SSL *s) { struct timeval timeleft; /* Get time left until timeout, return false if no timer running */ if (dtls1_get_timeout(s, &timeleft) == NULL) { return 0; } /* Return false if timer is not expired yet */ if (timeleft.tv_sec > 0 || timeleft.tv_usec > 0) { return 0; } /* Timer expired, so return true */ return 1; } void dtls1_double_timeout(SSL *s) { s->d1->timeout_duration *= 2; if (s->d1->timeout_duration > 60) s->d1->timeout_duration = 60; dtls1_start_timer(s); } void dtls1_stop_timer(SSL *s) { /* Reset everything */ memset(&s->d1->timeout, 0, sizeof(s->d1->timeout)); memset(&s->d1->next_timeout, 0, sizeof(s->d1->next_timeout)); s->d1->timeout_duration = 1; BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &(s->d1->next_timeout)); /* Clear retransmission buffer */ dtls1_clear_record_buffer(s); } int dtls1_check_timeout_num(SSL *s) { unsigned int mtu; s->d1->timeout.num_alerts++; /* Reduce MTU after 2 unsuccessful retransmissions */ BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &(s->d1->next_timeout)); /* Clear retransmission buffer */ dtls1_clear_record_buffer(s); } int dtls1_check_timeout_num(SSL *s) if (s->d1->timeout.num_alerts > DTLS1_TMO_ALERT_COUNT) { /* fail the connection, enough alerts have been sent */ SSLerr(SSL_F_DTLS1_CHECK_TIMEOUT_NUM, SSL_R_READ_TIMEOUT_EXPIRED); return -1; } return 0; } Commit Message: CWE ID: CWE-399 Target: 1 Example 2: Code: int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) { perf_guest_cbs = cbs; return 0; } 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: KioskNextHomeInterfaceBrokerImpl::KioskNextHomeInterfaceBrokerImpl( content::BrowserContext* context) : connector_(content::BrowserContext::GetConnectorFor(context)->Clone()), app_controller_(std::make_unique<AppControllerImpl>( Profile::FromBrowserContext(context))) {} 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 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: check_acl(pam_handle_t *pamh, const char *sense, const char *this_user, const char *other_user, int noent_code, int debug) { struct passwd *pwd; FILE *fp = NULL; int i, fd = -1, save_errno; uid_t fsuid; struct stat st; /* Check this user's <sense> file. */ pwd = pam_modutil_getpwnam(pamh, this_user); if (pwd == NULL) { pam_syslog(pamh, LOG_ERR, "error determining home directory for '%s'", this_user); return PAM_SESSION_ERR; } /* Figure out what that file is really named. */ i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense); if ((i >= (int)sizeof(path)) || (i < 0)) { pam_syslog(pamh, LOG_ERR, "name of user's home directory is too long"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); if (!stat(path, &st)) { if (!S_ISREG(st.st_mode)) errno = EINVAL; fd = open(path, O_RDONLY | O_NOCTTY); fd = open(path, O_RDONLY | O_NOCTTY); } save_errno = errno; setfsuid(fsuid); if (fd >= 0) { if (!fstat(fd, &st)) { if (!S_ISREG(st.st_mode)) save_errno = errno; close(fd); } } if (fp) { char buf[LINE_MAX], *tmp; /* Scan the file for a list of specs of users to "trust". */ while (fgets(buf, sizeof(buf), fp) != NULL) { tmp = memchr(buf, '\r', sizeof(buf)); if (tmp != NULL) { *tmp = '\0'; } tmp = memchr(buf, '\n', sizeof(buf)); if (tmp != NULL) { *tmp = '\0'; } if (fnmatch(buf, other_user, 0) == 0) { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s %s allowed by %s", other_user, sense, path); } fclose(fp); return PAM_SUCCESS; } } /* If there's no match in the file, we fail. */ if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s not listed in %s", other_user, path); } fclose(fp); return PAM_PERM_DENIED; } else { /* Default to okay if the file doesn't exist. */ errno = save_errno; switch (errno) { case ENOENT: if (noent_code == PAM_SUCCESS) { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, ignoring", path); } } else { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, failing", path); } } return noent_code; default: if (debug) { pam_syslog(pamh, LOG_DEBUG, "error opening %s: %m", path); } return PAM_PERM_DENIED; } } } Commit Message: CWE ID: Target: 1 Example 2: Code: static void send_packet_to_relay(struct dhcp_packet *dhcp_pkt) { log1("forwarding packet to relay"); udhcp_send_kernel_packet(dhcp_pkt, server_config.server_nip, SERVER_PORT, dhcp_pkt->gateway_nip, SERVER_PORT); } Commit Message: 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: PageGroupLoadDeferrer::PageGroupLoadDeferrer(Page* page, bool deferSelf) { const HashSet<Page*>& pages = page->group().pages(); HashSet<Page*>::const_iterator end = pages.end(); for (HashSet<Page*>::const_iterator it = pages.begin(); it != end; ++it) { Page* otherPage = *it; if ((deferSelf || otherPage != page)) { if (!otherPage->defersLoading()) { m_deferredFrames.append(otherPage->mainFrame()); for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree()->traverseNext()) frame->document()->suspendScheduledTasks(ActiveDOMObject::WillDeferLoading); } } } size_t count = m_deferredFrames.size(); for (size_t i = 0; i < count; ++i) if (Page* page = m_deferredFrames[i]->page()) page->setDefersLoading(true); } Commit Message: Don't wait to notify client of spoof attempt if a modal dialog is created. BUG=281256 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/23620020 git-svn-id: svn://svn.chromium.org/blink/trunk@157196 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: void PageHandler::PrintToPDF(Maybe<bool> landscape, Maybe<bool> display_header_footer, Maybe<bool> print_background, Maybe<double> scale, Maybe<double> paper_width, Maybe<double> paper_height, Maybe<double> margin_top, Maybe<double> margin_bottom, Maybe<double> margin_left, Maybe<double> margin_right, Maybe<String> page_ranges, Maybe<bool> ignore_invalid_page_ranges, std::unique_ptr<PrintToPDFCallback> callback) { callback->sendFailure(Response::Error("PrintToPDF is not implemented")); return; } Commit Message: DevTools: allow styling the page number element when printing over the protocol. Bug: none Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4 Reviewed-on: https://chromium-review.googlesource.com/809759 Commit-Queue: Pavel Feldman <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: Tom Sepez <[email protected]> Reviewed-by: Jianzhou Feng <[email protected]> Cr-Commit-Position: refs/heads/master@{#523966} CWE ID: CWE-20 Target: 1 Example 2: Code: EdgeStateSignatureType Signature(GestureState gesture_state, unsigned int touch_id, ui::EventType type, bool touch_handled) { CHECK((touch_id & 0xfff) == touch_id); TouchState touch_state = TouchEventTypeToTouchState(type); return static_cast<EdgeStateSignatureType> (G(gesture_state, touch_id, touch_state, touch_handled)); } Commit Message: Add setters for the aura gesture recognizer constants. BUG=113227 TEST=none Review URL: http://codereview.chromium.org/9372040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@122586 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: HeapObjectHeader* NormalPage::findHeaderFromAddress(Address address) { if (address < payload()) return nullptr; if (!m_objectStartBitMapComputed) populateObjectStartBitMap(); size_t objectOffset = address - payload(); size_t objectStartNumber = objectOffset / allocationGranularity; size_t mapIndex = objectStartNumber / 8; ASSERT(mapIndex < objectStartBitMapSize); size_t bit = objectStartNumber & 7; uint8_t byte = m_objectStartBitMap[mapIndex] & ((1 << (bit + 1)) - 1); while (!byte) { ASSERT(mapIndex > 0); byte = m_objectStartBitMap[--mapIndex]; } int leadingZeroes = numberOfLeadingZeroes(byte); objectStartNumber = (mapIndex * 8) + 7 - leadingZeroes; objectOffset = objectStartNumber * allocationGranularity; Address objectAddress = objectOffset + payload(); HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(objectAddress); if (header->isFree()) return nullptr; ASSERT(header->checkHeader()); return header; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119 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 l2cap_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags) { struct sock *sk = sock->sk; struct sockaddr_l2 la; int len, err = 0; BT_DBG("sk %p", sk); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; memset(&la, 0, sizeof(la)); len = min_t(unsigned int, sizeof(la), alen); memcpy(&la, addr, len); if (la.l2_cid) return -EINVAL; lock_sock(sk); if (sk->sk_type == SOCK_SEQPACKET && !la.l2_psm) { err = -EINVAL; goto done; } switch (l2cap_pi(sk)->mode) { case L2CAP_MODE_BASIC: break; case L2CAP_MODE_ERTM: if (enable_ertm) break; /* fall through */ default: err = -ENOTSUPP; goto done; } switch (sk->sk_state) { case BT_CONNECT: case BT_CONNECT2: case BT_CONFIG: /* Already connecting */ goto wait; case BT_CONNECTED: /* Already connected */ goto done; case BT_OPEN: case BT_BOUND: /* Can connect */ break; default: err = -EBADFD; goto done; } /* Set destination address and psm */ bacpy(&bt_sk(sk)->dst, &la.l2_bdaddr); l2cap_pi(sk)->psm = la.l2_psm; err = l2cap_do_connect(sk); if (err) goto done; wait: err = bt_sock_wait_state(sk, BT_CONNECTED, sock_sndtimeo(sk, flags & O_NONBLOCK)); done: release_sock(sk); return err; } Commit Message: Bluetooth: Add configuration support for ERTM and Streaming mode Add support to config_req and config_rsp to configure ERTM and Streaming mode. If the remote device specifies ERTM or Streaming mode, then the same mode is proposed. Otherwise ERTM or Basic mode is used. And in case of a state 2 device, the remote device should propose the same mode. If not, then the channel gets disconnected. Signed-off-by: Gustavo F. Padovan <[email protected]> Signed-off-by: Marcel Holtmann <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static void overloadedPerWorldBindingsMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); TestObjectPythonV8Internal::overloadedPerWorldBindingsMethodMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } 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: EncodedJSValue JSC_HOST_CALL jsTestEventTargetPrototypeFunctionItem(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestEventTarget::s_info)) return throwVMTypeError(exec); JSTestEventTarget* castedThis = jsCast<JSTestEventTarget*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestEventTarget::s_info); TestEventTarget* impl = static_cast<TestEventTarget*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); int index(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toUInt32(exec)); if (index < 0) { setDOMException(exec, INDEX_SIZE_ERR); return JSValue::encode(jsUndefined()); } if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(impl->item(index))); return JSValue::encode(result); } 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 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 __ip_select_ident(struct net *net, struct iphdr *iph, int segs) { static u32 ip_idents_hashrnd __read_mostly; u32 hash, id; net_get_random_once(&ip_idents_hashrnd, sizeof(ip_idents_hashrnd)); hash = jhash_3words((__force u32)iph->daddr, (__force u32)iph->saddr, iph->protocol ^ net_hash_mix(net), ip_idents_hashrnd); id = ip_idents_reserve(hash, segs); iph->id = htons(id); } Commit Message: inet: switch IP ID generator to siphash According to Amit Klein and Benny Pinkas, IP ID generation is too weak and might be used by attackers. Even with recent net_hash_mix() fix (netns: provide pure entropy for net_hash_mix()) having 64bit key and Jenkins hash is risky. It is time to switch to siphash and its 128bit keys. Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Amit Klein <[email protected]> Reported-by: Benny Pinkas <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp) { BDRVQcowState *s = bs->opaque; int flags = s->flags; AES_KEY aes_encrypt_key; AES_KEY aes_decrypt_key; uint32_t crypt_method = 0; QDict *options; Error *local_err = NULL; int ret; /* * Backing files are read-only which makes all of their metadata immutable, * that means we don't have to worry about reopening them here. */ if (s->crypt_method) { crypt_method = s->crypt_method; memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key)); memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key)); } qcow2_close(bs); bdrv_invalidate_cache(bs->file, &local_err); if (local_err) { error_propagate(errp, local_err); return; } memset(s, 0, sizeof(BDRVQcowState)); options = qdict_clone_shallow(bs->options); ret = qcow2_open(bs, options, flags, &local_err); if (local_err) { error_setg(errp, "Could not reopen qcow2 layer: %s", error_get_pretty(local_err)); error_free(local_err); return; } else if (ret < 0) { error_setg_errno(errp, -ret, "Could not reopen qcow2 layer"); return; } QDECREF(options); if (crypt_method) { s->crypt_method = crypt_method; memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key)); memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key)); } } Commit Message: 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: GC_API void GC_CALL GC_incr_bytes_allocd(size_t n) { GC_bytes_allocd += n; } Commit Message: Fix allocation size overflows due to rounding. * malloc.c (GC_generic_malloc): Check if the allocation size is rounded to a smaller value. * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. CWE ID: CWE-189 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: GDataFile::GDataFile(GDataDirectory* parent, GDataDirectoryService* directory_service) : GDataEntry(parent, directory_service), kind_(DocumentEntry::UNKNOWN), is_hosted_document_(false) { file_info_.is_directory = false; } 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: static bool seq_nr_after(u16 a, u16 b) { /* Remove inconsistency where * seq_nr_after(a, b) == seq_nr_before(a, b) */ if ((int) b - a == 32768) return false; return (((s16) (b - a)) < 0); } Commit Message: net: hsr: fix memory leak in hsr_dev_finalize() If hsr_add_port(hsr, hsr_dev, HSR_PT_MASTER) failed to add port, it directly returns res and forgets to free the node that allocated in hsr_create_self_node(), and forgets to delete the node->mac_list linked in hsr->self_node_db. BUG: memory leak unreferenced object 0xffff8881cfa0c780 (size 64): comm "syz-executor.0", pid 2077, jiffies 4294717969 (age 2415.377s) hex dump (first 32 bytes): e0 c7 a0 cf 81 88 ff ff 00 02 00 00 00 00 ad de ................ 00 e6 49 cd 81 88 ff ff c0 9b 87 d0 81 88 ff ff ..I............. backtrace: [<00000000e2ff5070>] hsr_dev_finalize+0x736/0x960 [hsr] [<000000003ed2e597>] hsr_newlink+0x2b2/0x3e0 [hsr] [<000000003fa8c6b6>] __rtnl_newlink+0xf1f/0x1600 net/core/rtnetlink.c:3182 [<000000001247a7ad>] rtnl_newlink+0x66/0x90 net/core/rtnetlink.c:3240 [<00000000e7d1b61d>] rtnetlink_rcv_msg+0x54e/0xb90 net/core/rtnetlink.c:5130 [<000000005556bd3a>] netlink_rcv_skb+0x129/0x340 net/netlink/af_netlink.c:2477 [<00000000741d5ee6>] netlink_unicast_kernel net/netlink/af_netlink.c:1310 [inline] [<00000000741d5ee6>] netlink_unicast+0x49a/0x650 net/netlink/af_netlink.c:1336 [<000000009d56f9b7>] netlink_sendmsg+0x88b/0xdf0 net/netlink/af_netlink.c:1917 [<0000000046b35c59>] sock_sendmsg_nosec net/socket.c:621 [inline] [<0000000046b35c59>] sock_sendmsg+0xc3/0x100 net/socket.c:631 [<00000000d208adc9>] __sys_sendto+0x33e/0x560 net/socket.c:1786 [<00000000b582837a>] __do_sys_sendto net/socket.c:1798 [inline] [<00000000b582837a>] __se_sys_sendto net/socket.c:1794 [inline] [<00000000b582837a>] __x64_sys_sendto+0xdd/0x1b0 net/socket.c:1794 [<00000000c866801d>] do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 [<00000000fea382d9>] entry_SYSCALL_64_after_hwframe+0x49/0xbe [<00000000e01dacb3>] 0xffffffffffffffff Fixes: c5a759117210 ("net/hsr: Use list_head (and rcu) instead of array for slave devices.") Reported-by: Hulk Robot <[email protected]> Signed-off-by: Mao Wenan <[email protected]> Signed-off-by: David S. Miller <[email protected]> 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: static int peer_has_ufo(VirtIONet *n) { if (!peer_has_vnet_hdr(n)) return 0; n->has_ufo = qemu_has_ufo(qemu_get_queue(n->nic)->peer); return n->has_ufo; } 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: char *strstr(char *s1, char *s2) { /* from libiberty */ char *p; int len = strlen(s2); if (*s2 == '\0') /* everything matches empty string */ return s1; for (p = s1; (p = strchr(p, *s2)) != NULL; p = strchr(p + 1, *s2)) { if (strncmp(p, s2, len) == 0) return (p); } return NULL; } Commit Message: misc oom and possible memory leak fix CWE ID: Target: 1 Example 2: Code: static int ftrace_function_set_regexp(struct ftrace_ops *ops, int filter, int reset, char *re, int len) { int ret; if (filter) ret = ftrace_set_filter(ops, re, len, reset); else ret = ftrace_set_notrace(ops, re, len, reset); return ret; } Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace Pull tracing fixes from Steven Rostedt: "This contains a few fixes and a clean up. - a bad merge caused an "endif" to go in the wrong place in scripts/Makefile.build - softirq tracing fix for tracing that corrupts lockdep and causes a false splat - histogram documentation typo fixes - fix a bad memory reference when passing in no filter to the filter code - simplify code by using the swap macro instead of open coding the swap" * tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace: tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount tracing: Fix some errors in histogram documentation tracing: Use swap macro in update_max_tr softirq: Reorder trace_softirqs_on to prevent lockdep splat tracing: Check for no filter when processing event filters 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: ModuleExport size_t RegisterPCXImage(void) { MagickInfo *entry; entry=SetMagickInfo("DCX"); entry->decoder=(DecodeImageHandler *) ReadPCXImage; entry->encoder=(EncodeImageHandler *) WritePCXImage; entry->seekable_stream=MagickTrue; entry->magick=(IsImageFormatHandler *) IsDCX; entry->description=ConstantString("ZSoft IBM PC multi-page Paintbrush"); entry->module=ConstantString("PCX"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PCX"); entry->decoder=(DecodeImageHandler *) ReadPCXImage; entry->encoder=(EncodeImageHandler *) WritePCXImage; entry->magick=(IsImageFormatHandler *) IsPCX; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("ZSoft IBM PC Paintbrush"); entry->module=ConstantString("PCX"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/575 CWE ID: CWE-772 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: SYSCALL_DEFINE4(osf_wait4, pid_t, pid, int __user *, ustatus, int, options, struct rusage32 __user *, ur) { struct rusage r; long ret, err; mm_segment_t old_fs; if (!ur) return sys_wait4(pid, ustatus, options, NULL); old_fs = get_fs(); set_fs (KERNEL_DS); ret = sys_wait4(pid, ustatus, options, (struct rusage __user *) &r); set_fs (old_fs); if (!access_ok(VERIFY_WRITE, ur, sizeof(*ur))) return -EFAULT; err = 0; err |= __put_user(r.ru_utime.tv_sec, &ur->ru_utime.tv_sec); err |= __put_user(r.ru_utime.tv_usec, &ur->ru_utime.tv_usec); err |= __put_user(r.ru_stime.tv_sec, &ur->ru_stime.tv_sec); err |= __put_user(r.ru_stime.tv_usec, &ur->ru_stime.tv_usec); err |= __put_user(r.ru_maxrss, &ur->ru_maxrss); err |= __put_user(r.ru_ixrss, &ur->ru_ixrss); err |= __put_user(r.ru_idrss, &ur->ru_idrss); err |= __put_user(r.ru_isrss, &ur->ru_isrss); err |= __put_user(r.ru_minflt, &ur->ru_minflt); err |= __put_user(r.ru_majflt, &ur->ru_majflt); err |= __put_user(r.ru_nswap, &ur->ru_nswap); err |= __put_user(r.ru_inblock, &ur->ru_inblock); err |= __put_user(r.ru_oublock, &ur->ru_oublock); err |= __put_user(r.ru_msgsnd, &ur->ru_msgsnd); err |= __put_user(r.ru_msgrcv, &ur->ru_msgrcv); err |= __put_user(r.ru_nsignals, &ur->ru_nsignals); err |= __put_user(r.ru_nvcsw, &ur->ru_nvcsw); err |= __put_user(r.ru_nivcsw, &ur->ru_nivcsw); return err ? err : ret; } Commit Message: alpha: fix several security issues Fix several security issues in Alpha-specific syscalls. Untested, but mostly trivial. 1. Signedness issue in osf_getdomainname allows copying out-of-bounds kernel memory to userland. 2. Signedness issue in osf_sysinfo allows copying large amounts of kernel memory to userland. 3. Typo (?) in osf_getsysinfo bounds minimum instead of maximum copy size, allowing copying large amounts of kernel memory to userland. 4. Usage of user pointer in osf_wait4 while under KERNEL_DS allows privilege escalation via writing return value of sys_wait4 to kernel memory. Signed-off-by: Dan Rosenberg <[email protected]> Cc: Richard Henderson <[email protected]> Cc: Ivan Kokshaysky <[email protected]> Cc: Matt Turner <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: bool HTMLMediaElement::isGestureNeededForPlaybackIfPendingUserGestureIsLocked() const { if (loadType() == WebMediaPlayer::LoadTypeMediaStream) return false; if (isHTMLVideoElement() && muted() && RuntimeEnabledFeatures::autoplayMutedVideosEnabled() && !(document().settings() && document().settings()->getDataSaverEnabled()) && !(document().settings() && document().settings()->getForcePreloadNoneForMediaElements()) && isAutoplayAllowedPerSettings()) { return false; } return true; } Commit Message: [Blink>Media] Allow autoplay muted on Android by default There was a mistake causing autoplay muted is shipped on Android but it will be disabled if the chromium embedder doesn't specify content setting for "AllowAutoplay" preference. This CL makes the AllowAutoplay preference true by default so that it is allowed by embedders (including AndroidWebView) unless they explicitly disable it. Intent to ship: https://groups.google.com/a/chromium.org/d/msg/blink-dev/Q1cnzNI2GpI/AL_eyUNABgAJ BUG=689018 Review-Url: https://codereview.chromium.org/2677173002 Cr-Commit-Position: refs/heads/master@{#448423} 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: status_t OMXNodeInstance::storeMetaDataInBuffers_l( OMX_U32 portIndex, OMX_BOOL enable, MetadataBufferType *type) { if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) { android_errorWriteLog(0x534e4554, "26324358"); if (type != NULL) { *type = kMetadataBufferTypeInvalid; } return BAD_VALUE; } OMX_INDEXTYPE index; OMX_STRING name = const_cast<OMX_STRING>( "OMX.google.android.index.storeMetaDataInBuffers"); OMX_STRING nativeBufferName = const_cast<OMX_STRING>( "OMX.google.android.index.storeANWBufferInMetadata"); MetadataBufferType negotiatedType; MetadataBufferType requestedType = type != NULL ? *type : kMetadataBufferTypeANWBuffer; StoreMetaDataInBuffersParams params; InitOMXParams(&params); params.nPortIndex = portIndex; params.bStoreMetaData = enable; OMX_ERRORTYPE err = requestedType == kMetadataBufferTypeANWBuffer ? OMX_GetExtensionIndex(mHandle, nativeBufferName, &index) : OMX_ErrorUnsupportedIndex; OMX_ERRORTYPE xerr = err; if (err == OMX_ErrorNone) { err = OMX_SetParameter(mHandle, index, &params); if (err == OMX_ErrorNone) { name = nativeBufferName; // set name for debugging negotiatedType = requestedType; } } if (err != OMX_ErrorNone) { err = OMX_GetExtensionIndex(mHandle, name, &index); xerr = err; if (err == OMX_ErrorNone) { negotiatedType = requestedType == kMetadataBufferTypeANWBuffer ? kMetadataBufferTypeGrallocSource : requestedType; err = OMX_SetParameter(mHandle, index, &params); } } if (err != OMX_ErrorNone) { if (err == OMX_ErrorUnsupportedIndex && portIndex == kPortIndexOutput) { CLOGW("component does not support metadata mode; using fallback"); } else if (xerr != OMX_ErrorNone) { CLOG_ERROR(getExtensionIndex, xerr, "%s", name); } else { CLOG_ERROR(setParameter, err, "%s(%#x): %s:%u en=%d type=%d", name, index, portString(portIndex), portIndex, enable, negotiatedType); } negotiatedType = mMetadataType[portIndex]; } else { if (!enable) { negotiatedType = kMetadataBufferTypeInvalid; } mMetadataType[portIndex] = negotiatedType; } CLOG_CONFIG(storeMetaDataInBuffers, "%s:%u %srequested %s:%d negotiated %s:%d", portString(portIndex), portIndex, enable ? "" : "UN", asString(requestedType), requestedType, asString(negotiatedType), negotiatedType); if (type != NULL) { *type = negotiatedType; } return StatusFromOMXError(err); } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) 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: ext2_xattr_delete_inode(struct inode *inode) { struct buffer_head *bh = NULL; struct mb_cache_entry *ce; down_write(&EXT2_I(inode)->xattr_sem); if (!EXT2_I(inode)->i_file_acl) goto cleanup; bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl); if (!bh) { ext2_error(inode->i_sb, "ext2_xattr_delete_inode", "inode %ld: block %d read error", inode->i_ino, EXT2_I(inode)->i_file_acl); goto cleanup; } ea_bdebug(bh, "b_count=%d", atomic_read(&(bh->b_count))); if (HDR(bh)->h_magic != cpu_to_le32(EXT2_XATTR_MAGIC) || HDR(bh)->h_blocks != cpu_to_le32(1)) { ext2_error(inode->i_sb, "ext2_xattr_delete_inode", "inode %ld: bad block %d", inode->i_ino, EXT2_I(inode)->i_file_acl); goto cleanup; } ce = mb_cache_entry_get(ext2_xattr_cache, bh->b_bdev, bh->b_blocknr); lock_buffer(bh); if (HDR(bh)->h_refcount == cpu_to_le32(1)) { if (ce) mb_cache_entry_free(ce); ext2_free_blocks(inode, EXT2_I(inode)->i_file_acl, 1); get_bh(bh); bforget(bh); unlock_buffer(bh); } else { le32_add_cpu(&HDR(bh)->h_refcount, -1); if (ce) mb_cache_entry_release(ce); ea_bdebug(bh, "refcount now=%d", le32_to_cpu(HDR(bh)->h_refcount)); unlock_buffer(bh); mark_buffer_dirty(bh); if (IS_SYNC(inode)) sync_dirty_buffer(bh); dquot_free_block_nodirty(inode, 1); } EXT2_I(inode)->i_file_acl = 0; cleanup: brelse(bh); up_write(&EXT2_I(inode)->xattr_sem); } Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-19 Target: 1 Example 2: Code: sort_dir_list(struct fixup_entry *p) { struct fixup_entry *a, *b, *t; if (p == NULL) return (NULL); /* A one-item list is already sorted. */ if (p->next == NULL) return (p); /* Step 1: split the list. */ t = p; a = p->next->next; while (a != NULL) { /* Step a twice, t once. */ a = a->next; if (a != NULL) a = a->next; t = t->next; } /* Now, t is at the mid-point, so break the list here. */ b = t->next; t->next = NULL; a = p; /* Step 2: Recursively sort the two sub-lists. */ a = sort_dir_list(a); b = sort_dir_list(b); /* Step 3: Merge the returned lists. */ /* Pick the first element for the merged list. */ if (strcmp(a->name, b->name) > 0) { t = p = a; a = a->next; } else { t = p = b; b = b->next; } /* Always put the later element on the list first. */ while (a != NULL && b != NULL) { if (strcmp(a->name, b->name) > 0) { t->next = a; a = a->next; } else { t->next = b; b = b->next; } t = t->next; } /* Only one list is non-empty, so just splice it on. */ if (a != NULL) t->next = a; if (b != NULL) t->next = b; return (p); } Commit Message: Add ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS option This fixes a directory traversal in the cpio tool. CWE ID: CWE-22 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_enc_delegreturn(struct rpc_rqst *req, __be32 *p, const struct nfs4_delegreturnargs *args) { struct xdr_stream xdr; struct compound_hdr hdr = { .nops = 3, }; int status; xdr_init_encode(&xdr, &req->rq_snd_buf, p); encode_compound_hdr(&xdr, &hdr); status = encode_putfh(&xdr, args->fhandle); if (status != 0) goto out; status = encode_delegreturn(&xdr, args->stateid); if (status != 0) goto out; status = encode_getfattr(&xdr, args->bitmask); 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: ieee802_11_print(netdissect_options *ndo, const u_char *p, u_int length, u_int orig_caplen, int pad, u_int fcslen) { uint16_t fc; u_int caplen, hdrlen, meshdrlen; struct lladdr_info src, dst; int llc_hdrlen; caplen = orig_caplen; /* Remove FCS, if present */ if (length < fcslen) { ND_PRINT((ndo, "%s", tstr)); return caplen; } length -= fcslen; if (caplen > length) { /* Amount of FCS in actual packet data, if any */ fcslen = caplen - length; caplen -= fcslen; ndo->ndo_snapend -= fcslen; } if (caplen < IEEE802_11_FC_LEN) { ND_PRINT((ndo, "%s", tstr)); return orig_caplen; } fc = EXTRACT_LE_16BITS(p); hdrlen = extract_header_length(ndo, fc); if (hdrlen == 0) { /* Unknown frame type or control frame subtype; quit. */ return (0); } if (pad) hdrlen = roundup2(hdrlen, 4); if (ndo->ndo_Hflag && FC_TYPE(fc) == T_DATA && DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) { meshdrlen = extract_mesh_header_length(p+hdrlen); hdrlen += meshdrlen; } else meshdrlen = 0; if (caplen < hdrlen) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } if (ndo->ndo_eflag) ieee_802_11_hdr_print(ndo, fc, p, hdrlen, meshdrlen); /* * Go past the 802.11 header. */ length -= hdrlen; caplen -= hdrlen; p += hdrlen; src.addr_string = etheraddr_string; dst.addr_string = etheraddr_string; switch (FC_TYPE(fc)) { case T_MGMT: get_mgmt_src_dst_mac(p - hdrlen, &src.addr, &dst.addr); if (!mgmt_body_print(ndo, fc, src.addr, p, length)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } break; case T_CTRL: if (!ctrl_body_print(ndo, fc, p - hdrlen)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } break; case T_DATA: if (DATA_FRAME_IS_NULL(FC_SUBTYPE(fc))) return hdrlen; /* no-data frame */ /* There may be a problem w/ AP not having this bit set */ if (FC_PROTECTED(fc)) { ND_PRINT((ndo, "Data")); if (!wep_print(ndo, p)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } } else { get_data_src_dst_mac(fc, p - hdrlen, &src.addr, &dst.addr); llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst); if (llc_hdrlen < 0) { /* * Some kinds of LLC packet we cannot * handle intelligently */ if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); llc_hdrlen = -llc_hdrlen; } hdrlen += llc_hdrlen; } break; default: /* We shouldn't get here - we should already have quit */ break; } return hdrlen; } Commit Message: (for 4.9.3) CVE-2018-16227/IEEE 802.11: add a missing bounds check ieee802_11_print() tried to access the Mesh Flags subfield of the Mesh Control field to find the size of the latter and increment the expected 802.11 header length before checking it is fully present in the input buffer. Add an intermediate bounds check to make it safe. This fixes a buffer over-read discovered by Ryan Ackroyd. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: void RenderFrameDevToolsAgentHost::OnSignedExchangeCertificateResponseReceived( FrameTreeNode* frame_tree_node, const base::UnguessableToken& request_id, const base::UnguessableToken& loader_id, const GURL& url, const network::ResourceResponseHead& head) { DispatchToAgents(frame_tree_node, &protocol::NetworkHandler::ResponseReceived, request_id.ToString(), loader_id.ToString(), url, protocol::Network::ResourceTypeEnum::Other, head, protocol::Maybe<std::string>()); } Commit Message: [DevTools] Do not allow Page.setDownloadBehavior for extensions Bug: 866426 Change-Id: I71b672978e1a8ec779ede49da16b21198567d3a4 Reviewed-on: https://chromium-review.googlesource.com/c/1270007 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Cr-Commit-Position: refs/heads/master@{#598004} 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: long Chapters::Edition::Parse( IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x36) // Atom ID { status = ParseAtom(pReader, pos, size); if (status < 0) // error return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 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 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: ScriptPromise BluetoothRemoteGATTService::getCharacteristicsImpl( ScriptState* scriptState, mojom::blink::WebBluetoothGATTQueryQuantity quantity, const String& characteristicsUUID) { if (!device()->gatt()->connected()) { return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(NetworkError, kGATTServerNotConnected)); } if (!device()->isValidService(m_service->instance_id)) { return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(InvalidStateError, kInvalidService)); } ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); device()->gatt()->AddToActiveAlgorithms(resolver); mojom::blink::WebBluetoothService* service = m_device->bluetooth()->service(); WTF::Optional<String> uuid = WTF::nullopt; if (!characteristicsUUID.isEmpty()) uuid = characteristicsUUID; service->RemoteServiceGetCharacteristics( m_service->instance_id, quantity, uuid, convertToBaseCallback( WTF::bind(&BluetoothRemoteGATTService::GetCharacteristicsCallback, wrapPersistent(this), m_service->instance_id, quantity, wrapPersistent(resolver)))); return promise; } Commit Message: Allow serialization of empty bluetooth uuids. This change allows the passing WTF::Optional<String> types as bluetooth.mojom.UUID optional parameter without needing to ensure the passed object isn't empty. BUG=None R=juncai, dcheng Review-Url: https://codereview.chromium.org/2646613003 Cr-Commit-Position: refs/heads/master@{#445809} CWE ID: CWE-119 Target: 1 Example 2: Code: linux_md_create_data_new (DBusGMethodInvocation *context, Daemon *daemon, const char *first_component_objpath) { LinuxMdCreateData *data; data = g_new0 (LinuxMdCreateData, 1); data->refcount = 1; data->context = context; data->daemon = g_object_ref (daemon); data->first_component_objpath = g_strdup (first_component_objpath); return data; } Commit Message: 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 ssize_t lbs_rdmac_read(struct file *file, char __user *userbuf, size_t count, loff_t *ppos) { struct lbs_private *priv = file->private_data; ssize_t pos = 0; int ret; unsigned long addr = get_zeroed_page(GFP_KERNEL); char *buf = (char *)addr; u32 val = 0; if (!buf) return -ENOMEM; ret = lbs_get_reg(priv, CMD_MAC_REG_ACCESS, priv->mac_offset, &val); mdelay(10); if (!ret) { pos = snprintf(buf, len, "MAC[0x%x] = 0x%08x\n", priv->mac_offset, val); ret = simple_read_from_buffer(userbuf, count, ppos, buf, pos); } free_page(addr); return ret; } 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 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: l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2) { if (tl1 > l2) return 0; return (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0); } Commit Message: CVE-2017-13010/BEEP: Do bounds checking when comparing strings. This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: ofputil_uninit_group_desc(struct ofputil_group_desc *gd) { ofputil_bucket_list_destroy(&gd->buckets); ofputil_group_properties_destroy(&gd->props); } Commit Message: ofp-group: Don't assert-fail decoding bad OF1.5 group mod type or command. When decoding a group mod, the current code validates the group type and command after the whole group mod has been decoded. The OF1.5 decoder, however, tries to use the type and command earlier, when it might still be invalid. This caused an assertion failure (via OVS_NOT_REACHED). This commit fixes the problem. ovs-vswitchd does not enable support for OpenFlow 1.5 by default. Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9249 Signed-off-by: Ben Pfaff <[email protected]> Reviewed-by: Yifeng Sun <[email protected]> CWE ID: CWE-617 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 AudioInputRendererHost::OnCreateStream( int stream_id, const media::AudioParameters& params, const std::string& device_id, bool automatic_gain_control) { VLOG(1) << "AudioInputRendererHost::OnCreateStream(stream_id=" << stream_id << ")"; DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(LookupById(stream_id) == NULL); media::AudioParameters audio_params(params); if (media_stream_manager_->audio_input_device_manager()-> ShouldUseFakeDevice()) { audio_params.Reset(media::AudioParameters::AUDIO_FAKE, params.channel_layout(), params.sample_rate(), params.bits_per_sample(), params.frames_per_buffer()); } else if (WebContentsCaptureUtil::IsWebContentsDeviceId(device_id)) { audio_params.Reset(media::AudioParameters::AUDIO_VIRTUAL, params.channel_layout(), params.sample_rate(), params.bits_per_sample(), params.frames_per_buffer()); } DCHECK_GT(audio_params.frames_per_buffer(), 0); uint32 buffer_size = audio_params.GetBytesPerBuffer(); scoped_ptr<AudioEntry> entry(new AudioEntry()); uint32 mem_size = sizeof(media::AudioInputBufferParameters) + buffer_size; if (!entry->shared_memory.CreateAndMapAnonymous(mem_size)) { SendErrorMessage(stream_id); return; } scoped_ptr<AudioInputSyncWriter> writer( new AudioInputSyncWriter(&entry->shared_memory)); if (!writer->Init()) { SendErrorMessage(stream_id); return; } entry->writer.reset(writer.release()); entry->controller = media::AudioInputController::CreateLowLatency( audio_manager_, this, audio_params, device_id, entry->writer.get()); if (!entry->controller) { SendErrorMessage(stream_id); return; } if (params.format() == media::AudioParameters::AUDIO_PCM_LOW_LATENCY) entry->controller->SetAutomaticGainControl(automatic_gain_control); entry->stream_id = stream_id; audio_entries_.insert(std::make_pair(stream_id, entry.release())); } Commit Message: Improve validation when creating audio streams. BUG=166795 Review URL: https://codereview.chromium.org/11647012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173981 0039d316-1c4b-4281-b951-d872f2087c98 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 Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image, *next_image, *pwp_image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; register Image *p; register ssize_t i; size_t filesize, length; ssize_t count; unsigned char magick[MagickPathExtent]; /* 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=DestroyImage(image); return((Image *) NULL); } pwp_image=image; memset(magick,0,sizeof(magick)); count=ReadBlob(pwp_image,5,magick); if ((count != 5) || (LocaleNCompare((char *) magick,"SFW95",5) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); read_info=CloneImageInfo(image_info); (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL, (void *) NULL); SetImageInfoBlob(read_info,(void *) NULL,0); unique_file=AcquireUniqueFileResource(filename); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"sfw:%s", filename); for ( ; ; ) { (void) memset(magick,0,sizeof(magick)); for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image)) { for (i=0; i < 17; i++) magick[i]=magick[i+1]; magick[17]=(unsigned char) c; if (LocaleNCompare((char *) (magick+12),"SFW94A",6) == 0) break; } if (c == EOF) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } if (LocaleNCompare((char *) (magick+12),"SFW94A",6) != 0) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } /* Dump SFW image to a temporary file. */ file=(FILE *) NULL; if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowFileException(exception,FileOpenError,"UnableToWriteFile", image->filename); image=DestroyImageList(image); return((Image *) NULL); } length=fwrite("SFW94A",1,6,file); (void) length; filesize=65535UL*magick[2]+256L*magick[1]+magick[0]; for (i=0; i < (ssize_t) filesize; i++) { c=ReadBlobByte(pwp_image); if (c == EOF) break; (void) fputc(c,file); } (void) fclose(file); if (c == EOF) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } next_image=ReadImage(read_info,exception); if (next_image == (Image *) NULL) break; (void) FormatLocaleString(next_image->filename,MagickPathExtent, "slide_%02ld.sfw",(long) next_image->scene); if (image == (Image *) NULL) image=next_image; else { /* Link image into image list. */ for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ; next_image->previous=p; next_image->scene=p->scene+1; p->next=next_image; } if (image_info->number_scenes != 0) if (next_image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image), GetBlobSize(pwp_image)); if (status == MagickFalse) break; } if (unique_file != -1) (void) close(unique_file); (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { if (EOFBlob(image) != MagickFalse) { char *message; message=GetExceptionMessage(errno); (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s': %s",image->filename, message); message=DestroyString(message); } (void) CloseBlob(image); } return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1199 CWE ID: CWE-20 Target: 1 Example 2: Code: static int setciedefgspace(i_ctx_t * i_ctx_p, ref *r, int *stage, int *cont, int CIESubst) { int code = 0; ref CIEDict, *nocie; ulong dictkey; gs_md5_state_t md5; byte key[16]; if (i_ctx_p->language_level < 3) return_error(gs_error_undefined); code = dict_find_string(systemdict, "NOCIE", &nocie); if (code > 0) { if (!r_has_type(nocie, t_boolean)) return_error(gs_error_typecheck); if (nocie->value.boolval) return setcmykspace(i_ctx_p, r, stage, cont, 1); } *cont = 0; code = array_get(imemory, r, 1, &CIEDict); if (code < 0) return code; if ((*stage) > 0) { gs_client_color cc; int i; cc.pattern = 0x00; for (i=0;i<4;i++) cc.paint.values[i] = 0; code = gs_setcolor(igs, &cc); *stage = 0; return code; } gs_md5_init(&md5); /* If the hash (dictkey) is 0, we don't check for an existing * ICC profile dor this space. So if we get an error hashing * the space, we construct a new profile. */ dictkey = 0; if (hashciedefgspace(i_ctx_p, r, &md5)) { /* Ideally we would use the whole md5 hash, but the ICC code only * expects a long. I'm 'slightly' concerned about collisions here * but I think its unlikely really. If it ever becomes a problem * we could add the hash bytes up, or modify the ICC cache to store * the full 16 byte hashs. */ gs_md5_finish(&md5, key); dictkey = *(ulong *)&key[sizeof(key) - sizeof(ulong)]; } else { gs_md5_finish(&md5, key); } code = ciedefgspace(i_ctx_p, &CIEDict,dictkey); *cont = 1; (*stage)++; return code; } Commit Message: CWE ID: CWE-704 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 svc_rdma_handle_bc_reply(struct rpc_xprt *xprt, struct rpcrdma_msg *rmsgp, struct xdr_buf *rcvbuf) { struct rpcrdma_xprt *r_xprt = rpcx_to_rdmax(xprt); struct kvec *dst, *src = &rcvbuf->head[0]; struct rpc_rqst *req; unsigned long cwnd; u32 credits; size_t len; __be32 xid; __be32 *p; int ret; p = (__be32 *)src->iov_base; len = src->iov_len; xid = rmsgp->rm_xid; #ifdef SVCRDMA_BACKCHANNEL_DEBUG pr_info("%s: xid=%08x, length=%zu\n", __func__, be32_to_cpu(xid), len); pr_info("%s: RPC/RDMA: %*ph\n", __func__, (int)RPCRDMA_HDRLEN_MIN, rmsgp); pr_info("%s: RPC: %*ph\n", __func__, (int)len, p); #endif ret = -EAGAIN; if (src->iov_len < 24) goto out_shortreply; spin_lock_bh(&xprt->transport_lock); req = xprt_lookup_rqst(xprt, xid); if (!req) goto out_notfound; dst = &req->rq_private_buf.head[0]; memcpy(&req->rq_private_buf, &req->rq_rcv_buf, sizeof(struct xdr_buf)); if (dst->iov_len < len) goto out_unlock; memcpy(dst->iov_base, p, len); credits = be32_to_cpu(rmsgp->rm_credit); if (credits == 0) credits = 1; /* don't deadlock */ else if (credits > r_xprt->rx_buf.rb_bc_max_requests) credits = r_xprt->rx_buf.rb_bc_max_requests; cwnd = xprt->cwnd; xprt->cwnd = credits << RPC_CWNDSHIFT; if (xprt->cwnd > cwnd) xprt_release_rqst_cong(req->rq_task); ret = 0; xprt_complete_rqst(req->rq_task, rcvbuf->len); rcvbuf->len = 0; out_unlock: spin_unlock_bh(&xprt->transport_lock); out: return ret; out_shortreply: dprintk("svcrdma: short bc reply: xprt=%p, len=%zu\n", xprt, src->iov_len); goto out; out_notfound: dprintk("svcrdma: unrecognized bc reply: xprt=%p, xid=%08x\n", xprt, be32_to_cpu(xid)); goto out_unlock; } 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 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 add_ballooned_pages(int nr_pages) { enum bp_state st; if (xen_hotplug_unpopulated) { st = reserve_additional_memory(); if (st != BP_ECANCELED) { mutex_unlock(&balloon_mutex); wait_event(balloon_wq, !list_empty(&ballooned_pages)); mutex_lock(&balloon_mutex); return 0; } } st = decrease_reservation(nr_pages, GFP_USER); if (st != BP_DONE) return -ENOMEM; return 0; } Commit Message: xen: let alloc_xenballooned_pages() fail if not enough memory free commit a1078e821b605813b63bf6bca414a85f804d5c66 upstream. Instead of trying to allocate pages with GFP_USER in add_ballooned_pages() check the available free memory via si_mem_available(). GFP_USER is far less limiting memory exhaustion than the test via si_mem_available(). This will avoid dom0 running out of memory due to excessive foreign page mappings especially on ARM and on x86 in PVH mode, as those don't have a pre-ballooned area which can be used for foreign mappings. As the normal ballooning suffers from the same problem don't balloon down more than si_mem_available() pages in one iteration. At the same time limit the default maximum number of retries. This is part of XSA-300. Signed-off-by: Juergen Gross <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-400 Target: 1 Example 2: Code: static int tg_schedulable(struct task_group *tg, void *data) { struct rt_schedulable_data *d = data; struct task_group *child; unsigned long total, sum = 0; u64 period, runtime; period = ktime_to_ns(tg->rt_bandwidth.rt_period); runtime = tg->rt_bandwidth.rt_runtime; if (tg == d->tg) { period = d->rt_period; runtime = d->rt_runtime; } /* * Cannot have more runtime than the period. */ if (runtime > period && runtime != RUNTIME_INF) return -EINVAL; /* * Ensure we don't starve existing RT tasks. */ if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg)) return -EBUSY; total = to_ratio(period, runtime); /* * Nobody can have more than the global setting allows. */ if (total > to_ratio(global_rt_period(), global_rt_runtime())) return -EINVAL; /* * The sum of our children's runtime should not exceed our own. */ list_for_each_entry_rcu(child, &tg->children, siblings) { period = ktime_to_ns(child->rt_bandwidth.rt_period); runtime = child->rt_bandwidth.rt_runtime; if (child == d->tg) { period = d->rt_period; runtime = d->rt_runtime; } sum += to_ratio(period, runtime); } if (sum > total) return -EINVAL; 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: encode_layoutcommit(struct xdr_stream *xdr, struct inode *inode, const struct nfs4_layoutcommit_args *args, struct compound_hdr *hdr) { __be32 *p; dprintk("%s: lbw: %llu type: %d\n", __func__, args->lastbytewritten, NFS_SERVER(args->inode)->pnfs_curr_ld->id); p = reserve_space(xdr, 44 + NFS4_STATEID_SIZE); *p++ = cpu_to_be32(OP_LAYOUTCOMMIT); /* Only whole file layouts */ p = xdr_encode_hyper(p, 0); /* offset */ p = xdr_encode_hyper(p, args->lastbytewritten + 1); /* length */ *p++ = cpu_to_be32(0); /* reclaim */ p = xdr_encode_opaque_fixed(p, args->stateid.data, NFS4_STATEID_SIZE); *p++ = cpu_to_be32(1); /* newoffset = TRUE */ p = xdr_encode_hyper(p, args->lastbytewritten); *p++ = cpu_to_be32(0); /* Never send time_modify_changed */ *p++ = cpu_to_be32(NFS_SERVER(args->inode)->pnfs_curr_ld->id);/* type */ if (NFS_SERVER(inode)->pnfs_curr_ld->encode_layoutcommit) NFS_SERVER(inode)->pnfs_curr_ld->encode_layoutcommit( NFS_I(inode)->layout, xdr, args); else { p = reserve_space(xdr, 4); *p = cpu_to_be32(0); /* no layout-type payload */ } hdr->nops++; hdr->replen += decode_layoutcommit_maxsz; return 0; } 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: static int dccp_error(struct net *net, struct nf_conn *tmpl, struct sk_buff *skb, unsigned int dataoff, enum ip_conntrack_info *ctinfo, u_int8_t pf, unsigned int hooknum) { struct dccp_hdr _dh, *dh; unsigned int dccp_len = skb->len - dataoff; unsigned int cscov; const char *msg; dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &dh); if (dh == NULL) { msg = "nf_ct_dccp: short packet "; goto out_invalid; } if (dh->dccph_doff * 4 < sizeof(struct dccp_hdr) || dh->dccph_doff * 4 > dccp_len) { msg = "nf_ct_dccp: truncated/malformed packet "; goto out_invalid; } cscov = dccp_len; if (dh->dccph_cscov) { cscov = (dh->dccph_cscov - 1) * 4; if (cscov > dccp_len) { msg = "nf_ct_dccp: bad checksum coverage "; goto out_invalid; } } if (net->ct.sysctl_checksum && hooknum == NF_INET_PRE_ROUTING && nf_checksum_partial(skb, hooknum, dataoff, cscov, IPPROTO_DCCP, pf)) { msg = "nf_ct_dccp: bad checksum "; goto out_invalid; } if (dh->dccph_type >= DCCP_PKT_INVALID) { msg = "nf_ct_dccp: reserved packet type "; goto out_invalid; } return NF_ACCEPT; out_invalid: if (LOG_INVALID(net, IPPROTO_DCCP)) nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL, "%s", msg); return -NF_ACCEPT; } Commit Message: netfilter: nf_conntrack_dccp: fix skb_header_pointer API usages Some occurences in the netfilter tree use skb_header_pointer() in the following way ... struct dccp_hdr _dh, *dh; ... skb_header_pointer(skb, dataoff, sizeof(_dh), &dh); ... where dh itself is a pointer that is being passed as the copy buffer. Instead, we need to use &_dh as the forth argument so that we're copying the data into an actual buffer that sits on the stack. Currently, we probably could overwrite memory on the stack (e.g. with a possibly mal-formed DCCP packet), but unintentionally, as we only want the buffer to be placed into _dh variable. Fixes: 2bc780499aa3 ("[NETFILTER]: nf_conntrack: add DCCP protocol support") Signed-off-by: Daniel Borkmann <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: static void mcryptd_hash_init(struct crypto_async_request *req_async, int err) { struct mcryptd_hash_ctx *ctx = crypto_tfm_ctx(req_async->tfm); struct crypto_shash *child = ctx->child; struct ahash_request *req = ahash_request_cast(req_async); struct mcryptd_hash_request_ctx *rctx = ahash_request_ctx(req); struct shash_desc *desc = &rctx->desc; if (unlikely(err == -EINPROGRESS)) goto out; desc->tfm = child; desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP; err = crypto_shash_init(desc); req->base.complete = rctx->complete; out: local_bh_disable(); rctx->complete(&req->base, err); local_bh_enable(); } Commit Message: crypto: include crypto- module prefix in template This adds the module loading prefix "crypto-" to the template lookup as well. For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly includes the "crypto-" prefix at every level, correctly rejecting "vfat": net-pf-38 algif-hash crypto-vfat(blowfish) crypto-vfat(blowfish)-all crypto-vfat Reported-by: Mathias Krause <[email protected]> Signed-off-by: Kees Cook <[email protected]> Acked-by: Mathias Krause <[email protected]> Signed-off-by: Herbert Xu <[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 void ikev2_parent_inI1outR1_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct ke_continuation *ke = (struct ke_continuation *)pcrc; struct msg_digest *md = ke->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent inI1outR1: calculated ke+nonce, sending R1")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (ke->md) release_md(ke->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == ke->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_inI1outR1_tail(pcrc, r); if (ke->md != NULL) { complete_v2_state_transition(&ke->md, e); if (ke->md) release_md(ke->md); } reset_globals(); passert(GLOBALS_ARE_RESET()); } Commit Message: SECURITY: Properly handle IKEv2 I1 notification packet without KE payload CWE ID: CWE-20 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 *ReadSVGImage(const ImageInfo *image_info,ExceptionInfo *exception) { char filename[MaxTextExtent]; FILE *file; Image *image; int status, unique_file; ssize_t n; SVGInfo *svg_info; unsigned char message[MaxTextExtent]; xmlSAXHandler sax_modules; xmlSAXHandlerPtr sax_handler; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if ((image->x_resolution < MagickEpsilon) || (image->y_resolution < MagickEpsilon)) { GeometryInfo geometry_info; int flags; flags=ParseGeometry(SVGDensityGeometry,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } if (LocaleCompare(image_info->magick,"MSVG") != 0) { const DelegateInfo *delegate_info; delegate_info=GetDelegateInfo("svg:decode",(char *) NULL,exception); if (delegate_info != (const DelegateInfo *) NULL) { char background[MaxTextExtent], command[MaxTextExtent], density[MaxTextExtent], input_filename[MaxTextExtent], opacity[MaxTextExtent], output_filename[MaxTextExtent], unique[MaxTextExtent]; int status; struct stat attributes; /* Our best hope for compliance to the SVG standard. */ status=AcquireUniqueSymbolicLink(image->filename,input_filename); (void) AcquireUniqueFilename(output_filename); (void) AcquireUniqueFilename(unique); (void) FormatLocaleString(density,MaxTextExtent,"%.20g,%.20g", image->x_resolution,image->y_resolution); (void) FormatLocaleString(background,MaxTextExtent, "rgb(%.20g%%,%.20g%%,%.20g%%)", 100.0*QuantumScale*image->background_color.red, 100.0*QuantumScale*image->background_color.green, 100.0*QuantumScale*image->background_color.blue); (void) FormatLocaleString(opacity,MaxTextExtent,"%.20g",QuantumScale* (QuantumRange-image->background_color.opacity)); (void) FormatLocaleString(command,MaxTextExtent,GetDelegateCommands( delegate_info),input_filename,output_filename,density,background, opacity,unique); status=ExternalDelegateCommand(MagickFalse,image_info->verbose, command,(char *) NULL,exception); (void) RelinquishUniqueFileResource(unique); (void) RelinquishUniqueFileResource(input_filename); if ((status == 0) && (stat(output_filename,&attributes) == 0) && (attributes.st_size != 0)) { ImageInfo *read_info; read_info=CloneImageInfo(image_info); (void) CopyMagickString(read_info->filename,output_filename, MaxTextExtent); image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); (void) RelinquishUniqueFileResource(output_filename); if (image != (Image *) NULL) return(image); } (void) RelinquishUniqueFileResource(output_filename); } { #if defined(MAGICKCORE_RSVG_DELEGATE) #if defined(MAGICKCORE_CAIRO_DELEGATE) cairo_surface_t *cairo_surface; cairo_t *cairo_image; MemoryInfo *pixel_info; register unsigned char *p; RsvgDimensionData dimension_info; unsigned char *pixels; #else GdkPixbuf *pixel_buffer; register const guchar *p; #endif GError *error; ssize_t y; PixelPacket fill_color; register ssize_t x; register PixelPacket *q; RsvgHandle *svg_handle; svg_handle=rsvg_handle_new(); if (svg_handle == (RsvgHandle *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); rsvg_handle_set_base_uri(svg_handle,image_info->filename); if ((image->x_resolution != 90.0) && (image->y_resolution != 90.0)) rsvg_handle_set_dpi_x_y(svg_handle,image->x_resolution, image->y_resolution); while ((n=ReadBlob(image,MaxTextExtent,message)) != 0) { error=(GError *) NULL; (void) rsvg_handle_write(svg_handle,message,n,&error); if (error != (GError *) NULL) g_error_free(error); } error=(GError *) NULL; rsvg_handle_close(svg_handle,&error); if (error != (GError *) NULL) g_error_free(error); #if defined(MAGICKCORE_CAIRO_DELEGATE) rsvg_handle_get_dimensions(svg_handle,&dimension_info); image->columns=image->x_resolution*dimension_info.width/90.0; image->rows=image->y_resolution*dimension_info.height/90.0; pixel_info=(MemoryInfo *) NULL; #else pixel_buffer=rsvg_handle_get_pixbuf(svg_handle); rsvg_handle_free(svg_handle); image->columns=gdk_pixbuf_get_width(pixel_buffer); image->rows=gdk_pixbuf_get_height(pixel_buffer); #endif image->matte=MagickTrue; SetImageProperty(image,"svg:base-uri", rsvg_handle_get_base_uri(svg_handle)); if ((image->columns == 0) || (image->rows == 0)) { #if !defined(MAGICKCORE_CAIRO_DELEGATE) g_object_unref(G_OBJECT(pixel_buffer)); #endif g_object_unref(svg_handle); ThrowReaderException(MissingDelegateError, "NoDecodeDelegateForThisImageFormat"); } if (image_info->ping == MagickFalse) { #if defined(MAGICKCORE_CAIRO_DELEGATE) size_t stride; stride=4*image->columns; #if defined(MAGICKCORE_PANGOCAIRO_DELEGATE) stride=(size_t) cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, (int) image->columns); #endif pixel_info=AcquireVirtualMemory(stride,image->rows*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { g_object_unref(svg_handle); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); #endif (void) SetImageBackgroundColor(image); #if defined(MAGICKCORE_CAIRO_DELEGATE) cairo_surface=cairo_image_surface_create_for_data(pixels, CAIRO_FORMAT_ARGB32,(int) image->columns,(int) image->rows, (int) stride); if (cairo_surface == (cairo_surface_t *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); g_object_unref(svg_handle); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } cairo_image=cairo_create(cairo_surface); cairo_set_operator(cairo_image,CAIRO_OPERATOR_CLEAR); cairo_paint(cairo_image); cairo_set_operator(cairo_image,CAIRO_OPERATOR_OVER); cairo_scale(cairo_image,image->x_resolution/90.0, image->y_resolution/90.0); rsvg_handle_render_cairo(svg_handle,cairo_image); cairo_destroy(cairo_image); cairo_surface_destroy(cairo_surface); g_object_unref(svg_handle); p=pixels; #else p=gdk_pixbuf_get_pixels(pixel_buffer); #endif for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { #if defined(MAGICKCORE_CAIRO_DELEGATE) fill_color.blue=ScaleCharToQuantum(*p++); fill_color.green=ScaleCharToQuantum(*p++); fill_color.red=ScaleCharToQuantum(*p++); #else fill_color.red=ScaleCharToQuantum(*p++); fill_color.green=ScaleCharToQuantum(*p++); fill_color.blue=ScaleCharToQuantum(*p++); #endif fill_color.opacity=QuantumRange-ScaleCharToQuantum(*p++); #if defined(MAGICKCORE_CAIRO_DELEGATE) { double gamma; gamma=1.0-QuantumScale*fill_color.opacity; gamma=PerceptibleReciprocal(gamma); fill_color.blue*=gamma; fill_color.green*=gamma; fill_color.red*=gamma; } #endif MagickCompositeOver(&fill_color,fill_color.opacity,q, (MagickRealType) q->opacity,q); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } #if defined(MAGICKCORE_CAIRO_DELEGATE) if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); #else g_object_unref(G_OBJECT(pixel_buffer)); #endif (void) CloseBlob(image); return(GetFirstImageInList(image)); #endif } } /* Open draw file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"w"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) CopyMagickString(image->filename,filename,MaxTextExtent); ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Parse SVG file. */ if (image == (Image *) NULL) return((Image *) NULL); svg_info=AcquireSVGInfo(); if (svg_info == (SVGInfo *) NULL) { (void) fclose(file); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } svg_info->file=file; svg_info->exception=exception; svg_info->image=image; svg_info->image_info=image_info; svg_info->bounds.width=image->columns; svg_info->bounds.height=image->rows; if (image_info->size != (char *) NULL) (void) CloneString(&svg_info->size,image_info->size); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"begin SAX"); (void) xmlSubstituteEntitiesDefault(1); (void) ResetMagickMemory(&sax_modules,0,sizeof(sax_modules)); sax_modules.internalSubset=SVGInternalSubset; sax_modules.isStandalone=SVGIsStandalone; sax_modules.hasInternalSubset=SVGHasInternalSubset; sax_modules.hasExternalSubset=SVGHasExternalSubset; sax_modules.resolveEntity=SVGResolveEntity; sax_modules.getEntity=SVGGetEntity; sax_modules.entityDecl=SVGEntityDeclaration; sax_modules.notationDecl=SVGNotationDeclaration; sax_modules.attributeDecl=SVGAttributeDeclaration; sax_modules.elementDecl=SVGElementDeclaration; sax_modules.unparsedEntityDecl=SVGUnparsedEntityDeclaration; sax_modules.setDocumentLocator=SVGSetDocumentLocator; sax_modules.startDocument=SVGStartDocument; sax_modules.endDocument=SVGEndDocument; sax_modules.startElement=SVGStartElement; sax_modules.endElement=SVGEndElement; sax_modules.reference=SVGReference; sax_modules.characters=SVGCharacters; sax_modules.ignorableWhitespace=SVGIgnorableWhitespace; sax_modules.processingInstruction=SVGProcessingInstructions; sax_modules.comment=SVGComment; sax_modules.warning=SVGWarning; sax_modules.error=SVGError; sax_modules.fatalError=SVGError; sax_modules.getParameterEntity=SVGGetParameterEntity; sax_modules.cdataBlock=SVGCDataBlock; sax_modules.externalSubset=SVGExternalSubset; sax_handler=(&sax_modules); n=ReadBlob(image,MaxTextExtent,message); if (n > 0) { svg_info->parser=xmlCreatePushParserCtxt(sax_handler,svg_info,(char *) message,n,image->filename); while ((n=ReadBlob(image,MaxTextExtent,message)) != 0) { status=xmlParseChunk(svg_info->parser,(char *) message,(int) n,0); if (status != 0) break; } } (void) xmlParseChunk(svg_info->parser,(char *) message,0,1); xmlFreeParserCtxt(svg_info->parser); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"end SAX"); (void) fclose(file); (void) CloseBlob(image); image->columns=svg_info->width; image->rows=svg_info->height; if (exception->severity >= ErrorException) { image=DestroyImage(image); return((Image *) NULL); } if (image_info->ping == MagickFalse) { ImageInfo *read_info; /* Draw image. */ image=DestroyImage(image); image=(Image *) NULL; read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); if (read_info->density != (char *) NULL) read_info->density=DestroyString(read_info->density); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"mvg:%s", filename); image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); } /* Relinquish resources. */ if (image != (Image *) NULL) { if (svg_info->title != (char *) NULL) (void) SetImageProperty(image,"svg:title",svg_info->title); if (svg_info->comment != (char *) NULL) (void) SetImageProperty(image,"svg:comment",svg_info->comment); } svg_info=DestroySVGInfo(svg_info); (void) RelinquishUniqueFileResource(filename); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: static int __init userfaultfd_init(void) { userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache", sizeof(struct userfaultfd_ctx), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, init_once_userfaultfd_ctx); return 0; } 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: 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 pdf_load_xrefs(FILE *fp, pdf_t *pdf) { int i, ver, is_linear; long pos, pos_count; char x, *c, buf[256]; c = NULL; /* Count number of xrefs */ pdf->n_xrefs = 0; fseek(fp, 0, SEEK_SET); while (get_next_eof(fp) >= 0) ++pdf->n_xrefs; if (!pdf->n_xrefs) return 0; /* Load in the start/end positions */ fseek(fp, 0, SEEK_SET); pdf->xrefs = calloc(1, sizeof(xref_t) * pdf->n_xrefs); ver = 1; for (i=0; i<pdf->n_xrefs; i++) { /* Seek to %%EOF */ if ((pos = get_next_eof(fp)) < 0) break; /* Set and increment the version */ pdf->xrefs[i].version = ver++; /* Rewind until we find end of "startxref" */ pos_count = 0; while (SAFE_F(fp, ((x = fgetc(fp)) != 'f'))) fseek(fp, pos - (++pos_count), SEEK_SET); /* Suck in end of "startxref" to start of %%EOF */ if (pos_count >= sizeof(buf)) { ERR("Failed to locate the startxref token. " "This might be a corrupt PDF.\n"); return -1; } memset(buf, 0, sizeof(buf)); SAFE_E(fread(buf, 1, pos_count, fp), pos_count, "Failed to read startxref.\n"); c = buf; while (*c == ' ' || *c == '\n' || *c == '\r') ++c; /* xref start position */ pdf->xrefs[i].start = atol(c); /* If xref is 0 handle linear xref table */ if (pdf->xrefs[i].start == 0) get_xref_linear_skipped(fp, &pdf->xrefs[i]); /* Non-linear, normal operation, so just find the end of the xref */ else { /* xref end position */ pos = ftell(fp); fseek(fp, pdf->xrefs[i].start, SEEK_SET); pdf->xrefs[i].end = get_next_eof(fp); /* Look for next EOF and xref data */ fseek(fp, pos, SEEK_SET); } /* Check validity */ if (!is_valid_xref(fp, pdf, &pdf->xrefs[i])) { is_linear = pdf->xrefs[i].is_linear; memset(&pdf->xrefs[i], 0, sizeof(xref_t)); pdf->xrefs[i].is_linear = is_linear; rewind(fp); get_next_eof(fp); continue; } /* Load the entries from the xref */ load_xref_entries(fp, &pdf->xrefs[i]); } /* Now we have all xref tables, if this is linearized, we need * to make adjustments so that things spit out properly */ if (pdf->xrefs[0].is_linear) resolve_linearized_pdf(pdf); /* Ok now we have all xref data. Go through those versions of the * PDF and try to obtain creator information */ load_creator(fp, pdf); return pdf->n_xrefs; } Commit Message: Zero and sanity check all dynamic allocs. This addresses the memory issues in Issue #6 expressed in calloc_some.pdf and malloc_some.pdf CWE ID: CWE-787 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: GDataFileError GDataWapiFeedProcessor::FeedToFileResourceMap( const std::vector<DocumentFeed*>& feed_list, FileResourceIdMap* file_map, int64* feed_changestamp, FeedToFileResourceMapUmaStats* uma_stats) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(uma_stats); GDataFileError error = GDATA_FILE_OK; uma_stats->num_regular_files = 0; uma_stats->num_hosted_documents = 0; uma_stats->num_files_with_entry_kind.clear(); for (size_t i = 0; i < feed_list.size(); ++i) { const DocumentFeed* feed = feed_list[i]; if (i == 0) { const Link* root_feed_upload_link = feed->GetLinkByType(Link::RESUMABLE_CREATE_MEDIA); if (root_feed_upload_link) directory_service_->root()->set_upload_url( root_feed_upload_link->href()); *feed_changestamp = feed->largest_changestamp(); DCHECK_GE(*feed_changestamp, 0); } for (ScopedVector<DocumentEntry>::const_iterator iter = feed->entries().begin(); iter != feed->entries().end(); ++iter) { DocumentEntry* doc = *iter; GDataEntry* entry = GDataEntry::FromDocumentEntry( NULL, doc, directory_service_); if (!entry) continue; GDataFile* as_file = entry->AsGDataFile(); if (as_file) { if (as_file->is_hosted_document()) ++uma_stats->num_hosted_documents; else ++uma_stats->num_regular_files; ++uma_stats->num_files_with_entry_kind[as_file->kind()]; } FileResourceIdMap::iterator map_entry = file_map->find(entry->resource_id()); if (map_entry != file_map->end()) { LOG(WARNING) << "Found duplicate file " << map_entry->second->base_name(); delete map_entry->second; file_map->erase(map_entry); } file_map->insert( std::pair<std::string, GDataEntry*>(entry->resource_id(), entry)); } } if (error != GDATA_FILE_OK) { STLDeleteValues(file_map); } return error; } 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: TemplateURLRef::~TemplateURLRef() { } 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: 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: fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec) { struct mrb_context *c = fiber_check(mrb, self); struct mrb_context *old_c = mrb->c; mrb_value value; fiber_check_cfunc(mrb, c); if (resume && c->status == MRB_FIBER_TRANSFERRED) { mrb_raise(mrb, E_FIBER_ERROR, "resuming transferred fiber"); } if (c->status == MRB_FIBER_RUNNING || c->status == MRB_FIBER_RESUMED) { mrb_raise(mrb, E_FIBER_ERROR, "double resume (fib)"); } if (c->status == MRB_FIBER_TERMINATED) { mrb_raise(mrb, E_FIBER_ERROR, "resuming dead fiber"); } mrb->c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED; c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c); if (c->status == MRB_FIBER_CREATED) { mrb_value *b, *e; if (len >= c->stend - c->stack) { mrb_raise(mrb, E_FIBER_ERROR, "too many arguments to fiber"); } b = c->stack+1; e = b + len; while (b<e) { *b++ = *a++; } c->cibase->argc = (int)len; value = c->stack[0] = MRB_PROC_ENV(c->ci->proc)->stack[0]; } else { value = fiber_result(mrb, a, len); } fiber_switch_context(mrb, c); if (vmexec) { c->vmexec = TRUE; value = mrb_vm_exec(mrb, c->ci[-1].proc, c->ci->pc); mrb->c = old_c; } else { MARK_CONTEXT_MODIFY(c); } return value; } Commit Message: Extend stack when pushing arguments that does not fit in; fix #4038 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 InputWindowInfo::isTrustedOverlay() const { return layoutParamsType == TYPE_INPUT_METHOD || layoutParamsType == TYPE_INPUT_METHOD_DIALOG || layoutParamsType == TYPE_MAGNIFICATION_OVERLAY || layoutParamsType == TYPE_SECURE_SYSTEM_OVERLAY; } Commit Message: Add new MotionEvent flag for partially obscured windows. Due to more complex window layouts resulting in lots of overlapping windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to only be set when the point at which the window was touched is obscured. Unfortunately, this doesn't prevent tapjacking attacks that overlay the dialog's text, making a potentially dangerous operation seem innocuous. To avoid this on particularly sensitive dialogs, introduce a new flag that really does tell you when your window is being even partially overlapped. We aren't exposing this as API since we plan on making the original flag more robust. This is really a workaround for system dialogs since we generally know their layout and screen position, and that they're unlikely to be overlapped by other applications. Bug: 26677796 Change-Id: I9e336afe90f262ba22015876769a9c510048fd47 CWE ID: CWE-264 Target: 1 Example 2: Code: void TabsDetectLanguageFunction::GotLanguage(const std::string& language) { Respond(OneArgument(std::make_unique<base::Value>(language))); Release(); // Balanced in Run() } Commit Message: Call CanCaptureVisiblePage in page capture API. Currently the pageCapture permission allows access to arbitrary local files and chrome:// pages which can be a security concern. In order to address this, the page capture API needs to be changed similar to the captureVisibleTab API. The API will now only allow extensions to capture otherwise-restricted URLs if the user has granted activeTab. In addition, file:// URLs are only capturable with the "Allow on file URLs" option enabled. Bug: 893087 Change-Id: I6d6225a3efb70fc033e2e1c031c633869afac624 Reviewed-on: https://chromium-review.googlesource.com/c/1330689 Commit-Queue: Bettina Dea <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Varun Khaneja <[email protected]> Cr-Commit-Position: refs/heads/master@{#615248} CWE ID: CWE-20 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 AppCacheUpdateJob::OnResponseInfoLoaded( AppCacheResponseInfo* response_info, int64_t response_id) { const net::HttpResponseInfo* http_info = response_info ? &response_info->http_response_info() : nullptr; if (internal_state_ == FETCH_MANIFEST) { if (http_info) manifest_fetcher_->set_existing_response_headers( http_info->headers.get()); manifest_fetcher_->Start(); return; } auto found = loading_responses_.find(response_id); DCHECK(found != loading_responses_.end()); const GURL& url = found->second; if (!http_info) { LoadFromNewestCacheFailed(url, nullptr); // no response found } else if (!CanUseExistingResource(http_info)) { LoadFromNewestCacheFailed(url, response_info); } else { DCHECK(group_->newest_complete_cache()); AppCacheEntry* copy_me = group_->newest_complete_cache()->GetEntry(url); DCHECK(copy_me); DCHECK_EQ(copy_me->response_id(), response_id); auto it = url_file_list_.find(url); DCHECK(it != url_file_list_.end()); AppCacheEntry& entry = it->second; entry.set_response_id(response_id); entry.set_response_size(copy_me->response_size()); inprogress_cache_->AddOrModifyEntry(url, entry); NotifyAllProgress(url); ++url_fetches_completed_; } loading_responses_.erase(found); MaybeCompleteUpdate(); } 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: void sock_release(struct socket *sock) { if (sock->ops) { struct module *owner = sock->ops->owner; sock->ops->release(sock); sock->ops = NULL; module_put(owner); } if (rcu_dereference_protected(sock->wq, 1)->fasync_list) pr_err("%s: fasync list not empty!\n", __func__); if (!sock->file) { iput(SOCK_INODE(sock)); return; } sock->file = NULL; } Commit Message: socket: close race condition between sock_close() and sockfs_setattr() fchownat() doesn't even hold refcnt of fd until it figures out fd is really needed (otherwise is ignored) and releases it after it resolves the path. This means sock_close() could race with sockfs_setattr(), which leads to a NULL pointer dereference since typically we set sock->sk to NULL in ->release(). As pointed out by Al, this is unique to sockfs. So we can fix this in socket layer by acquiring inode_lock in sock_close() and checking against NULL in sockfs_setattr(). sock_release() is called in many places, only the sock_close() path matters here. And fortunately, this should not affect normal sock_close() as it is only called when the last fd refcnt is gone. It only affects sock_close() with a parallel sockfs_setattr() in progress, which is not common. Fixes: 86741ec25462 ("net: core: Add a UID field to struct sock.") Reported-by: shankarapailoor <[email protected]> Cc: Tetsuo Handa <[email protected]> Cc: Lorenzo Colitti <[email protected]> Cc: Al Viro <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: static void coroutine_fn v9fs_getlock(void *opaque) { size_t offset = 7; struct stat stbuf; V9fsFidState *fidp; V9fsGetlock glock; int32_t fid, err = 0; V9fsPDU *pdu = opaque; v9fs_string_init(&glock.client_id); err = pdu_unmarshal(pdu, offset, "dbqqds", &fid, &glock.type, &glock.start, &glock.length, &glock.proc_id, &glock.client_id); if (err < 0) { goto out_nofid; } trace_v9fs_getlock(pdu->tag, pdu->id, fid, glock.type, glock.start, glock.length); fidp = get_fid(pdu, fid); if (fidp == NULL) { err = -ENOENT; goto out_nofid; } err = v9fs_co_fstat(pdu, fidp, &stbuf); if (err < 0) { goto out; } glock.type = P9_LOCK_TYPE_UNLCK; err = pdu_marshal(pdu, offset, "bqqds", glock.type, glock.start, glock.length, glock.proc_id, &glock.client_id); if (err < 0) { goto out; } err += offset; trace_v9fs_getlock_return(pdu->tag, pdu->id, glock.type, glock.start, glock.length, glock.proc_id); out: put_fid(pdu, fidp); out_nofid: pdu_complete(pdu, err); v9fs_string_free(&glock.client_id); } Commit Message: CWE ID: CWE-400 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 attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options) { int ret = 0; int codec_init_ok = 0; AVDictionary *tmp = NULL; const AVPixFmtDescriptor *pixdesc; if (avcodec_is_open(avctx)) return 0; if ((!codec && !avctx->codec)) { av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2()\n"); return AVERROR(EINVAL); } if ((codec && avctx->codec && codec != avctx->codec)) { av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, " "but %s passed to avcodec_open2()\n", avctx->codec->name, codec->name); return AVERROR(EINVAL); } if (!codec) codec = avctx->codec; if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE) return AVERROR(EINVAL); if (options) av_dict_copy(&tmp, *options, 0); ff_lock_avcodec(avctx, codec); avctx->internal = av_mallocz(sizeof(*avctx->internal)); if (!avctx->internal) { ret = AVERROR(ENOMEM); goto end; } avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool)); if (!avctx->internal->pool) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->to_free = av_frame_alloc(); if (!avctx->internal->to_free) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->compat_decode_frame = av_frame_alloc(); if (!avctx->internal->compat_decode_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->buffer_frame = av_frame_alloc(); if (!avctx->internal->buffer_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->buffer_pkt = av_packet_alloc(); if (!avctx->internal->buffer_pkt) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->ds.in_pkt = av_packet_alloc(); if (!avctx->internal->ds.in_pkt) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->last_pkt_props = av_packet_alloc(); if (!avctx->internal->last_pkt_props) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->skip_samples_multiplier = 1; if (codec->priv_data_size > 0) { if (!avctx->priv_data) { avctx->priv_data = av_mallocz(codec->priv_data_size); if (!avctx->priv_data) { ret = AVERROR(ENOMEM); goto end; } if (codec->priv_class) { *(const AVClass **)avctx->priv_data = codec->priv_class; av_opt_set_defaults(avctx->priv_data); } } if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0) goto free_and_end; } else { avctx->priv_data = NULL; } if ((ret = av_opt_set_dict(avctx, &tmp)) < 0) goto free_and_end; if (avctx->codec_whitelist && av_match_list(codec->name, avctx->codec_whitelist, ',') <= 0) { av_log(avctx, AV_LOG_ERROR, "Codec (%s) not on whitelist \'%s\'\n", codec->name, avctx->codec_whitelist); ret = AVERROR(EINVAL); goto free_and_end; } if (!(avctx->coded_width && avctx->coded_height && avctx->width && avctx->height && (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_VP6F || avctx->codec_id == AV_CODEC_ID_DXV))) { if (avctx->coded_width && avctx->coded_height) ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height); else if (avctx->width && avctx->height) ret = ff_set_dimensions(avctx, avctx->width, avctx->height); if (ret < 0) goto free_and_end; } if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height) && ( av_image_check_size2(avctx->coded_width, avctx->coded_height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0 || av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0)) { av_log(avctx, AV_LOG_WARNING, "Ignoring invalid width/height values\n"); ff_set_dimensions(avctx, 0, 0); } if (avctx->width > 0 && avctx->height > 0) { if (av_image_check_sar(avctx->width, avctx->height, avctx->sample_aspect_ratio) < 0) { av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n", avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den); avctx->sample_aspect_ratio = (AVRational){ 0, 1 }; } } /* if the decoder init function was already called previously, * free the already allocated subtitle_header before overwriting it */ if (av_codec_is_decoder(codec)) av_freep(&avctx->subtitle_header); if (avctx->channels > FF_SANE_NB_CHANNELS) { av_log(avctx, AV_LOG_ERROR, "Too many channels: %d\n", avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } avctx->codec = codec; if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) && avctx->codec_id == AV_CODEC_ID_NONE) { avctx->codec_type = codec->type; avctx->codec_id = codec->id; } if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) { av_log(avctx, AV_LOG_ERROR, "Codec type or id mismatches\n"); ret = AVERROR(EINVAL); goto free_and_end; } avctx->frame_number = 0; avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id); if ((avctx->codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) && avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) { const char *codec_string = av_codec_is_encoder(codec) ? "encoder" : "decoder"; AVCodec *codec2; av_log(avctx, AV_LOG_ERROR, "The %s '%s' is experimental but experimental codecs are not enabled, " "add '-strict %d' if you want to use it.\n", codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL); codec2 = av_codec_is_encoder(codec) ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id); if (!(codec2->capabilities & AV_CODEC_CAP_EXPERIMENTAL)) av_log(avctx, AV_LOG_ERROR, "Alternatively use the non experimental %s '%s'.\n", codec_string, codec2->name); ret = AVERROR_EXPERIMENTAL; goto free_and_end; } if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && (!avctx->time_base.num || !avctx->time_base.den)) { avctx->time_base.num = 1; avctx->time_base.den = avctx->sample_rate; } if (!HAVE_THREADS) av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n"); if (CONFIG_FRAME_THREAD_ENCODER && av_codec_is_encoder(avctx->codec)) { ff_unlock_avcodec(codec); //we will instantiate a few encoders thus kick the counter to prevent false detection of a problem ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL); ff_lock_avcodec(avctx, codec); if (ret < 0) goto free_and_end; } if (av_codec_is_decoder(avctx->codec)) { ret = ff_decode_bsfs_init(avctx); if (ret < 0) goto free_and_end; } if (HAVE_THREADS && !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) { ret = ff_thread_init(avctx); if (ret < 0) { goto free_and_end; } } if (!HAVE_THREADS && !(codec->capabilities & AV_CODEC_CAP_AUTO_THREADS)) avctx->thread_count = 1; if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) { av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n", avctx->codec->max_lowres); avctx->lowres = avctx->codec->max_lowres; } if (av_codec_is_encoder(avctx->codec)) { int i; #if FF_API_CODED_FRAME FF_DISABLE_DEPRECATION_WARNINGS avctx->coded_frame = av_frame_alloc(); if (!avctx->coded_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } FF_ENABLE_DEPRECATION_WARNINGS #endif if (avctx->time_base.num <= 0 || avctx->time_base.den <= 0) { av_log(avctx, AV_LOG_ERROR, "The encoder timebase is not set.\n"); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->sample_fmts) { for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) { if (avctx->sample_fmt == avctx->codec->sample_fmts[i]) break; if (avctx->channels == 1 && av_get_planar_sample_fmt(avctx->sample_fmt) == av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) { avctx->sample_fmt = avctx->codec->sample_fmts[i]; break; } } if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) { char buf[128]; snprintf(buf, sizeof(buf), "%d", avctx->sample_fmt); av_log(avctx, AV_LOG_ERROR, "Specified sample format %s is invalid or not supported\n", (char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf)); ret = AVERROR(EINVAL); goto free_and_end; } } if (avctx->codec->pix_fmts) { for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++) if (avctx->pix_fmt == avctx->codec->pix_fmts[i]) break; if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE && !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG) && avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) { char buf[128]; snprintf(buf, sizeof(buf), "%d", avctx->pix_fmt); av_log(avctx, AV_LOG_ERROR, "Specified pixel format %s is invalid or not supported\n", (char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf)); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ411P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P) avctx->color_range = AVCOL_RANGE_JPEG; } if (avctx->codec->supported_samplerates) { for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++) if (avctx->sample_rate == avctx->codec->supported_samplerates[i]) break; if (avctx->codec->supported_samplerates[i] == 0) { av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n", avctx->sample_rate); ret = AVERROR(EINVAL); goto free_and_end; } } if (avctx->sample_rate < 0) { av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n", avctx->sample_rate); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->channel_layouts) { if (!avctx->channel_layout) { av_log(avctx, AV_LOG_WARNING, "Channel layout not specified\n"); } else { for (i = 0; avctx->codec->channel_layouts[i] != 0; i++) if (avctx->channel_layout == avctx->codec->channel_layouts[i]) break; if (avctx->codec->channel_layouts[i] == 0) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_ERROR, "Specified channel layout '%s' is not supported\n", buf); ret = AVERROR(EINVAL); goto free_and_end; } } } if (avctx->channel_layout && avctx->channels) { int channels = av_get_channel_layout_nb_channels(avctx->channel_layout); if (channels != avctx->channels) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_ERROR, "Channel layout '%s' with %d channels does not match number of specified channels %d\n", buf, channels, avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } } else if (avctx->channel_layout) { avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout); } if (avctx->channels < 0) { av_log(avctx, AV_LOG_ERROR, "Specified number of channels %d is not supported\n", avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } if(avctx->codec_type == AVMEDIA_TYPE_VIDEO) { pixdesc = av_pix_fmt_desc_get(avctx->pix_fmt); if ( avctx->bits_per_raw_sample < 0 || (avctx->bits_per_raw_sample > 8 && pixdesc->comp[0].depth <= 8)) { av_log(avctx, AV_LOG_WARNING, "Specified bit depth %d not possible with the specified pixel formats depth %d\n", avctx->bits_per_raw_sample, pixdesc->comp[0].depth); avctx->bits_per_raw_sample = pixdesc->comp[0].depth; } if (avctx->width <= 0 || avctx->height <= 0) { av_log(avctx, AV_LOG_ERROR, "dimensions not set\n"); ret = AVERROR(EINVAL); goto free_and_end; } } if ( (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO) && avctx->bit_rate>0 && avctx->bit_rate<1000) { av_log(avctx, AV_LOG_WARNING, "Bitrate %"PRId64" is extremely low, maybe you mean %"PRId64"k\n", avctx->bit_rate, avctx->bit_rate); } if (!avctx->rc_initial_buffer_occupancy) avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3LL / 4; if (avctx->ticks_per_frame && avctx->time_base.num && avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) { av_log(avctx, AV_LOG_ERROR, "ticks_per_frame %d too large for the timebase %d/%d.", avctx->ticks_per_frame, avctx->time_base.num, avctx->time_base.den); goto free_and_end; } if (avctx->hw_frames_ctx) { AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data; if (frames_ctx->format != avctx->pix_fmt) { av_log(avctx, AV_LOG_ERROR, "Mismatching AVCodecContext.pix_fmt and AVHWFramesContext.format\n"); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->sw_pix_fmt != AV_PIX_FMT_NONE && avctx->sw_pix_fmt != frames_ctx->sw_format) { av_log(avctx, AV_LOG_ERROR, "Mismatching AVCodecContext.sw_pix_fmt (%s) " "and AVHWFramesContext.sw_format (%s)\n", av_get_pix_fmt_name(avctx->sw_pix_fmt), av_get_pix_fmt_name(frames_ctx->sw_format)); ret = AVERROR(EINVAL); goto free_and_end; } avctx->sw_pix_fmt = frames_ctx->sw_format; } } avctx->pts_correction_num_faulty_pts = avctx->pts_correction_num_faulty_dts = 0; avctx->pts_correction_last_pts = avctx->pts_correction_last_dts = INT64_MIN; if ( !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY && avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO) av_log(avctx, AV_LOG_WARNING, "gray decoding requested but not enabled at configuration time\n"); if ( avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME) || avctx->internal->frame_thread_encoder)) { ret = avctx->codec->init(avctx); if (ret < 0) { goto free_and_end; } codec_init_ok = 1; } ret=0; if (av_codec_is_decoder(avctx->codec)) { if (!avctx->bit_rate) avctx->bit_rate = get_bit_rate(avctx); /* validate channel layout from the decoder */ if (avctx->channel_layout) { int channels = av_get_channel_layout_nb_channels(avctx->channel_layout); if (!avctx->channels) avctx->channels = channels; else if (channels != avctx->channels) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_WARNING, "Channel layout '%s' with %d channels does not match specified number of channels %d: " "ignoring specified channel layout\n", buf, channels, avctx->channels); avctx->channel_layout = 0; } } if (avctx->channels && avctx->channels < 0 || avctx->channels > FF_SANE_NB_CHANNELS) { ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->bits_per_coded_sample < 0) { ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->sub_charenc) { if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) { av_log(avctx, AV_LOG_ERROR, "Character encoding is only " "supported with subtitles codecs\n"); ret = AVERROR(EINVAL); goto free_and_end; } else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) { av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, " "subtitles character encoding will be ignored\n", avctx->codec_descriptor->name); avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING; } else { /* input character encoding is set for a text based subtitle * codec at this point */ if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC) avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER; if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) { #if CONFIG_ICONV iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc); if (cd == (iconv_t)-1) { ret = AVERROR(errno); av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context " "with input character encoding \"%s\"\n", avctx->sub_charenc); goto free_and_end; } iconv_close(cd); #else av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles " "conversion needs a libavcodec built with iconv support " "for this codec\n"); ret = AVERROR(ENOSYS); goto free_and_end; #endif } } } #if FF_API_AVCTX_TIMEBASE if (avctx->framerate.num > 0 && avctx->framerate.den > 0) avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1})); #endif } if (codec->priv_data_size > 0 && avctx->priv_data && codec->priv_class) { av_assert0(*(const AVClass **)avctx->priv_data == codec->priv_class); } end: ff_unlock_avcodec(codec); if (options) { av_dict_free(options); *options = tmp; } return ret; free_and_end: if (avctx->codec && (codec_init_ok || (avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP))) avctx->codec->close(avctx); if (codec->priv_class && codec->priv_data_size) av_opt_free(avctx->priv_data); av_opt_free(avctx); #if FF_API_CODED_FRAME FF_DISABLE_DEPRECATION_WARNINGS av_frame_free(&avctx->coded_frame); FF_ENABLE_DEPRECATION_WARNINGS #endif av_dict_free(&tmp); av_freep(&avctx->priv_data); if (avctx->internal) { av_frame_free(&avctx->internal->to_free); av_frame_free(&avctx->internal->compat_decode_frame); av_frame_free(&avctx->internal->buffer_frame); av_packet_free(&avctx->internal->buffer_pkt); av_packet_free(&avctx->internal->last_pkt_props); av_packet_free(&avctx->internal->ds.in_pkt); ff_decode_bsfs_uninit(avctx); av_freep(&avctx->internal->pool); } av_freep(&avctx->internal); avctx->codec = NULL; goto end; } Commit Message: avcodec/utils: Check close before calling it Fixes: NULL pointer dereference Fixes: 15733/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_IDF_fuzzer-5658616977162240 Reviewed-by: Paul B Mahol <[email protected]> Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg Signed-off-by: Michael Niedermayer <[email protected]> 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: status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) { Mutex::Autolock _l(mLock); ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface); if (mState == DESTROYED || mEffectInterface == NULL) { return NO_INIT; } if (mStatus != NO_ERROR) { return mStatus; } if (cmdCode == EFFECT_CMD_GET_PARAM && (*replySize < sizeof(effect_param_t) || ((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t))) { android_errorWriteLog(0x534e4554, "29251553"); return -EINVAL; } status_t status = (*mEffectInterface)->command(mEffectInterface, cmdCode, cmdSize, pCmdData, replySize, pReplyData); if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) { uint32_t size = (replySize == NULL) ? 0 : *replySize; for (size_t i = 1; i < mHandles.size(); i++) { EffectHandle *h = mHandles[i]; if (h != NULL && !h->destroyed_l()) { h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData); } } } return status; } Commit Message: Add EFFECT_CMD_SET_PARAM parameter checking Bug: 30204301 Change-Id: Ib9c3ee1c2f23c96f8f7092dd9e146bc453d7a290 (cherry picked from commit e4a1d91501d47931dbae19c47815952378787ab6) CWE ID: CWE-200 Target: 1 Example 2: Code: static bool fuse_page_is_writeback(struct inode *inode, pgoff_t index) { struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_inode *fi = get_fuse_inode(inode); struct fuse_req *req; bool found = false; spin_lock(&fc->lock); list_for_each_entry(req, &fi->writepages, writepages_entry) { pgoff_t curr_index; BUG_ON(req->inode != inode); curr_index = req->misc.write.in.offset >> PAGE_CACHE_SHIFT; if (curr_index == index) { found = true; break; } } spin_unlock(&fc->lock); return found; } Commit Message: fuse: verify ioctl retries Verify that the total length of the iovec returned in FUSE_IOCTL_RETRY doesn't overflow iov_length(). Signed-off-by: Miklos Szeredi <[email protected]> CC: Tejun Heo <[email protected]> CC: <[email protected]> [2.6.31+] 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 kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr) { return kvm_x86_ops->set_msr(vcpu, msr); } Commit Message: KVM: x86: Check non-canonical addresses upon WRMSR Upon WRMSR, the CPU should inject #GP if a non-canonical value (address) is written to certain MSRs. The behavior is "almost" identical for AMD and Intel (ignoring MSRs that are not implemented in either architecture since they would anyhow #GP). However, IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if non-canonical address is written on Intel but not on AMD (which ignores the top 32-bits). Accordingly, this patch injects a #GP on the MSRs which behave identically on Intel and AMD. To eliminate the differences between the architecutres, the value which is written to IA32_SYSENTER_ESP and IA32_SYSENTER_EIP is turned to canonical value before writing instead of injecting a #GP. Some references from Intel and AMD manuals: According to Intel SDM description of WRMSR instruction #GP is expected on WRMSR "If the source register contains a non-canonical address and ECX specifies one of the following MSRs: IA32_DS_AREA, IA32_FS_BASE, IA32_GS_BASE, IA32_KERNEL_GS_BASE, IA32_LSTAR, IA32_SYSENTER_EIP, IA32_SYSENTER_ESP." According to AMD manual instruction manual: LSTAR/CSTAR (SYSCALL): "The WRMSR instruction loads the target RIP into the LSTAR and CSTAR registers. If an RIP written by WRMSR is not in canonical form, a general-protection exception (#GP) occurs." IA32_GS_BASE and IA32_FS_BASE (WRFSBASE/WRGSBASE): "The address written to the base field must be in canonical form or a #GP fault will occur." IA32_KERNEL_GS_BASE (SWAPGS): "The address stored in the KernelGSbase MSR must be in canonical form." This patch fixes CVE-2014-3610. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> 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: void Verify_StoreExistingGroupExistingCache(base::Time expected_update_time) { EXPECT_TRUE(delegate()->stored_group_success_); EXPECT_EQ(cache_.get(), group_->newest_complete_cache()); AppCacheDatabase::CacheRecord cache_record; EXPECT_TRUE(database()->FindCache(1, &cache_record)); EXPECT_EQ(1, cache_record.cache_id); EXPECT_EQ(1, cache_record.group_id); EXPECT_FALSE(cache_record.online_wildcard); EXPECT_TRUE(expected_update_time == cache_record.update_time); EXPECT_EQ(100 + kDefaultEntrySize, cache_record.cache_size); std::vector<AppCacheDatabase::EntryRecord> entry_records; EXPECT_TRUE(database()->FindEntriesForCache(1, &entry_records)); EXPECT_EQ(2U, entry_records.size()); if (entry_records[0].url == kDefaultEntryUrl) entry_records.erase(entry_records.begin()); EXPECT_EQ(1, entry_records[0].cache_id); EXPECT_EQ(kEntryUrl, entry_records[0].url); EXPECT_EQ(AppCacheEntry::MASTER, entry_records[0].flags); EXPECT_EQ(1, entry_records[0].response_id); EXPECT_EQ(100, entry_records[0].response_size); EXPECT_EQ(100 + kDefaultEntrySize, storage()->usage_map_[kOrigin]); EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_); EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_); EXPECT_EQ(100, mock_quota_manager_proxy_->last_delta_); TestFinished(); } 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 Target: 1 Example 2: Code: register_vrrp_scheduler_addresses(void) { register_thread_address("vrrp_arp_thread", vrrp_arp_thread); register_thread_address("vrrp_dispatcher_init", vrrp_dispatcher_init); register_thread_address("vrrp_gratuitous_arp_thread", vrrp_gratuitous_arp_thread); register_thread_address("vrrp_lower_prio_gratuitous_arp_thread", vrrp_lower_prio_gratuitous_arp_thread); register_thread_address("vrrp_script_child_thread", vrrp_script_child_thread); register_thread_address("vrrp_script_thread", vrrp_script_thread); register_thread_address("vrrp_read_dispatcher_thread", vrrp_read_dispatcher_thread); #ifdef _WITH_BFD_ register_thread_address("vrrp_bfd_thread", vrrp_bfd_thread); #endif } Commit Message: When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-59 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: SPL_METHOD(RecursiveDirectoryIterator, getSubPathname) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *sub_name; int len; char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { len = spprintf(&sub_name, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name); RETURN_STRINGL(sub_name, len, 0); } else { RETURN_STRING(intern->u.dir.entry.d_name, 1); } } Commit Message: Fix bug #72262 - do not overflow int 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: void BlockPainter::PaintScrollHitTestDisplayItem(const PaintInfo& paint_info) { DCHECK(RuntimeEnabledFeatures::SlimmingPaintV2Enabled()); if (paint_info.GetGlobalPaintFlags() & kGlobalPaintFlattenCompositingLayers) return; const auto* fragment = paint_info.FragmentToPaint(layout_block_); const auto* properties = fragment ? fragment->PaintProperties() : nullptr; if (properties && properties->Scroll()) { DCHECK(properties->ScrollTranslation()); ScopedPaintChunkProperties scroll_hit_test_properties( paint_info.context.GetPaintController(), fragment->LocalBorderBoxProperties(), layout_block_, DisplayItem::kScrollHitTest); ScrollHitTestDisplayItem::Record(paint_info.context, layout_block_, DisplayItem::kScrollHitTest, properties->ScrollTranslation()); } } 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: Target: 1 Example 2: Code: error::Error GLES2DecoderImpl::HandleBeginQueryEXT( uint32 immediate_data_size, const gles2::BeginQueryEXT& c) { GLenum target = static_cast<GLenum>(c.target); GLuint client_id = static_cast<GLuint>(c.id); int32 sync_shm_id = static_cast<int32>(c.sync_data_shm_id); uint32 sync_shm_offset = static_cast<uint32>(c.sync_data_shm_offset); switch (target) { case GL_COMMANDS_ISSUED_CHROMIUM: break; default: if (!feature_info_->feature_flags().occlusion_query_boolean) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled"); return error::kNoError; } break; } if (current_query_) { SetGLError( GL_INVALID_OPERATION, "glBeginQueryEXT", "query already in progress"); return error::kNoError; } if (client_id == 0) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "id is 0"); return error::kNoError; } QueryManager::Query* query = query_manager_->GetQuery(client_id); if (!query) { query = query_manager_->CreateQuery( target, client_id, sync_shm_id, sync_shm_offset); } if (query->target() != target) { SetGLError( GL_INVALID_OPERATION, "glBeginQueryEXT", "target does not match"); return error::kNoError; } else if (query->shm_id() != sync_shm_id || query->shm_offset() != sync_shm_offset) { DLOG(ERROR) << "Shared memory used by query not the same as before"; return error::kInvalidArguments; } if (!query_manager_->BeginQuery(query)) { return error::kOutOfBounds; } current_query_ = query; return error::kNoError; } Commit Message: Fix SafeAdd and SafeMultiply BUG=145648,145544 Review URL: https://chromiumcodereview.appspot.com/10916165 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 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: static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb, __be16 sport, __be16 dport, struct udp_table *udptable) { const struct iphdr *iph = ip_hdr(skb); return __udp4_lib_lookup(dev_net(skb_dst(skb)->dev), iph->saddr, sport, iph->daddr, dport, inet_iif(skb), udptable); } Commit Message: udp: fix behavior of wrong checksums We have two problems in UDP stack related to bogus checksums : 1) We return -EAGAIN to application even if receive queue is not empty. This breaks applications using edge trigger epoll() 2) Under UDP flood, we can loop forever without yielding to other processes, potentially hanging the host, especially on non SMP. This patch is an attempt to make things better. We might in the future add extra support for rt applications wanting to better control time spent doing a recv() in a hostile environment. For example we could validate checksums before queuing packets in socket receive queue. Signed-off-by: Eric Dumazet <[email protected]> Cc: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]> 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: xmlParseStartTag(xmlParserCtxtPtr ctxt) { const xmlChar *name; const xmlChar *attname; xmlChar *attvalue; const xmlChar **atts = ctxt->atts; int nbatts = 0; int maxatts = ctxt->maxatts; int i; if (RAW != '<') return(NULL); NEXT1; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseStartTag: invalid element name\n"); return(NULL); } /* * Now parse the attributes, it ends up with the ending * * (S Attribute)* S? */ SKIP_BLANKS; GROW; while ((RAW != '>') && ((RAW != '/') || (NXT(1) != '>')) && (IS_BYTE_CHAR(RAW))) { const xmlChar *q = CUR_PTR; unsigned int cons = ctxt->input->consumed; attname = xmlParseAttribute(ctxt, &attvalue); if ((attname != NULL) && (attvalue != NULL)) { /* * [ WFC: Unique Att Spec ] * No attribute name may appear more than once in the same * start-tag or empty-element tag. */ for (i = 0; i < nbatts;i += 2) { if (xmlStrEqual(atts[i], attname)) { xmlErrAttributeDup(ctxt, NULL, attname); xmlFree(attvalue); goto failed; } } /* * Add the pair to atts */ if (atts == NULL) { maxatts = 22; /* allow for 10 attrs by default */ atts = (const xmlChar **) xmlMalloc(maxatts * sizeof(xmlChar *)); if (atts == NULL) { xmlErrMemory(ctxt, NULL); if (attvalue != NULL) xmlFree(attvalue); goto failed; } ctxt->atts = atts; ctxt->maxatts = maxatts; } else if (nbatts + 4 > maxatts) { const xmlChar **n; maxatts *= 2; n = (const xmlChar **) xmlRealloc((void *) atts, maxatts * sizeof(const xmlChar *)); if (n == NULL) { xmlErrMemory(ctxt, NULL); if (attvalue != NULL) xmlFree(attvalue); goto failed; } atts = n; ctxt->atts = atts; ctxt->maxatts = maxatts; } atts[nbatts++] = attname; atts[nbatts++] = attvalue; atts[nbatts] = NULL; atts[nbatts + 1] = NULL; } else { if (attvalue != NULL) xmlFree(attvalue); } failed: GROW if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) break; if (!IS_BLANK_CH(RAW)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "attributes construct error\n"); } SKIP_BLANKS; if ((cons == ctxt->input->consumed) && (q == CUR_PTR) && (attname == NULL) && (attvalue == NULL)) { xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, "xmlParseStartTag: problem parsing attributes\n"); break; } SHRINK; GROW; } /* * SAX: Start of Element ! */ if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL) && (!ctxt->disableSAX)) { if (nbatts > 0) ctxt->sax->startElement(ctxt->userData, name, atts); else ctxt->sax->startElement(ctxt->userData, name, NULL); } if (atts != NULL) { /* Free only the content strings */ for (i = 1;i < nbatts;i+=2) if (atts[i] != NULL) xmlFree((xmlChar *) atts[i]); } return(name); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: static int btrfs_ioctl_getflags(struct file *file, void __user *arg) { struct btrfs_inode *ip = BTRFS_I(file->f_path.dentry->d_inode); unsigned int flags = btrfs_flags_to_ioctl(ip->flags); if (copy_to_user(arg, &flags, sizeof(flags))) return -EFAULT; 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 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: alloc_trace_space(const gs_ref_memory_t *imem) { return imem->space + (imem->stable_memory == (const gs_memory_t *)imem); } Commit Message: 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: SProcXFixesSelectCursorInput(ClientPtr client) { REQUEST(xXFixesSelectCursorInputReq); swaps(&stuff->length); swapl(&stuff->window); return (*ProcXFixesVector[stuff->xfixesReqType]) (client); } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: static inline unsigned int ReadProfileLong(const EndianType endian, unsigned char *buffer) { unsigned int value; if (endian == LSBEndian) { value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8 ) | (buffer[0])); return((unsigned int) (value & 0xffffffff)); } value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); return((unsigned int) (value & 0xffffffff)); } Commit Message: Fixed SEGV reported in https://github.com/ImageMagick/ImageMagick/issues/130 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 RenderWidgetHostViewAura::OnLostResources() { image_transport_clients_.clear(); current_surface_ = 0; protection_state_id_ = 0; current_surface_is_protected_ = true; current_surface_in_use_by_compositor_ = true; surface_route_id_ = 0; UpdateExternalTexture(); locks_pending_commit_.clear(); DCHECK(!shared_surface_handle_.is_null()); ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); factory->DestroySharedSurfaceHandle(shared_surface_handle_); shared_surface_handle_ = factory->CreateSharedSurfaceHandle(); host_->CompositingSurfaceUpdated(); host_->ScheduleComposite(); } 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:
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 TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception) { char message[MagickPathExtent], *text; uint32 count, length, type; unsigned long *tietz; if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) (void) SetImageProperty(image,"tiff:artist",text,exception); if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) (void) SetImageProperty(image,"tiff:copyright",text,exception); if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) (void) SetImageProperty(image,"tiff:timestamp",text,exception); if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) (void) SetImageProperty(image,"tiff:document",text,exception); if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) (void) SetImageProperty(image,"tiff:hostcomputer",text,exception); if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) (void) SetImageProperty(image,"comment",text,exception); if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) (void) SetImageProperty(image,"tiff:make",text,exception); if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) (void) SetImageProperty(image,"tiff:model",text,exception); if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:image-id",message,exception); } if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) (void) SetImageProperty(image,"label",text,exception); if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) (void) SetImageProperty(image,"tiff:software",text,exception); if (TIFFGetField(tiff,33423,&count,&text) == 1) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-33423",message,exception); } if (TIFFGetField(tiff,36867,&count,&text) == 1) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-36867",message,exception); } if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1) switch (type) { case 0x01: { (void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE", exception); break; } case 0x02: { (void) SetImageProperty(image,"tiff:subfiletype","PAGE",exception); break; } case 0x04: { (void) SetImageProperty(image,"tiff:subfiletype","MASK",exception); break; } default: break; } if (TIFFGetField(tiff,37706,&length,&tietz) == 1) { (void) FormatLocaleString(message,MagickPathExtent,"%lu",tietz[0]); (void) SetImageProperty(image,"tiff:tietz_offset",message,exception); } } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/298 CWE ID: CWE-476 Target: 1 Example 2: Code: static struct page *__read_cache_page(struct address_space *mapping, pgoff_t index, int (*filler)(void *,struct page*), void *data) { struct page *page; int err; repeat: page = find_get_page(mapping, index); if (!page) { page = page_cache_alloc_cold(mapping); if (!page) return ERR_PTR(-ENOMEM); err = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL); if (unlikely(err)) { page_cache_release(page); if (err == -EEXIST) goto repeat; /* Presumably ENOMEM for radix tree node */ return ERR_PTR(err); } err = filler(data, page); if (err < 0) { page_cache_release(page); page = ERR_PTR(err); } } return page; } Commit Message: fix writev regression: pan hanging unkillable and un-straceable Frederik Himpe reported an unkillable and un-straceable pan process. Zero length iovecs can go into an infinite loop in writev, because the iovec iterator does not always advance over them. The sequence required to trigger this is not trivial. I think it requires that a zero-length iovec be followed by a non-zero-length iovec which causes a pagefault in the atomic usercopy. This causes the writev code to drop back into single-segment copy mode, which then tries to copy the 0 bytes of the zero-length iovec; a zero length copy looks like a failure though, so it loops. Put a test into iov_iter_advance to catch zero-length iovecs. We could just put the test in the fallback path, but I feel it is more robust to skip over zero-length iovecs throughout the code (iovec iterator may be used in filesystems too, so it should be robust). Signed-off-by: Nick Piggin <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> 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 struct svc_xprt *svc_rdma_create(struct svc_serv *serv, struct net *net, struct sockaddr *sa, int salen, int flags) { struct rdma_cm_id *listen_id; struct svcxprt_rdma *cma_xprt; int ret; dprintk("svcrdma: Creating RDMA socket\n"); if ((sa->sa_family != AF_INET) && (sa->sa_family != AF_INET6)) { dprintk("svcrdma: Address family %d is not supported.\n", sa->sa_family); return ERR_PTR(-EAFNOSUPPORT); } cma_xprt = rdma_create_xprt(serv, 1); if (!cma_xprt) return ERR_PTR(-ENOMEM); listen_id = rdma_create_id(&init_net, rdma_listen_handler, cma_xprt, RDMA_PS_TCP, IB_QPT_RC); if (IS_ERR(listen_id)) { ret = PTR_ERR(listen_id); dprintk("svcrdma: rdma_create_id failed = %d\n", ret); goto err0; } /* Allow both IPv4 and IPv6 sockets to bind a single port * at the same time. */ #if IS_ENABLED(CONFIG_IPV6) ret = rdma_set_afonly(listen_id, 1); if (ret) { dprintk("svcrdma: rdma_set_afonly failed = %d\n", ret); goto err1; } #endif ret = rdma_bind_addr(listen_id, sa); if (ret) { dprintk("svcrdma: rdma_bind_addr failed = %d\n", ret); goto err1; } cma_xprt->sc_cm_id = listen_id; ret = rdma_listen(listen_id, RPCRDMA_LISTEN_BACKLOG); if (ret) { dprintk("svcrdma: rdma_listen failed = %d\n", ret); goto err1; } /* * We need to use the address from the cm_id in case the * caller specified 0 for the port number. */ sa = (struct sockaddr *)&cma_xprt->sc_cm_id->route.addr.src_addr; svc_xprt_set_local(&cma_xprt->sc_xprt, sa, salen); return &cma_xprt->sc_xprt; err1: rdma_destroy_id(listen_id); err0: kfree(cma_xprt); return ERR_PTR(ret); } 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 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* SegmentInfo::GetWritingAppAsUTF8() const { return m_pWritingAppAsUTF8; } 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: Vector<CSPHeaderAndType> ContentSecurityPolicy::Headers() const { Vector<CSPHeaderAndType> headers; headers.ReserveInitialCapacity(policies_.size()); for (const auto& policy : policies_) { headers.UncheckedAppend( CSPHeaderAndType(policy->Header(), policy->HeaderType())); } return headers; } Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener Spec PR: https://github.com/w3c/webappsec-csp/pull/358 Bug: 905301, 894228, 836148 Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a Reviewed-on: https://chromium-review.googlesource.com/c/1314633 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#610850} 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 TouchEventHandler::handleTouchPoint(Platform::TouchPoint& point, unsigned modifiers) { m_webPage->m_inputHandler->setInputModeEnabled(); bool shiftActive = modifiers & KEYMOD_SHIFT; bool altActive = modifiers & KEYMOD_ALT; bool ctrlActive = modifiers & KEYMOD_CTRL; switch (point.m_state) { case Platform::TouchPoint::TouchPressed: { m_webPage->m_inputHandler->clearDidSpellCheckState(); if (!m_lastFatFingersResult.isValid()) doFatFingers(point); Element* elementUnderFatFinger = m_lastFatFingersResult.nodeAsElementIfApplicable(); if (m_lastFatFingersResult.isTextInput()) { elementUnderFatFinger = m_lastFatFingersResult.nodeAsElementIfApplicable(FatFingersResult::ShadowContentNotAllowed, true /* shouldUseRootEditableElement */); m_shouldRequestSpellCheckOptions = m_webPage->m_inputHandler->shouldRequestSpellCheckingOptionsForPoint(point.m_pos, elementUnderFatFinger, m_spellCheckOptionRequest); } handleFatFingerPressed(shiftActive, altActive, ctrlActive); break; } case Platform::TouchPoint::TouchReleased: { if (!m_shouldRequestSpellCheckOptions) m_webPage->m_inputHandler->processPendingKeyboardVisibilityChange(); if (m_webPage->m_inputHandler->isInputMode()) m_webPage->m_inputHandler->notifyClientOfKeyboardVisibilityChange(true); m_webPage->m_tapHighlight->hide(); IntPoint adjustedPoint = m_webPage->mapFromContentsToViewport(m_lastFatFingersResult.adjustedPosition()); PlatformMouseEvent mouseEvent(adjustedPoint, m_lastScreenPoint, PlatformEvent::MouseReleased, 1, LeftButton, shiftActive, ctrlActive, altActive, TouchScreen); m_webPage->handleMouseEvent(mouseEvent); if (m_shouldRequestSpellCheckOptions) { IntPoint pixelPositionRelativeToViewport = m_webPage->mapToTransformed(adjustedPoint); IntSize screenOffset(m_lastScreenPoint - pixelPositionRelativeToViewport); m_webPage->m_inputHandler->requestSpellingCheckingOptions(m_spellCheckOptionRequest, screenOffset); m_shouldRequestSpellCheckOptions = false; } m_lastFatFingersResult.reset(); // Reset the fat finger result as its no longer valid when a user's finger is not on the screen. break; } case Platform::TouchPoint::TouchMoved: { m_webPage->m_inputHandler->clearDidSpellCheckState(); PlatformMouseEvent mouseEvent(point.m_pos, m_lastScreenPoint, PlatformEvent::MouseMoved, 1, LeftButton, shiftActive, ctrlActive, altActive, TouchScreen); m_lastScreenPoint = point.m_screenPos; m_webPage->handleMouseEvent(mouseEvent); break; } default: break; } } 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: int SeekHead::GetCount() const { return m_entry_count; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: static void rtsp_cmd_options(HTTPContext *c, const char *url) { /* rtsp_reply_header(c, RTSP_STATUS_OK); */ avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK"); avio_printf(c->pb, "CSeq: %d\r\n", c->seq); avio_printf(c->pb, "Public: %s\r\n", "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE"); avio_printf(c->pb, "\r\n"); } Commit Message: ffserver: Check chunk size Fixes out of array access Fixes: poc_ffserver.py Found-by: Paul Cher <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> 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 BrowserPluginGuest::SetCompositingBufferData(int gpu_process_id, uint32 client_id, uint32 context_id, uint32 texture_id_0, uint32 texture_id_1, uint32 sync_point) { if (texture_id_0 == 0) { DCHECK(texture_id_1 == 0); return; } DCHECK(texture_id_1 != 0); DCHECK(texture_id_0 != texture_id_1); surface_handle_ = gfx::GLSurfaceHandle(gfx::kNullPluginWindow, true); surface_handle_.parent_gpu_process_id = gpu_process_id; surface_handle_.parent_client_id = client_id; surface_handle_.parent_context_id = context_id; surface_handle_.parent_texture_id[0] = texture_id_0; surface_handle_.parent_texture_id[1] = texture_id_1; surface_handle_.sync_point = sync_point; } 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:
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 *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loaddr, Sdb *sdb) { if (!buf || !sz || sz == UT64_MAX) { return NULL; } RBuffer *tbuf = r_buf_new (); r_buf_set_bytes (tbuf, buf, sz); struct r_bin_bflt_obj *res = r_bin_bflt_new_buf (tbuf); r_buf_free (tbuf); return res ? res : NULL; } Commit Message: Fix #6829 oob write because of using wrong struct CWE ID: CWE-119 Target: 1 Example 2: Code: void HTMLInputElement::stepDown(int n, ExceptionState& exception_state) { input_type_->StepUp(-1.0 * n, exception_state); } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#542517} 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: l2tp_msgtype_print(netdissect_options *ndo, const u_char *dat) { const uint16_t *ptr = (const uint16_t *)dat; ND_PRINT((ndo, "%s", tok2str(l2tp_msgtype2str, "MSGTYPE-#%u", EXTRACT_16BITS(ptr)))); } Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file 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: IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_hdr(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; UWORD16 u2_height; UWORD16 u2_width; if (impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != SEQUENCE_HEADER_CODE) { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND; } impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u2_width = impeg2d_bit_stream_get(ps_stream,12); u2_height = impeg2d_bit_stream_get(ps_stream,12); if ((u2_width != ps_dec->u2_horizontal_size) || (u2_height != ps_dec->u2_vertical_size)) { if (0 == ps_dec->u2_header_done) { /* This is the first time we are reading the resolution */ ps_dec->u2_horizontal_size = u2_width; ps_dec->u2_vertical_size = u2_height; if (0 == ps_dec->u4_frm_buf_stride) { ps_dec->u4_frm_buf_stride = (UWORD32) (u2_width); } } else { if((u2_width > ps_dec->u2_create_max_width) || (u2_height > ps_dec->u2_create_max_height)) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS; ps_dec->u2_reinit_max_height = u2_height; ps_dec->u2_reinit_max_width = u2_width; return e_error; } else { /* The resolution has changed */ return (IMPEG2D_ERROR_CODES_T)IVD_RES_CHANGED; } } } if((ps_dec->u2_horizontal_size > ps_dec->u2_create_max_width) || (ps_dec->u2_vertical_size > ps_dec->u2_create_max_height)) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS; return SET_IVD_FATAL_ERROR(e_error); } /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* aspect_ratio_info (4 bits) */ /*------------------------------------------------------------------------*/ ps_dec->u2_aspect_ratio_info = impeg2d_bit_stream_get(ps_stream,4); /*------------------------------------------------------------------------*/ /* Frame rate code(4 bits) */ /*------------------------------------------------------------------------*/ ps_dec->u2_frame_rate_code = impeg2d_bit_stream_get(ps_stream,4); if (ps_dec->u2_frame_rate_code > MPEG2_MAX_FRAME_RATE_CODE) { return IMPEG2D_FRM_HDR_DECODE_ERR; } /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* bit_rate_value (18 bits) */ /*------------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,18); GET_MARKER_BIT(ps_dec,ps_stream); /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* vbv_buffer_size_value(10 bits), constrained_parameter_flag (1 bit) */ /*------------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,11); /*------------------------------------------------------------------------*/ /* Quantization matrix for the intra blocks */ /*------------------------------------------------------------------------*/ if(impeg2d_bit_stream_get_bit(ps_stream) == 1) { UWORD16 i; for(i = 0; i < NUM_PELS_IN_BLOCK; i++) { ps_dec->au1_intra_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8); } } else { memcpy(ps_dec->au1_intra_quant_matrix,gau1_impeg2_intra_quant_matrix_default, NUM_PELS_IN_BLOCK); } /*------------------------------------------------------------------------*/ /* Quantization matrix for the inter blocks */ /*------------------------------------------------------------------------*/ if(impeg2d_bit_stream_get_bit(ps_stream) == 1) { UWORD16 i; for(i = 0; i < NUM_PELS_IN_BLOCK; i++) { ps_dec->au1_inter_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8); } } else { memcpy(ps_dec->au1_inter_quant_matrix,gau1_impeg2_inter_quant_matrix_default, NUM_PELS_IN_BLOCK); } impeg2d_next_start_code(ps_dec); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; } Commit Message: Fix in handling header decode errors If header decode was unsuccessful, do not try decoding a frame Also, initialize pic_wd, pic_ht for reinitialization when decoder is created with smaller dimensions Bug: 28886651 Bug: 35219737 Change-Id: I8c06d9052910e47fce2e6fe25ad318d4c83d2c50 (cherry picked from commit 2b9fa9ace2dbedfbac026fc9b6ab6cdac7f68c27) (cherry picked from commit c2395cd7cc0c286a66de674032dd2ed26500aef4) CWE ID: CWE-119 Target: 1 Example 2: Code: GF_Err rtp_hnti_Read(GF_Box *s, GF_BitStream *bs) { u32 length; GF_RTPBox *ptr = (GF_RTPBox *)s; if (ptr == NULL) return GF_BAD_PARAM; ISOM_DECREASE_SIZE(ptr, 4) ptr->subType = gf_bs_read_u32(bs); length = (u32) (ptr->size); ptr->sdpText = (char*)gf_malloc(sizeof(char) * (length+1)); if (!ptr->sdpText) return GF_OUT_OF_MEM; gf_bs_read_data(bs, ptr->sdpText, length); ptr->sdpText[length] = 0; return GF_OK; } 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: static PHP_FUNCTION(xmlwriter_output_memory) { php_xmlwriter_flush(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } Commit Message: 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 ocfs2_dio_get_block(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { struct ocfs2_super *osb = OCFS2_SB(inode->i_sb); struct ocfs2_inode_info *oi = OCFS2_I(inode); struct ocfs2_write_ctxt *wc; struct ocfs2_write_cluster_desc *desc = NULL; struct ocfs2_dio_write_ctxt *dwc = NULL; struct buffer_head *di_bh = NULL; u64 p_blkno; loff_t pos = iblock << inode->i_sb->s_blocksize_bits; unsigned len, total_len = bh_result->b_size; int ret = 0, first_get_block = 0; len = osb->s_clustersize - (pos & (osb->s_clustersize - 1)); len = min(total_len, len); mlog(0, "get block of %lu at %llu:%u req %u\n", inode->i_ino, pos, len, total_len); /* * Because we need to change file size in ocfs2_dio_end_io_write(), or * we may need to add it to orphan dir. So can not fall to fast path * while file size will be changed. */ if (pos + total_len <= i_size_read(inode)) { down_read(&oi->ip_alloc_sem); /* This is the fast path for re-write. */ ret = ocfs2_get_block(inode, iblock, bh_result, create); up_read(&oi->ip_alloc_sem); if (buffer_mapped(bh_result) && !buffer_new(bh_result) && ret == 0) goto out; /* Clear state set by ocfs2_get_block. */ bh_result->b_state = 0; } dwc = ocfs2_dio_alloc_write_ctx(bh_result, &first_get_block); if (unlikely(dwc == NULL)) { ret = -ENOMEM; mlog_errno(ret); goto out; } if (ocfs2_clusters_for_bytes(inode->i_sb, pos + total_len) > ocfs2_clusters_for_bytes(inode->i_sb, i_size_read(inode)) && !dwc->dw_orphaned) { /* * when we are going to alloc extents beyond file size, add the * inode to orphan dir, so we can recall those spaces when * system crashed during write. */ ret = ocfs2_add_inode_to_orphan(osb, inode); if (ret < 0) { mlog_errno(ret); goto out; } dwc->dw_orphaned = 1; } ret = ocfs2_inode_lock(inode, &di_bh, 1); if (ret) { mlog_errno(ret); goto out; } down_write(&oi->ip_alloc_sem); if (first_get_block) { if (ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb))) ret = ocfs2_zero_tail(inode, di_bh, pos); else ret = ocfs2_expand_nonsparse_inode(inode, di_bh, pos, total_len, NULL); if (ret < 0) { mlog_errno(ret); goto unlock; } } ret = ocfs2_write_begin_nolock(inode->i_mapping, pos, len, OCFS2_WRITE_DIRECT, NULL, (void **)&wc, di_bh, NULL); if (ret) { mlog_errno(ret); goto unlock; } desc = &wc->w_desc[0]; p_blkno = ocfs2_clusters_to_blocks(inode->i_sb, desc->c_phys); BUG_ON(p_blkno == 0); p_blkno += iblock & (u64)(ocfs2_clusters_to_blocks(inode->i_sb, 1) - 1); map_bh(bh_result, inode->i_sb, p_blkno); bh_result->b_size = len; if (desc->c_needs_zero) set_buffer_new(bh_result); /* May sleep in end_io. It should not happen in a irq context. So defer * it to dio work queue. */ set_buffer_defer_completion(bh_result); if (!list_empty(&wc->w_unwritten_list)) { struct ocfs2_unwritten_extent *ue = NULL; ue = list_first_entry(&wc->w_unwritten_list, struct ocfs2_unwritten_extent, ue_node); BUG_ON(ue->ue_cpos != desc->c_cpos); /* The physical address may be 0, fill it. */ ue->ue_phys = desc->c_phys; list_splice_tail_init(&wc->w_unwritten_list, &dwc->dw_zero_list); dwc->dw_zero_count++; } ret = ocfs2_write_end_nolock(inode->i_mapping, pos, len, len, wc); BUG_ON(ret != len); ret = 0; unlock: up_write(&oi->ip_alloc_sem); ocfs2_inode_unlock(inode, 1); brelse(di_bh); out: if (ret < 0) ret = -EIO; return ret; } Commit Message: ocfs2: ip_alloc_sem should be taken in ocfs2_get_block() ip_alloc_sem should be taken in ocfs2_get_block() when reading file in DIRECT mode to prevent concurrent access to extent tree with ocfs2_dio_end_io_write(), which may cause BUGON in the following situation: read file 'A' end_io of writing file 'A' vfs_read __vfs_read ocfs2_file_read_iter generic_file_read_iter ocfs2_direct_IO __blockdev_direct_IO do_blockdev_direct_IO do_direct_IO get_more_blocks ocfs2_get_block ocfs2_extent_map_get_blocks ocfs2_get_clusters ocfs2_get_clusters_nocache() ocfs2_search_extent_list return the index of record which contains the v_cluster, that is v_cluster > rec[i]->e_cpos. ocfs2_dio_end_io ocfs2_dio_end_io_write down_write(&oi->ip_alloc_sem); ocfs2_mark_extent_written ocfs2_change_extent_flag ocfs2_split_extent ... --> modify the rec[i]->e_cpos, resulting in v_cluster < rec[i]->e_cpos. BUG_ON(v_cluster < le32_to_cpu(rec->e_cpos)) [[email protected]: v3] Link: http://lkml.kernel.org/r/[email protected] Link: http://lkml.kernel.org/r/[email protected] Fixes: c15471f79506 ("ocfs2: fix sparse file & data ordering issue in direct io") Signed-off-by: Alex Chen <[email protected]> Reviewed-by: Jun Piao <[email protected]> Reviewed-by: Joseph Qi <[email protected]> Reviewed-by: Gang He <[email protected]> Acked-by: Changwei Ge <[email protected]> Cc: Mark Fasheh <[email protected]> Cc: Joel Becker <[email protected]> Cc: Junxiao Bi <[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: static int fuse_copy_ioctl_iovec(struct fuse_conn *fc, struct iovec *dst, void *src, size_t transferred, unsigned count, bool is_compat) { unsigned i; struct fuse_ioctl_iovec *fiov = src; if (fc->minor < 16) { return fuse_copy_ioctl_iovec_old(dst, src, transferred, count, is_compat); } if (count * sizeof(struct fuse_ioctl_iovec) != transferred) return -EIO; for (i = 0; i < count; i++) { /* Did the server supply an inappropriate value? */ if (fiov[i].base != (unsigned long) fiov[i].base || fiov[i].len != (unsigned long) fiov[i].len) return -EIO; dst[i].iov_base = (void __user *) (unsigned long) fiov[i].base; dst[i].iov_len = (size_t) fiov[i].len; #ifdef CONFIG_COMPAT if (is_compat && (ptr_to_compat(dst[i].iov_base) != fiov[i].base || (compat_size_t) dst[i].iov_len != fiov[i].len)) return -EIO; #endif } return 0; } Commit Message: fuse: break infinite loop in fuse_fill_write_pages() I got a report about unkillable task eating CPU. Further investigation shows, that the problem is in the fuse_fill_write_pages() function. If iov's first segment has zero length, we get an infinite loop, because we never reach iov_iter_advance() call. Fix this by calling iov_iter_advance() before repeating an attempt to copy data from userspace. A similar problem is described in 124d3b7041f ("fix writev regression: pan hanging unkillable and un-straceable"). If zero-length segmend is followed by segment with invalid address, iov_iter_fault_in_readable() checks only first segment (zero-length), iov_iter_copy_from_user_atomic() skips it, fails at second and returns zero -> goto again without skipping zero-length segment. Patch calls iov_iter_advance() before goto again: we'll skip zero-length segment at second iteraction and iov_iter_fault_in_readable() will detect invalid address. Special thanks to Konstantin Khlebnikov, who helped a lot with the commit description. Cc: Andrew Morton <[email protected]> Cc: Maxim Patlasov <[email protected]> Cc: Konstantin Khlebnikov <[email protected]> Signed-off-by: Roman Gushchin <[email protected]> Signed-off-by: Miklos Szeredi <[email protected]> Fixes: ea9b9907b82a ("fuse: implement perform_write") Cc: <[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: void BluetoothDeviceChromeOS::RequestConfirmation( const dbus::ObjectPath& device_path, uint32 passkey, const ConfirmationCallback& callback) { DCHECK(agent_.get()); DCHECK(device_path == object_path_); VLOG(1) << object_path_.value() << ": RequestConfirmation: " << passkey; UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod", UMA_PAIRING_METHOD_CONFIRM_PASSKEY, UMA_PAIRING_METHOD_COUNT); DCHECK(pairing_delegate_); DCHECK(confirmation_callback_.is_null()); confirmation_callback_ = callback; pairing_delegate_->ConfirmPasskey(this, passkey); pairing_delegate_used_ = true; } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: 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 venc_dev::venc_output_log_buffers(const char *buffer_addr, int buffer_len) { if (!m_debug.outfile) { int size = 0; if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_MPEG4) { size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.m4v", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); } else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H264) { size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.264", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); } else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_HEVC) { size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%ld_%ld_%p.265", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); } else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H263) { size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.263", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); } else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_VP8) { size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.ivf", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); } if ((size > PROPERTY_VALUE_MAX) && (size < 0)) { DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d", m_debug.outfile_name, size); } m_debug.outfile = fopen(m_debug.outfile_name, "ab"); if (!m_debug.outfile) { DEBUG_PRINT_ERROR("Failed to open output file: %s for logging errno:%d", m_debug.outfile_name, errno); m_debug.outfile_name[0] = '\0'; return -1; } } if (m_debug.outfile && buffer_len) { DEBUG_PRINT_LOW("%s buffer_len:%d", __func__, buffer_len); fwrite(buffer_addr, buffer_len, 1, m_debug.outfile); } return 0; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers Heap pointers do not point to user virtual addresses in case of secure session. Set them to NULL and add checks to avoid accesing them Bug: 28815329 Bug: 28920116 Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26 CWE ID: CWE-200 Target: 1 Example 2: Code: const AtomicString& TextTrackCue::InterfaceName() const { return EventTargetNames::TextTrackCue; } Commit Message: Support negative timestamps of TextTrackCue Ensure proper behaviour for negative timestamps of TextTrackCue. 1. Cues with negative startTime should become active from 0s. 2. Cues with negative startTime and endTime should never be active. Bug: 314032 Change-Id: Ib53710e58be0be770c933ea8c3c4709a0e5dec0d Reviewed-on: https://chromium-review.googlesource.com/863270 Commit-Queue: srirama chandra sekhar <[email protected]> Reviewed-by: Fredrik Söderquist <[email protected]> Cr-Commit-Position: refs/heads/master@{#529012} 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 NetworkHandler::ClearBrowserCache( std::unique_ptr<ClearBrowserCacheCallback> callback) { if (!process_) { callback->sendFailure(Response::InternalError()); return; } content::BrowsingDataRemover* remover = content::BrowserContext::GetBrowsingDataRemover( process_->GetBrowserContext()); remover->RemoveAndReply( base::Time(), base::Time::Max(), content::BrowsingDataRemover::DATA_TYPE_CACHE, content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB, new DevtoolsClearCacheObserver(remover, std::move(callback))); } 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 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: IHEVCD_ERROR_T ihevcd_mv_buf_mgr_add_bufs(codec_t *ps_codec) { IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; WORD32 i; WORD32 max_dpb_size; WORD32 mv_bank_size_allocated; WORD32 pic_mv_bank_size; sps_t *ps_sps; UWORD8 *pu1_buf; mv_buf_t *ps_mv_buf; /* Initialize MV Bank buffer manager */ ps_sps = ps_codec->s_parse.ps_sps; /* Compute the number of MV Bank buffers needed */ max_dpb_size = ps_sps->ai1_sps_max_dec_pic_buffering[ps_sps->i1_sps_max_sub_layers - 1]; /* Allocate one extra MV Bank to handle current frame * In case of asynchronous parsing and processing, number of buffers should increase here * based on when parsing and processing threads are synchronized */ max_dpb_size++; pu1_buf = (UWORD8 *)ps_codec->pv_mv_bank_buf_base; ps_mv_buf = (mv_buf_t *)pu1_buf; pu1_buf += max_dpb_size * sizeof(mv_buf_t); ps_codec->ps_mv_buf = ps_mv_buf; mv_bank_size_allocated = ps_codec->i4_total_mv_bank_size - max_dpb_size * sizeof(mv_buf_t); /* Compute MV bank size per picture */ pic_mv_bank_size = ihevcd_get_pic_mv_bank_size(ALIGN64(ps_sps->i2_pic_width_in_luma_samples) * ALIGN64(ps_sps->i2_pic_height_in_luma_samples)); for(i = 0; i < max_dpb_size; i++) { WORD32 buf_ret; WORD32 num_pu; WORD32 num_ctb; WORD32 pic_size; pic_size = ALIGN64(ps_sps->i2_pic_width_in_luma_samples) * ALIGN64(ps_sps->i2_pic_height_in_luma_samples); num_pu = pic_size / (MIN_PU_SIZE * MIN_PU_SIZE); num_ctb = pic_size / (MIN_CTB_SIZE * MIN_CTB_SIZE); mv_bank_size_allocated -= pic_mv_bank_size; if(mv_bank_size_allocated < 0) { ps_codec->s_parse.i4_error_code = IHEVCD_INSUFFICIENT_MEM_MVBANK; return IHEVCD_INSUFFICIENT_MEM_MVBANK; } ps_mv_buf->pu4_pic_pu_idx = (UWORD32 *)pu1_buf; pu1_buf += (num_ctb + 1) * sizeof(WORD32); ps_mv_buf->pu1_pic_pu_map = pu1_buf; pu1_buf += num_pu; ps_mv_buf->pu1_pic_slice_map = (UWORD16 *)pu1_buf; pu1_buf += ALIGN4(num_ctb * sizeof(UWORD16)); ps_mv_buf->ps_pic_pu = (pu_t *)pu1_buf; pu1_buf += num_pu * sizeof(pu_t); buf_ret = ihevc_buf_mgr_add((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, ps_mv_buf, i); if(0 != buf_ret) { ps_codec->s_parse.i4_error_code = IHEVCD_BUF_MGR_ERROR; return IHEVCD_BUF_MGR_ERROR; } ps_mv_buf++; } return ret; } Commit Message: Check only allocated mv bufs for releasing from reference When checking mv bufs for releasing from reference, unallocated mv bufs were also checked. This issue was fixed by restricting the loop count to allocated number of mv bufs. Bug: 34896906 Bug: 34819017 Change-Id: If832f590b301f414d4cd5206414efc61a70c17cb (cherry picked from commit 23bfe3e06d53ea749073a5d7ceda84239742b2c2) CWE ID: Target: 1 Example 2: Code: filter_lookup(struct archive *_a, int n) { struct archive_write *a = (struct archive_write *)_a; struct archive_write_filter *f = a->filter_first; if (n == -1) return a->filter_last; if (n < 0) return NULL; while (n > 0 && f != NULL) { f = f->next_filter; --n; } return f; } Commit Message: Limit write requests to at most INT_MAX. This prevents a certain common programming error (passing -1 to write) from leading to other problems deeper in the library. 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: make_boot_catalog(struct archive_write *a) { struct iso9660 *iso9660 = a->format_data; unsigned char *block; unsigned char *p; uint16_t sum, *wp; block = wb_buffptr(a); memset(block, 0, LOGICAL_BLOCK_SIZE); p = block; /* * Validation Entry */ /* Header ID */ p[0] = 1; /* Platform ID */ p[1] = iso9660->el_torito.platform_id; /* Reserved */ p[2] = p[3] = 0; /* ID */ if (archive_strlen(&(iso9660->el_torito.id)) > 0) strncpy((char *)p+4, iso9660->el_torito.id.s, 23); p[27] = 0; /* Checksum */ p[28] = p[29] = 0; /* Key */ p[30] = 0x55; p[31] = 0xAA; sum = 0; wp = (uint16_t *)block; while (wp < (uint16_t *)&block[32]) sum += archive_le16dec(wp++); set_num_721(&block[28], (~sum) + 1); /* * Initial/Default Entry */ p = &block[32]; /* Boot Indicator */ p[0] = 0x88; /* Boot media type */ p[1] = iso9660->el_torito.media_type; /* Load Segment */ if (iso9660->el_torito.media_type == BOOT_MEDIA_NO_EMULATION) set_num_721(&p[2], iso9660->el_torito.boot_load_seg); else set_num_721(&p[2], 0); /* System Type */ p[4] = iso9660->el_torito.system_type; /* Unused */ p[5] = 0; /* Sector Count */ if (iso9660->el_torito.media_type == BOOT_MEDIA_NO_EMULATION) set_num_721(&p[6], iso9660->el_torito.boot_load_size); else set_num_721(&p[6], 1); /* Load RBA */ set_num_731(&p[8], iso9660->el_torito.boot->file->content.location); /* Unused */ memset(&p[12], 0, 20); return (wb_consume(a, LOGICAL_BLOCK_SIZE)); } Commit Message: Issue 711: Be more careful about verifying filename lengths when writing ISO9660 archives * Don't cast size_t to int, since this can lead to overflow on machines where sizeof(int) < sizeof(size_t) * Check a + b > limit by writing it as a > limit || b > limit || a + b > limit to avoid problems when a + b wraps around. 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: get_cdtext_generic (void *p_user_data) { generic_img_private_t *p_env = p_user_data; uint8_t *p_cdtext_data = NULL; size_t len; if (!p_env) return NULL; if (p_env->b_cdtext_error) return NULL; if (NULL == p_env->cdtext) { p_cdtext_data = read_cdtext_generic (p_env); if (NULL != p_cdtext_data) { len = CDIO_MMC_GET_LEN16(p_cdtext_data)-2; p_env->cdtext = cdtext_init(); if(len <= 0 || 0 != cdtext_data_init (p_env->cdtext, &p_cdtext_data[4], len)) { p_env->b_cdtext_error = true; cdtext_destroy (p_env->cdtext); free(p_env->cdtext); p_env->cdtext = NULL; } } free(p_cdtext_data); } } Commit Message: CWE ID: CWE-415 Target: 1 Example 2: Code: xsltNewKeyDef(const xmlChar *name, const xmlChar *nameURI) { xsltKeyDefPtr cur; cur = (xsltKeyDefPtr) xmlMalloc(sizeof(xsltKeyDef)); if (cur == NULL) { xsltTransformError(NULL, NULL, NULL, "xsltNewKeyDef : malloc failed\n"); return(NULL); } memset(cur, 0, sizeof(xsltKeyDef)); if (name != NULL) cur->name = xmlStrdup(name); if (nameURI != NULL) cur->nameURI = xmlStrdup(nameURI); cur->nsList = NULL; return(cur); } 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: void big_key_describe(const struct key *key, struct seq_file *m) { size_t datalen = (size_t)key->payload.data[big_key_len]; seq_puts(m, key->description); if (key_is_instantiated(key)) seq_printf(m, ": %zu [%s]", datalen, datalen > BIG_KEY_FILE_THRESHOLD ? "file" : "buff"); } 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 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 StoreNewGroup() { PushNextTask(base::BindOnce(&AppCacheStorageImplTest::Verify_StoreNewGroup, base::Unretained(this))); group_ = new AppCacheGroup(storage(), kManifestUrl, storage()->NewGroupId()); cache_ = new AppCache(storage(), storage()->NewCacheId()); cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::EXPLICIT, 1, kDefaultEntrySize)); mock_quota_manager_proxy_->mock_manager_->async_ = true; storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate()); EXPECT_FALSE(delegate()->stored_group_success_); } 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 Target: 1 Example 2: Code: void WebRuntimeFeatures::EnableReducedReferrerGranularity(bool enable) { RuntimeEnabledFeatures::SetReducedReferrerGranularityEnabled(enable); } Commit Message: Remove RequireCSSExtensionForFile runtime enabled flag. The feature has long since been stable (since M64) and doesn't seem to be a need for this flag. BUG=788936 Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0 Reviewed-on: https://chromium-review.googlesource.com/c/1324143 Reviewed-by: Mike West <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Dave Tapuska <[email protected]> Cr-Commit-Position: refs/heads/master@{#607329} 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 ebt_unregister_table(struct net *net, struct ebt_table *table, const struct nf_hook_ops *ops) { if (ops) nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks)); __ebt_unregister_table(net, table); } Commit Message: netfilter: ebtables: CONFIG_COMPAT: don't trust userland offsets We need to make sure the offsets are not out of range of the total size. Also check that they are in ascending order. The WARN_ON triggered by syzkaller (it sets panic_on_warn) is changed to also bail out, no point in continuing parsing. Briefly tested with simple ruleset of -A INPUT --limit 1/s' --log plus jump to custom chains using 32bit ebtables binary. Reported-by: <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> 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: TEE_Result tee_mmu_check_access_rights(const struct user_ta_ctx *utc, uint32_t flags, uaddr_t uaddr, size_t len) { uaddr_t a; size_t addr_incr = MIN(CORE_MMU_USER_CODE_SIZE, CORE_MMU_USER_PARAM_SIZE); if (ADD_OVERFLOW(uaddr, len, &a)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_NONSECURE) && (flags & TEE_MEMORY_ACCESS_SECURE)) return TEE_ERROR_ACCESS_DENIED; /* * Rely on TA private memory test to check if address range is private * to TA or not. */ if (!(flags & TEE_MEMORY_ACCESS_ANY_OWNER) && !tee_mmu_is_vbuf_inside_ta_private(utc, (void *)uaddr, len)) return TEE_ERROR_ACCESS_DENIED; for (a = uaddr; a < (uaddr + len); a += addr_incr) { uint32_t attr; TEE_Result res; res = tee_mmu_user_va2pa_attr(utc, (void *)a, NULL, &attr); if (res != TEE_SUCCESS) return res; if ((flags & TEE_MEMORY_ACCESS_NONSECURE) && (attr & TEE_MATTR_SECURE)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_SECURE) && !(attr & TEE_MATTR_SECURE)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_WRITE) && !(attr & TEE_MATTR_UW)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_READ) && !(attr & TEE_MATTR_UR)) return TEE_ERROR_ACCESS_DENIED; } return TEE_SUCCESS; } Commit Message: core: tee_mmu_check_access_rights() check all pages Prior to this patch tee_mmu_check_access_rights() checks an address in each page of a supplied range. If both the start and length of that range is unaligned the last page in the range is sometimes not checked. With this patch the first address of each page in the range is checked to simplify the logic of checking each page and the range and also to cover the last page under all circumstances. Fixes: OP-TEE-2018-0005: "tee_mmu_check_access_rights does not check final page of TA buffer" Signed-off-by: Jens Wiklander <[email protected]> Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8) Reviewed-by: Joakim Bech <[email protected]> Reported-by: Riscure <[email protected]> Reported-by: Alyssa Milburn <[email protected]> Acked-by: Etienne Carriere <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: int DiskCacheBackendTest::GetRoundedSize(int exact_size) { if (!simple_cache_mode_) return exact_size; return (exact_size + 255) & 0xFFFFFF00; } Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem Thanks to nedwilliamson@ (on gmail) for an alternative perspective plus a reduction to make fixing this much easier. Bug: 826626, 518908, 537063, 802886 Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f Reviewed-on: https://chromium-review.googlesource.com/985052 Reviewed-by: Matt Menke <[email protected]> Commit-Queue: Maks Orlovich <[email protected]> Cr-Commit-Position: refs/heads/master@{#547103} 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: PHP_METHOD(Phar, webPhar) { zval *mimeoverride = NULL, *rewrite = NULL; char *alias = NULL, *error, *index_php = NULL, *f404 = NULL, *ru = NULL; int alias_len = 0, ret, f404_len = 0, free_pathinfo = 0, ru_len = 0; char *fname, *path_info, *mime_type = NULL, *entry, *pt; const char *basename; int fname_len, entry_len, code, index_php_len = 0, not_cgi; phar_archive_data *phar = NULL; phar_entry_info *info = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!s!saz", &alias, &alias_len, &index_php, &index_php_len, &f404, &f404_len, &mimeoverride, &rewrite) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); fname = (char*)zend_get_executed_filename(TSRMLS_C); fname_len = strlen(fname); if (phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) != SUCCESS) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } return; } /* retrieve requested file within phar */ if (!(SG(request_info).request_method && SG(request_info).request_uri && (!strcmp(SG(request_info).request_method, "GET") || !strcmp(SG(request_info).request_method, "POST")))) { return; } #ifdef PHP_WIN32 fname = estrndup(fname, fname_len); phar_unixify_path_separators(fname, fname_len); #endif basename = zend_memrchr(fname, '/', fname_len); if (!basename) { basename = fname; } else { ++basename; } if ((strlen(sapi_module.name) == sizeof("cgi-fcgi")-1 && !strncmp(sapi_module.name, "cgi-fcgi", sizeof("cgi-fcgi")-1)) || (strlen(sapi_module.name) == sizeof("fpm-fcgi")-1 && !strncmp(sapi_module.name, "fpm-fcgi", sizeof("fpm-fcgi")-1)) || (strlen(sapi_module.name) == sizeof("cgi")-1 && !strncmp(sapi_module.name, "cgi", sizeof("cgi")-1))) { if (PG(http_globals)[TRACK_VARS_SERVER]) { HashTable *_server = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]); zval **z_script_name, **z_path_info; if (SUCCESS != zend_hash_find(_server, "SCRIPT_NAME", sizeof("SCRIPT_NAME"), (void**)&z_script_name) || IS_STRING != Z_TYPE_PP(z_script_name) || !strstr(Z_STRVAL_PP(z_script_name), basename)) { return; } if (SUCCESS == zend_hash_find(_server, "PATH_INFO", sizeof("PATH_INFO"), (void**)&z_path_info) && IS_STRING == Z_TYPE_PP(z_path_info)) { entry_len = Z_STRLEN_PP(z_path_info); entry = estrndup(Z_STRVAL_PP(z_path_info), entry_len); path_info = emalloc(Z_STRLEN_PP(z_script_name) + entry_len + 1); memcpy(path_info, Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name)); memcpy(path_info + Z_STRLEN_PP(z_script_name), entry, entry_len + 1); free_pathinfo = 1; } else { entry_len = 0; entry = estrndup("", 0); path_info = Z_STRVAL_PP(z_script_name); } pt = estrndup(Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name)); } else { char *testit; testit = sapi_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1 TSRMLS_CC); if (!(pt = strstr(testit, basename))) { efree(testit); return; } path_info = sapi_getenv("PATH_INFO", sizeof("PATH_INFO")-1 TSRMLS_CC); if (path_info) { entry = path_info; entry_len = strlen(entry); spprintf(&path_info, 0, "%s%s", testit, path_info); free_pathinfo = 1; } else { path_info = testit; free_pathinfo = 1; entry = estrndup("", 0); entry_len = 0; } pt = estrndup(testit, (pt - testit) + (fname_len - (basename - fname))); } not_cgi = 0; } else { path_info = SG(request_info).request_uri; if (!(pt = strstr(path_info, basename))) { /* this can happen with rewrite rules - and we have no idea what to do then, so return */ return; } entry_len = strlen(path_info); entry_len -= (pt - path_info) + (fname_len - (basename - fname)); entry = estrndup(pt + (fname_len - (basename - fname)), entry_len); pt = estrndup(path_info, (pt - path_info) + (fname_len - (basename - fname))); not_cgi = 1; } if (rewrite) { zend_fcall_info fci; zend_fcall_info_cache fcc; zval *params, *retval_ptr, **zp[1]; MAKE_STD_ZVAL(params); ZVAL_STRINGL(params, entry, entry_len, 1); zp[0] = &params; #if PHP_VERSION_ID < 50300 if (FAILURE == zend_fcall_info_init(rewrite, &fci, &fcc TSRMLS_CC)) { #else if (FAILURE == zend_fcall_info_init(rewrite, 0, &fci, &fcc, NULL, NULL TSRMLS_CC)) { #endif zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: invalid rewrite callback"); if (free_pathinfo) { efree(path_info); } return; } fci.param_count = 1; fci.params = zp; #if PHP_VERSION_ID < 50300 ++(params->refcount); #else Z_ADDREF_P(params); #endif fci.retval_ptr_ptr = &retval_ptr; if (FAILURE == zend_call_function(&fci, &fcc TSRMLS_CC)) { if (!EG(exception)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: failed to call rewrite callback"); } if (free_pathinfo) { efree(path_info); } return; } if (!fci.retval_ptr_ptr || !retval_ptr) { if (free_pathinfo) { efree(path_info); } zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false"); return; } switch (Z_TYPE_P(retval_ptr)) { #if PHP_VERSION_ID >= 60000 case IS_UNICODE: zval_unicode_to_string(retval_ptr TSRMLS_CC); /* break intentionally omitted */ #endif case IS_STRING: efree(entry); if (fci.retval_ptr_ptr != &retval_ptr) { entry = estrndup(Z_STRVAL_PP(fci.retval_ptr_ptr), Z_STRLEN_PP(fci.retval_ptr_ptr)); entry_len = Z_STRLEN_PP(fci.retval_ptr_ptr); } else { entry = Z_STRVAL_P(retval_ptr); entry_len = Z_STRLEN_P(retval_ptr); } break; case IS_BOOL: phar_do_403(entry, entry_len TSRMLS_CC); if (free_pathinfo) { efree(path_info); } zend_bailout(); return; default: efree(retval_ptr); if (free_pathinfo) { efree(path_info); } zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false"); return; } } if (entry_len) { phar_postprocess_ru_web(fname, fname_len, &entry, &entry_len, &ru, &ru_len TSRMLS_CC); } if (!entry_len || (entry_len == 1 && entry[0] == '/')) { efree(entry); /* direct request */ if (index_php_len) { entry = index_php; entry_len = index_php_len; if (entry[0] != '/') { spprintf(&entry, 0, "/%s", index_php); ++entry_len; } } else { /* assume "index.php" is starting point */ entry = estrndup("/index.php", sizeof("/index.php")); entry_len = sizeof("/index.php")-1; } if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) || (info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) { phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC); if (free_pathinfo) { efree(path_info); } zend_bailout(); } else { char *tmp = NULL, sa = '\0'; sapi_header_line ctr = {0}; ctr.response_code = 301; ctr.line_len = sizeof("HTTP/1.1 301 Moved Permanently")-1; ctr.line = "HTTP/1.1 301 Moved Permanently"; sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); if (not_cgi) { tmp = strstr(path_info, basename) + fname_len; sa = *tmp; *tmp = '\0'; } ctr.response_code = 0; if (path_info[strlen(path_info)-1] == '/') { ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry + 1); } else { ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry); } if (not_cgi) { *tmp = sa; } if (free_pathinfo) { efree(path_info); } sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); sapi_send_headers(TSRMLS_C); efree(ctr.line); zend_bailout(); } } if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) || (info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) { phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC); #ifdef PHP_WIN32 efree(fname); #endif zend_bailout(); } if (mimeoverride && zend_hash_num_elements(Z_ARRVAL_P(mimeoverride))) { const char *ext = zend_memrchr(entry, '.', entry_len); zval **val; if (ext) { ++ext; if (SUCCESS == zend_hash_find(Z_ARRVAL_P(mimeoverride), ext, strlen(ext)+1, (void **) &val)) { switch (Z_TYPE_PP(val)) { case IS_LONG: if (Z_LVAL_PP(val) == PHAR_MIME_PHP || Z_LVAL_PP(val) == PHAR_MIME_PHPS) { mime_type = ""; code = Z_LVAL_PP(val); } else { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used, only Phar::PHP, Phar::PHPS and a mime type string are allowed"); #ifdef PHP_WIN32 efree(fname); #endif RETURN_FALSE; } break; case IS_STRING: mime_type = Z_STRVAL_PP(val); code = PHAR_MIME_OTHER; break; default: zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used (not a string or int), only Phar::PHP, Phar::PHPS and a mime type string are allowed"); #ifdef PHP_WIN32 efree(fname); #endif RETURN_FALSE; } } } } if (!mime_type) { code = phar_file_type(&PHAR_G(mime_types), entry, &mime_type TSRMLS_CC); } ret = phar_file_action(phar, info, mime_type, code, entry, entry_len, fname, pt, ru, ru_len TSRMLS_CC); } /* }}} */ /* {{{ proto void Phar::mungServer(array munglist) * Defines a list of up to 4 $_SERVER variables that should be modified for execution * to mask the presence of the phar archive. This should be used in conjunction with * Phar::webPhar(), and has no effect otherwise * SCRIPT_NAME, PHP_SELF, REQUEST_URI and SCRIPT_FILENAME */ PHP_METHOD(Phar, mungServer) { zval *mungvalues; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &mungvalues) == FAILURE) { return; } if (!zend_hash_num_elements(Z_ARRVAL_P(mungvalues))) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "No values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME"); return; } if (zend_hash_num_elements(Z_ARRVAL_P(mungvalues)) > 4) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Too many values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME"); return; } phar_request_initialize(TSRMLS_C); for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(mungvalues)); SUCCESS == zend_hash_has_more_elements(Z_ARRVAL_P(mungvalues)); zend_hash_move_forward(Z_ARRVAL_P(mungvalues))) { zval **data = NULL; if (SUCCESS != zend_hash_get_current_data(Z_ARRVAL_P(mungvalues), (void **) &data)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "unable to retrieve array value in Phar::mungServer()"); return; } if (Z_TYPE_PP(data) != IS_STRING) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Non-string value passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME"); return; } if (Z_STRLEN_PP(data) == sizeof("PHP_SELF")-1 && !strncmp(Z_STRVAL_PP(data), "PHP_SELF", sizeof("PHP_SELF")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_PHP_SELF; } if (Z_STRLEN_PP(data) == sizeof("REQUEST_URI")-1) { if (!strncmp(Z_STRVAL_PP(data), "REQUEST_URI", sizeof("REQUEST_URI")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_REQUEST_URI; } if (!strncmp(Z_STRVAL_PP(data), "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_NAME; } } if (Z_STRLEN_PP(data) == sizeof("SCRIPT_FILENAME")-1 && !strncmp(Z_STRVAL_PP(data), "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1)) { PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_FILENAME; } } } /* }}} */ /* {{{ proto void Phar::interceptFileFuncs() * instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions * and return stat on files within the phar for relative paths * * Once called, this cannot be reversed, and continue until the end of the request. * * This allows legacy scripts to be pharred unmodified */ PHP_METHOD(Phar, interceptFileFuncs) { if (zend_parse_parameters_none() == FAILURE) { return; } phar_intercept_functions(TSRMLS_C); } /* }}} */ /* {{{ proto array Phar::createDefaultStub([string indexfile[, string webindexfile]]) * Return a stub that can be used to run a phar-based archive without the phar extension * indexfile is the CLI startup filename, which defaults to "index.php", webindexfile * is the web startup filename, and also defaults to "index.php" */ PHP_METHOD(Phar, createDefaultStub) { char *index = NULL, *webindex = NULL, *stub, *error; int index_len = 0, webindex_len = 0; size_t stub_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ss", &index, &index_len, &webindex, &webindex_len) == FAILURE) { return; } stub = phar_create_default_stub(index, webindex, &stub_len, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); return; } RETURN_STRINGL(stub, stub_len, 0); } /* }}} */ /* {{{ proto mixed Phar::mapPhar([string alias, [int dataoffset]]) * Reads the currently executed file (a phar) and registers its manifest */ PHP_METHOD(Phar, mapPhar) { char *alias = NULL, *error; int alias_len = 0; long dataoffset = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!l", &alias, &alias_len, &dataoffset) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); RETVAL_BOOL(phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } /* }}} */ /* {{{ proto mixed Phar::loadPhar(string filename [, string alias]) * Loads any phar archive with an alias */ PHP_METHOD(Phar, loadPhar) { char *fname, *alias = NULL, *error; int fname_len, alias_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error TSRMLS_CC) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } /* }}} */ /* {{{ proto string Phar::apiVersion() * Returns the api version */ PHP_METHOD(Phar, apiVersion) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRINGL(PHP_PHAR_API_VERSION, sizeof(PHP_PHAR_API_VERSION)-1, 1); } /* }}}*/ /* {{{ proto bool Phar::canCompress([int method]) * Returns whether phar extension supports compression using zlib/bzip2 */ PHP_METHOD(Phar, canCompress) { long method = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &method) == FAILURE) { return; } phar_request_initialize(TSRMLS_C); switch (method) { case PHAR_ENT_COMPRESSED_GZ: if (PHAR_G(has_zlib)) { RETURN_TRUE; } else { RETURN_FALSE; } case PHAR_ENT_COMPRESSED_BZ2: if (PHAR_G(has_bz2)) { RETURN_TRUE; } else { RETURN_FALSE; } default: if (PHAR_G(has_zlib) || PHAR_G(has_bz2)) { RETURN_TRUE; } else { RETURN_FALSE; } } } /* }}} */ /* {{{ proto bool Phar::canWrite() * Returns whether phar extension supports writing and creating phars */ PHP_METHOD(Phar, canWrite) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(!PHAR_G(readonly)); } /* }}} */ /* {{{ proto bool Phar::isValidPharFilename(string filename[, bool executable = true]) * Returns whether the given filename is a valid phar filename */ PHP_METHOD(Phar, isValidPharFilename) { char *fname; const char *ext_str; int fname_len, ext_len, is_executable; zend_bool executable = 1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &fname, &fname_len, &executable) == FAILURE) { return; } is_executable = executable; RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1 TSRMLS_CC) == SUCCESS); } /* }}} */ #if HAVE_SPL /** * from spl_directory */ static void phar_spl_foreign_dtor(spl_filesystem_object *object TSRMLS_DC) /* {{{ */ { phar_archive_data *phar = (phar_archive_data *) object->oth; if (!phar->is_persistent) { phar_archive_delref(phar TSRMLS_CC); } object->oth = NULL; } /* }}} */ /** * from spl_directory */ static void phar_spl_foreign_clone(spl_filesystem_object *src, spl_filesystem_object *dst TSRMLS_DC) /* {{{ */ { phar_archive_data *phar_data = (phar_archive_data *) dst->oth; if (!phar_data->is_persistent) { ++(phar_data->refcount); } } /* }}} */ static spl_other_handler phar_spl_foreign_handler = { phar_spl_foreign_dtor, phar_spl_foreign_clone }; #endif /* HAVE_SPL */ /* {{{ proto void Phar::__construct(string fname [, int flags [, string alias]]) * Construct a Phar archive object * * proto void PharData::__construct(string fname [[, int flags [, string alias]], int file format = Phar::TAR]) * Construct a PharData archive object * * This function is used as the constructor for both the Phar and PharData * classes, hence the two prototypes above. */ PHP_METHOD(Phar, __construct) { #if !HAVE_SPL zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Cannot instantiate Phar object without SPL extension"); #else char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname; int fname_len, alias_len = 0, arch_len, entry_len, is_data; #if PHP_VERSION_ID < 50300 long flags = 0; #else long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS; #endif long format = 0; phar_archive_object *phar_obj; phar_archive_data *phar_data; zval *zobj = getThis(), arg1, arg2; phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC); if (is_data) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) { return; } } if (phar_obj->arc.archive) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice"); return; } save_fname = fname; if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) { /* use arch (the basename for the archive) for fname instead of fname */ /* this allows support for RecursiveDirectoryIterator of subdirectories */ #ifdef PHP_WIN32 phar_unixify_path_separators(arch, arch_len); #endif fname = arch; fname_len = arch_len; #ifdef PHP_WIN32 } else { arch = estrndup(fname, fname_len); arch_len = fname_len; fname = arch; phar_unixify_path_separators(arch, arch_len); #endif } if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) { if (fname == arch && fname != save_fname) { efree(arch); fname = save_fname; } if (entry) { efree(entry); } if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "%s", error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Phar creation or opening failed"); } return; } if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) { phar_data->is_zip = 1; phar_data->is_tar = 0; } if (fname == arch) { efree(arch); fname = save_fname; } if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) { if (is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "PharData class can only be used for non-executable tar and zip archives"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Phar class can only be used for executable tar and zip archives"); } efree(entry); return; } is_data = phar_data->is_data; if (!phar_data->is_persistent) { ++(phar_data->refcount); } phar_obj->arc.archive = phar_data; phar_obj->spl.oth_handler = &phar_spl_foreign_handler; if (entry) { fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry); efree(entry); } else { fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname); } INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, fname, fname_len, 0); INIT_PZVAL(&arg2); ZVAL_LONG(&arg2, flags); zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj), &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2); if (!phar_data->is_persistent) { phar_obj->arc.archive->is_data = is_data; } else if (!EG(exception)) { /* register this guy so we can modify if necessary */ zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL); } phar_obj->spl.info_class = phar_ce_entry; efree(fname); #endif /* HAVE_SPL */ } /* }}} */ /* {{{ proto array Phar::getSupportedSignatures() * Return array of supported signature types */ PHP_METHOD(Phar, getSupportedSignatures) { if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); add_next_index_stringl(return_value, "MD5", 3, 1); add_next_index_stringl(return_value, "SHA-1", 5, 1); #ifdef PHAR_HASH_OK add_next_index_stringl(return_value, "SHA-256", 7, 1); add_next_index_stringl(return_value, "SHA-512", 7, 1); #endif #if PHAR_HAVE_OPENSSL add_next_index_stringl(return_value, "OpenSSL", 7, 1); #else if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) { add_next_index_stringl(return_value, "OpenSSL", 7, 1); } #endif } /* }}} */ /* {{{ proto array Phar::getSupportedCompression() * Return array of supported comparession algorithms */ PHP_METHOD(Phar, getSupportedCompression) { if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); phar_request_initialize(TSRMLS_C); if (PHAR_G(has_zlib)) { add_next_index_stringl(return_value, "GZ", 2, 1); } if (PHAR_G(has_bz2)) { add_next_index_stringl(return_value, "BZIP2", 5, 1); } } /* }}} */ /* {{{ proto array Phar::unlinkArchive(string archive) * Completely remove a phar archive from memory and disk */ PHP_METHOD(Phar, unlinkArchive) { char *fname, *error, *zname, *arch, *entry; int fname_len, zname_len, arch_len, entry_len; phar_archive_data *phar; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (!fname_len) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"\""); return; } if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error TSRMLS_CC)) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\": %s", fname, error); efree(error); } else { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\"", fname); } return; } zname = (char*)zend_get_executed_filename(TSRMLS_C); zname_len = strlen(zname); if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) { if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" cannot be unlinked from within itself", fname); efree(arch); efree(entry); return; } efree(arch); efree(entry); } if (phar->is_persistent) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname); return; } if (phar->refcount) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname); return; } fname = estrndup(phar->fname, phar->fname_len); /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar_archive_delref(phar TSRMLS_CC); unlink(fname); efree(fname); RETURN_TRUE; } /* }}} */ #if HAVE_SPL #define PHAR_ARCHIVE_OBJECT() \ phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ if (!phar_obj->arc.archive) { \ zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \ "Cannot call method on an uninitialized Phar object"); \ return; \ } /* {{{ proto void Phar::__destruct() * if persistent, remove from the cache */ PHP_METHOD(Phar, __destruct) { phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (phar_obj->arc.archive && phar_obj->arc.archive->is_persistent) { zend_hash_del(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive)); } } /* }}} */ struct _phar_t { phar_archive_object *p; zend_class_entry *c; char *b; uint l; zval *ret; int count; php_stream *fp; }; static int phar_build(zend_object_iterator *iter, void *puser TSRMLS_DC) /* {{{ */ { zval **value; zend_uchar key_type; zend_bool close_fp = 1; ulong int_key; struct _phar_t *p_obj = (struct _phar_t*) puser; uint str_key_len, base_len = p_obj->l, fname_len; phar_entry_data *data; php_stream *fp; size_t contents_len; char *fname, *error = NULL, *base = p_obj->b, *opened, *save = NULL, *temp = NULL; phar_zstr key; char *str_key; zend_class_entry *ce = p_obj->c; phar_archive_object *phar_obj = p_obj->p; char *str = "[stream]"; iter->funcs->get_current_data(iter, &value TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (!value) { /* failure in get_current_data */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned no value", ce->name); return ZEND_HASH_APPLY_STOP; } switch (Z_TYPE_PP(value)) { #if PHP_VERSION_ID >= 60000 case IS_UNICODE: zval_unicode_to_string(*(value) TSRMLS_CC); /* break intentionally omitted */ #endif case IS_STRING: break; case IS_RESOURCE: php_stream_from_zval_no_verify(fp, value); if (!fp) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returned an invalid stream handle", ce->name); return ZEND_HASH_APPLY_STOP; } if (iter->funcs->get_current_key) { key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (key_type == HASH_KEY_IS_LONG) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } if (key_type > 9) { /* IS_UNICODE == 10 */ #if PHP_VERSION_ID < 60000 /* this can never happen, but fixes a compile warning */ spprintf(&str_key, 0, "%s", key); #else spprintf(&str_key, 0, "%v", key); ezfree(key); #endif } else { PHAR_STR(key, str_key); } save = str_key; if (str_key[str_key_len - 1] == '\0') { str_key_len--; } } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } close_fp = 0; opened = (char *) estrndup(str, sizeof("[stream]") - 1); goto after_open_fp; case IS_OBJECT: if (instanceof_function(Z_OBJCE_PP(value), spl_ce_SplFileInfo TSRMLS_CC)) { char *test = NULL; zval dummy; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(*value TSRMLS_CC); if (!base_len) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returns an SplFileInfo object, so base directory must be specified", ce->name); return ZEND_HASH_APPLY_STOP; } switch (intern->type) { case SPL_FS_DIR: #if PHP_VERSION_ID >= 60000 test = spl_filesystem_object_get_path(intern, NULL, NULL TSRMLS_CC).s; #elif PHP_VERSION_ID >= 50300 test = spl_filesystem_object_get_path(intern, NULL TSRMLS_CC); #else test = intern->path; #endif fname_len = spprintf(&fname, 0, "%s%c%s", test, DEFAULT_SLASH, intern->u.dir.entry.d_name); php_stat(fname, fname_len, FS_IS_DIR, &dummy TSRMLS_CC); if (Z_BVAL(dummy)) { /* ignore directories */ efree(fname); return ZEND_HASH_APPLY_KEEP; } test = expand_filepath(fname, NULL TSRMLS_CC); efree(fname); if (test) { fname = test; fname_len = strlen(fname); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path"); return ZEND_HASH_APPLY_STOP; } save = fname; goto phar_spl_fileinfo; case SPL_FS_INFO: case SPL_FS_FILE: #if PHP_VERSION_ID >= 60000 if (intern->file_name_type == IS_UNICODE) { zval zv; INIT_ZVAL(zv); Z_UNIVAL(zv) = intern->file_name; Z_UNILEN(zv) = intern->file_name_len; Z_TYPE(zv) = IS_UNICODE; zval_copy_ctor(&zv); zval_unicode_to_string(&zv TSRMLS_CC); fname = expand_filepath(Z_STRVAL(zv), NULL TSRMLS_CC); ezfree(Z_UNIVAL(zv)); } else { fname = expand_filepath(intern->file_name.s, NULL TSRMLS_CC); } #else fname = expand_filepath(intern->file_name, NULL TSRMLS_CC); #endif if (!fname) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path"); return ZEND_HASH_APPLY_STOP; } fname_len = strlen(fname); save = fname; goto phar_spl_fileinfo; } } /* fall-through */ default: zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid value (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } fname = Z_STRVAL_PP(value); fname_len = Z_STRLEN_PP(value); phar_spl_fileinfo: if (base_len) { temp = expand_filepath(base, NULL TSRMLS_CC); if (!temp) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path"); if (save) { efree(save); } return ZEND_HASH_APPLY_STOP; } base = temp; base_len = strlen(base); if (strstr(fname, base)) { str_key_len = fname_len - base_len; if (str_key_len <= 0) { if (save) { efree(save); efree(temp); } return ZEND_HASH_APPLY_KEEP; } str_key = fname + base_len; if (*str_key == '/' || *str_key == '\\') { str_key++; str_key_len--; } } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that is not in the base directory \"%s\"", ce->name, fname, base); if (save) { efree(save); efree(temp); } return ZEND_HASH_APPLY_STOP; } } else { if (iter->funcs->get_current_key) { key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (key_type == HASH_KEY_IS_LONG) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } if (key_type > 9) { /* IS_UNICODE == 10 */ #if PHP_VERSION_ID < 60000 /* this can never happen, but fixes a compile warning */ spprintf(&str_key, 0, "%s", key); #else spprintf(&str_key, 0, "%v", key); ezfree(key); #endif } else { PHAR_STR(key, str_key); } save = str_key; if (str_key[str_key_len - 1] == '\0') str_key_len--; } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name); return ZEND_HASH_APPLY_STOP; } } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that safe mode prevents opening", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } #endif if (php_check_open_basedir(fname TSRMLS_CC)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that open_basedir prevents opening", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } /* try to open source file, then create internal phar file and copy contents */ fp = php_stream_open_wrapper(fname, "rb", STREAM_MUST_SEEK|0, &opened); if (!fp) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a file that could not be opened \"%s\"", ce->name, fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } after_open_fp: if (str_key_len >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) { /* silently skip any files that would be added to the magic .phar directory */ if (save) { efree(save); } if (temp) { efree(temp); } if (opened) { efree(opened); } if (close_fp) { php_stream_close(fp); } return ZEND_HASH_APPLY_KEEP; } if (!(data = phar_get_or_create_entry_data(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, str_key, str_key_len, "w+b", 0, &error, 1 TSRMLS_CC))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s cannot be created: %s", str_key, error); efree(error); if (save) { efree(save); } if (opened) { efree(opened); } if (temp) { efree(temp); } if (close_fp) { php_stream_close(fp); } return ZEND_HASH_APPLY_STOP; } else { if (error) { efree(error); } /* convert to PHAR_UFP */ if (data->internal_file->fp_type == PHAR_MOD) { php_stream_close(data->internal_file->fp); } data->internal_file->fp = NULL; data->internal_file->fp_type = PHAR_UFP; data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp); data->fp = NULL; phar_stream_copy_to_stream(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len); data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize = php_stream_tell(p_obj->fp) - data->internal_file->offset; } if (close_fp) { php_stream_close(fp); } add_assoc_string(p_obj->ret, str_key, opened, 0); if (save) { efree(save); } if (temp) { efree(temp); } data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len; phar_entry_delref(data TSRMLS_CC); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* {{{ proto array Phar::buildFromDirectory(string base_dir[, string regex]) * Construct a phar archive from an existing directory, recursively. * Optional second parameter is a regular expression for filtering directory contents. * * Return value is an array mapping phar index to actual files added. */ PHP_METHOD(Phar, buildFromDirectory) { char *dir, *error, *regex = NULL; int dir_len, regex_len = 0; zend_bool apply_reg = 0; zval arg, arg2, *iter, *iteriter, *regexiter = NULL; struct _phar_t pass; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write to archive - write operations restricted by INI setting"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &dir, &dir_len, &regex, &regex_len) == FAILURE) { RETURN_FALSE; } MAKE_STD_ZVAL(iter); if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) { zval_ptr_dtor(&iter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname); RETURN_FALSE; } INIT_PZVAL(&arg); ZVAL_STRINGL(&arg, dir, dir_len, 0); INIT_PZVAL(&arg2); #if PHP_VERSION_ID < 50300 ZVAL_LONG(&arg2, 0); #else ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS); #endif zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator, &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2); if (EG(exception)) { zval_ptr_dtor(&iter); RETURN_FALSE; } MAKE_STD_ZVAL(iteriter); if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) { zval_ptr_dtor(&iter); zval_ptr_dtor(&iteriter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname); RETURN_FALSE; } zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator, &spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, iter); if (EG(exception)) { zval_ptr_dtor(&iter); zval_ptr_dtor(&iteriter); RETURN_FALSE; } zval_ptr_dtor(&iter); if (regex_len > 0) { apply_reg = 1; MAKE_STD_ZVAL(regexiter); if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) { zval_ptr_dtor(&iteriter); zval_dtor(regexiter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate regex iterator for %s", phar_obj->arc.archive->fname); RETURN_FALSE; } INIT_PZVAL(&arg2); ZVAL_STRINGL(&arg2, regex, regex_len, 0); zend_call_method_with_2_params(&regexiter, spl_ce_RegexIterator, &spl_ce_RegexIterator->constructor, "__construct", NULL, iteriter, &arg2); } array_init(return_value); pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter); pass.p = phar_obj; pass.b = dir; pass.l = dir_len; pass.count = 0; pass.ret = return_value; pass.fp = php_stream_fopen_tmpfile(); if (pass.fp == NULL) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" unable to create temporary file", phar_obj->arc.archive->fname); return; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } php_stream_close(pass.fp); zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } phar_obj->arc.archive->ufp = pass.fp; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } else { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } php_stream_close(pass.fp); } } /* }}} */ /* {{{ proto array Phar::buildFromIterator(Iterator iter[, string base_directory]) * Construct a phar archive from an iterator. The iterator must return a series of strings * that are full paths to files that should be added to the phar. The iterator key should * be the path that the file will have within the phar archive. * * If base directory is specified, then the key will be ignored, and instead the portion of * the current value minus the base directory will be used * * Returned is an array mapping phar index to actual file added */ PHP_METHOD(Phar, buildFromIterator) { zval *obj; char *error; uint base_len = 0; char *base = NULL; struct _phar_t pass; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot write out phar archive, phar is read-only"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|s", &obj, zend_ce_traversable, &base, &base_len) == FAILURE) { RETURN_FALSE; } if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname); return; } array_init(return_value); pass.c = Z_OBJCE_P(obj); pass.p = phar_obj; pass.b = base; pass.l = base_len; pass.ret = return_value; pass.count = 0; pass.fp = php_stream_fopen_tmpfile(); if (pass.fp == NULL) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\": unable to create temporary file", phar_obj->arc.archive->fname); return; } if (SUCCESS == spl_iterator_apply(obj, (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) { phar_obj->arc.archive->ufp = pass.fp; phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error); efree(error); } } else { php_stream_close(pass.fp); } } /* }}} */ /* {{{ proto int Phar::count() * Returns the number of entries in the Phar archive */ PHP_METHOD(Phar, count) { PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest)); } /* }}} */ /* {{{ proto bool Phar::isFileFormat(int format) * Returns true if the phar archive is based on the tar/zip/phar file format depending * on whether Phar::TAR, Phar::ZIP or Phar::PHAR was passed in */ PHP_METHOD(Phar, isFileFormat) { long type; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &type) == FAILURE) { RETURN_FALSE; } switch (type) { case PHAR_FORMAT_TAR: RETURN_BOOL(phar_obj->arc.archive->is_tar); case PHAR_FORMAT_ZIP: RETURN_BOOL(phar_obj->arc.archive->is_zip); case PHAR_FORMAT_PHAR: RETURN_BOOL(!phar_obj->arc.archive->is_tar && !phar_obj->arc.archive->is_zip); default: zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown file format specified"); } } /* }}} */ static int phar_copy_file_contents(phar_entry_info *entry, php_stream *fp TSRMLS_DC) /* {{{ */ { char *error; off_t offset; phar_entry_info *link; if (FAILURE == phar_open_entry_fp(entry, &error, 1 TSRMLS_CC)) { if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents: %s", entry->phar->fname, entry->filename, error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents", entry->phar->fname, entry->filename); } return FAILURE; } /* copy old contents in entirety */ phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC); offset = php_stream_tell(fp); link = phar_get_link_source(entry TSRMLS_CC); if (!link) { link = entry; } if (SUCCESS != phar_stream_copy_to_stream(phar_get_efp(link, 0 TSRMLS_CC), fp, link->uncompressed_filesize, NULL)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot convert phar archive \"%s\", unable to copy entry \"%s\" contents", entry->phar->fname, entry->filename); return FAILURE; } if (entry->fp_type == PHAR_MOD) { /* save for potential restore on error */ entry->cfp = entry->fp; entry->fp = NULL; } /* set new location of file contents */ entry->fp_type = PHAR_FP; entry->offset = offset; return SUCCESS; } /* }}} */ static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) /* {{{ */ { const char *oldname = NULL; char *oldpath = NULL; char *basename = NULL, *basepath = NULL; char *newname = NULL, *newpath = NULL; zval *ret, arg1; zend_class_entry *ce; char *error; const char *pcr_error; int ext_len = ext ? strlen(ext) : 0; int oldname_len; phar_archive_data **pphar = NULL; php_stream_statbuf ssb; if (!ext) { if (phar->is_zip) { if (phar->is_data) { ext = "zip"; } else { ext = "phar.zip"; } } else if (phar->is_tar) { switch (phar->flags) { case PHAR_FILE_COMPRESSED_GZ: if (phar->is_data) { ext = "tar.gz"; } else { ext = "phar.tar.gz"; } break; case PHAR_FILE_COMPRESSED_BZ2: if (phar->is_data) { ext = "tar.bz2"; } else { ext = "phar.tar.bz2"; } break; default: if (phar->is_data) { ext = "tar"; } else { ext = "phar.tar"; } } } else { switch (phar->flags) { case PHAR_FILE_COMPRESSED_GZ: ext = "phar.gz"; break; case PHAR_FILE_COMPRESSED_BZ2: ext = "phar.bz2"; break; default: ext = "phar"; } } } else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) { if (phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar converted from \"%s\" has invalid extension %s", phar->fname, ext); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar converted from \"%s\" has invalid extension %s", phar->fname, ext); } return NULL; } if (ext[0] == '.') { ++ext; } oldpath = estrndup(phar->fname, phar->fname_len); oldname = zend_memrchr(phar->fname, '/', phar->fname_len); ++oldname; oldname_len = strlen(oldname); basename = estrndup(oldname, oldname_len); spprintf(&newname, 0, "%s.%s", strtok(basename, "."), ext); efree(basename); basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len)); phar->fname_len = spprintf(&newpath, 0, "%s%s", basepath, newname); phar->fname = newpath; phar->ext = newpath + phar->fname_len - strlen(ext) - 1; efree(basepath); efree(newname); if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, new phar name is in phar.cache_list", phar->fname); return NULL; } if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) { if ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) { if (!zend_hash_num_elements(&phar->manifest)) { (*pphar)->is_tar = phar->is_tar; (*pphar)->is_zip = phar->is_zip; (*pphar)->is_data = phar->is_data; (*pphar)->flags = phar->flags; (*pphar)->fp = phar->fp; phar->fp = NULL; phar_destroy_phar_data(phar TSRMLS_CC); phar = *pphar; phar->refcount++; newpath = oldpath; goto its_ok; } } efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, a phar with that name already exists", phar->fname); return NULL; } its_ok: if (SUCCESS == php_stream_stat_path(newpath, &ssb)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" exists and must be unlinked prior to conversion", newpath); efree(oldpath); return NULL; } if (!phar->is_data) { if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" has invalid extension %s", phar->fname, ext); return NULL; } if (phar->alias) { if (phar->is_temporary_alias) { phar->alias = NULL; phar->alias_len = 0; } else { phar->alias = estrndup(newpath, strlen(newpath)); phar->alias_len = strlen(newpath); phar->is_temporary_alias = 1; zend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL); } } } else { if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar \"%s\" has invalid extension %s", phar->fname, ext); return NULL; } phar->alias = NULL; phar->alias_len = 0; } if ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars", phar->fname); return NULL; } phar_flush(phar, 0, 0, 1, &error TSRMLS_CC); if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error); efree(error); efree(oldpath); return NULL; } efree(oldpath); if (phar->is_data) { ce = phar_ce_data; } else { ce = phar_ce_archive; } MAKE_STD_ZVAL(ret); if (SUCCESS != object_init_ex(ret, ce)) { zval_dtor(ret); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate phar object when converting archive \"%s\"", phar->fname); return NULL; } INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0); zend_call_method_with_1_params(&ret, ce, &ce->constructor, "__construct", NULL, &arg1); return ret; } /* }}} */ static zval *phar_convert_to_other(phar_archive_data *source, int convert, char *ext, php_uint32 flags TSRMLS_DC) /* {{{ */ { phar_archive_data *phar; phar_entry_info *entry, newentry; zval *ret; /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar = (phar_archive_data *) ecalloc(1, sizeof(phar_archive_data)); /* set whole-archive compression and type from parameter */ phar->flags = flags; phar->is_data = source->is_data; switch (convert) { case PHAR_FORMAT_TAR: phar->is_tar = 1; break; case PHAR_FORMAT_ZIP: phar->is_zip = 1; break; default: phar->is_data = 0; break; } zend_hash_init(&(phar->manifest), sizeof(phar_entry_info), zend_get_hash_value, destroy_phar_manifest_entry, 0); zend_hash_init(&phar->mounted_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); zend_hash_init(&phar->virtual_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); phar->fp = php_stream_fopen_tmpfile(); if (phar->fp == NULL) { zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "unable to create temporary file"); return NULL; } phar->fname = source->fname; phar->fname_len = source->fname_len; phar->is_temporary_alias = source->is_temporary_alias; phar->alias = source->alias; if (source->metadata) { zval *t; t = source->metadata; ALLOC_ZVAL(phar->metadata); *phar->metadata = *t; zval_copy_ctor(phar->metadata); #if PHP_VERSION_ID < 50300 phar->metadata->refcount = 1; #else Z_SET_REFCOUNT_P(phar->metadata, 1); #endif phar->metadata_len = 0; } /* first copy each file's uncompressed contents to a temporary file and set per-file flags */ for (zend_hash_internal_pointer_reset(&source->manifest); SUCCESS == zend_hash_has_more_elements(&source->manifest); zend_hash_move_forward(&source->manifest)) { if (FAILURE == zend_hash_get_current_data(&source->manifest, (void **) &entry)) { zend_hash_destroy(&(phar->manifest)); php_stream_close(phar->fp); efree(phar); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Cannot convert phar archive \"%s\"", source->fname); return NULL; } newentry = *entry; if (newentry.link) { newentry.link = estrdup(newentry.link); goto no_copy; } if (newentry.tmp) { newentry.tmp = estrdup(newentry.tmp); goto no_copy; } newentry.metadata_str.c = 0; if (FAILURE == phar_copy_file_contents(&newentry, phar->fp TSRMLS_CC)) { zend_hash_destroy(&(phar->manifest)); php_stream_close(phar->fp); efree(phar); /* exception already thrown */ return NULL; } no_copy: newentry.filename = estrndup(newentry.filename, newentry.filename_len); if (newentry.metadata) { zval *t; t = newentry.metadata; ALLOC_ZVAL(newentry.metadata); *newentry.metadata = *t; zval_copy_ctor(newentry.metadata); #if PHP_VERSION_ID < 50300 newentry.metadata->refcount = 1; #else Z_SET_REFCOUNT_P(newentry.metadata, 1); #endif newentry.metadata_str.c = NULL; newentry.metadata_str.len = 0; } newentry.is_zip = phar->is_zip; newentry.is_tar = phar->is_tar; if (newentry.is_tar) { newentry.tar_type = (entry->is_dir ? TAR_DIR : TAR_FILE); } newentry.is_modified = 1; newentry.phar = phar; newentry.old_flags = newentry.flags & ~PHAR_ENT_COMPRESSION_MASK; /* remove compression from old_flags */ phar_set_inode(&newentry TSRMLS_CC); zend_hash_add(&(phar->manifest), newentry.filename, newentry.filename_len, (void*)&newentry, sizeof(phar_entry_info), NULL); phar_add_virtual_dirs(phar, newentry.filename, newentry.filename_len TSRMLS_CC); } if ((ret = phar_rename_archive(phar, ext, 0 TSRMLS_CC))) { return ret; } else { zend_hash_destroy(&(phar->manifest)); zend_hash_destroy(&(phar->mounted_dirs)); zend_hash_destroy(&(phar->virtual_dirs)); php_stream_close(phar->fp); efree(phar->fname); efree(phar); return NULL; /* }}} */ 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: void LogoService::GetLogo(LogoCallbacks callbacks) { if (!template_url_service_) { RunCallbacksWithDisabled(std::move(callbacks)); return; } const TemplateURL* template_url = template_url_service_->GetDefaultSearchProvider(); if (!template_url) { RunCallbacksWithDisabled(std::move(callbacks)); return; } const base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); GURL logo_url; if (command_line->HasSwitch(switches::kSearchProviderLogoURL)) { logo_url = GURL( command_line->GetSwitchValueASCII(switches::kSearchProviderLogoURL)); } else { #if defined(OS_ANDROID) logo_url = template_url->logo_url(); #endif } GURL base_url; GURL doodle_url; const bool is_google = template_url->url_ref().HasGoogleBaseURLs( template_url_service_->search_terms_data()); if (is_google) { base_url = GURL(template_url_service_->search_terms_data().GoogleBaseURLValue()); doodle_url = search_provider_logos::GetGoogleDoodleURL(base_url); } else if (base::FeatureList::IsEnabled(features::kThirdPartyDoodles)) { if (command_line->HasSwitch(switches::kThirdPartyDoodleURL)) { doodle_url = GURL( command_line->GetSwitchValueASCII(switches::kThirdPartyDoodleURL)); } else { std::string override_url = base::GetFieldTrialParamValueByFeature( features::kThirdPartyDoodles, features::kThirdPartyDoodlesOverrideUrlParam); if (!override_url.empty()) { doodle_url = GURL(override_url); } else { doodle_url = template_url->doodle_url(); } } base_url = doodle_url.GetOrigin(); } if (!logo_url.is_valid() && !doodle_url.is_valid()) { RunCallbacksWithDisabled(std::move(callbacks)); return; } const bool use_fixed_logo = !doodle_url.is_valid(); if (!logo_tracker_) { std::unique_ptr<LogoCache> logo_cache = std::move(logo_cache_for_test_); if (!logo_cache) { logo_cache = std::make_unique<LogoCache>(cache_directory_); } std::unique_ptr<base::Clock> clock = std::move(clock_for_test_); if (!clock) { clock = std::make_unique<base::DefaultClock>(); } logo_tracker_ = std::make_unique<LogoTracker>( request_context_getter_, std::make_unique<LogoDelegateImpl>(std::move(image_decoder_)), std::move(logo_cache), std::move(clock)); } if (use_fixed_logo) { logo_tracker_->SetServerAPI( logo_url, base::Bind(&search_provider_logos::ParseFixedLogoResponse), base::Bind(&search_provider_logos::UseFixedLogoUrl)); } else if (is_google) { logo_tracker_->SetServerAPI( doodle_url, search_provider_logos::GetGoogleParseLogoResponseCallback(base_url), search_provider_logos::GetGoogleAppendQueryparamsCallback( use_gray_background_)); } else { logo_tracker_->SetServerAPI( doodle_url, base::Bind(&search_provider_logos::GoogleNewParseLogoResponse, base_url), base::Bind(&search_provider_logos::GoogleNewAppendQueryparamsToLogoURL, use_gray_background_)); } logo_tracker_->GetLogo(std::move(callbacks)); } Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <[email protected]> Reviewed-by: Marc Treib <[email protected]> Commit-Queue: Chris Pickel <[email protected]> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119 Target: 1 Example 2: Code: const GURL& previous_url() { return previous_url_; } Commit Message: Prevent renderer initiated back navigation to cancel a browser one. Renderer initiated back/forward navigations must not be able to cancel ongoing browser initiated navigation if they are not user initiated. Note: 'normal' renderer initiated navigation uses the FrameHost::BeginNavigation() path. A code similar to this patch is done in NavigatorImpl::OnBeginNavigation(). Test: ----- Added: NavigationBrowserTest. * HistoryBackInBeforeUnload * HistoryBackInBeforeUnloadAfterSetTimeout * HistoryBackCancelPendingNavigationNoUserGesture * HistoryBackCancelPendingNavigationUserGesture Fixed: * (WPT) .../the-history-interface/traverse_the_history_2.html * (WPT) .../the-history-interface/traverse_the_history_3.html * (WPT) .../the-history-interface/traverse_the_history_4.html * (WPT) .../the-history-interface/traverse_the_history_5.html Bug: 879965 Change-Id: I1a9bfaaea1ffc219e6c32f6e676b660e746c578c Reviewed-on: https://chromium-review.googlesource.com/1209744 Commit-Queue: Arthur Sonzogni <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Mustaq Ahmed <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Reviewed-by: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#592823} 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: my_object_many_uppercase (MyObject *obj, const char * const *in, char ***out, GError **error) { int len; int i; len = g_strv_length ((char**) in); *out = g_new0 (char *, len + 1); for (i = 0; i < len; i++) { (*out)[i] = g_ascii_strup (in[i], -1); } (*out)[i] = NULL; return TRUE; } Commit Message: 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: void FragmentPaintPropertyTreeBuilder::UpdateOutOfFlowContext() { if (!object_.IsBoxModelObject() && !properties_) return; if (object_.IsLayoutBlock()) context_.paint_offset_for_float = context_.current.paint_offset; if (object_.CanContainAbsolutePositionObjects()) { context_.absolute_position = context_.current; } if (object_.IsLayoutView()) { const auto* initial_fixed_transform = context_.fixed_position.transform; const auto* initial_fixed_scroll = context_.fixed_position.scroll; context_.fixed_position = context_.current; context_.fixed_position.fixed_position_children_fixed_to_root = true; context_.fixed_position.transform = initial_fixed_transform; context_.fixed_position.scroll = initial_fixed_scroll; } else if (object_.CanContainFixedPositionObjects()) { context_.fixed_position = context_.current; context_.fixed_position.fixed_position_children_fixed_to_root = false; } else if (properties_ && properties_->CssClip()) { auto* css_clip = properties_->CssClip(); if (context_.fixed_position.clip == css_clip->Parent()) { context_.fixed_position.clip = css_clip; } else { if (NeedsPaintPropertyUpdate()) { OnUpdate(properties_->UpdateCssClipFixedPosition( context_.fixed_position.clip, ClipPaintPropertyNode::State{css_clip->LocalTransformSpace(), css_clip->ClipRect()})); } if (properties_->CssClipFixedPosition()) context_.fixed_position.clip = properties_->CssClipFixedPosition(); return; } } if (NeedsPaintPropertyUpdate() && properties_) OnClear(properties_->ClearCssClipFixedPosition()); } 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: Target: 1 Example 2: Code: static void clean_module_classes(int module_number TSRMLS_DC) /* {{{ */ { zend_hash_apply_with_argument(EG(class_table), (apply_func_arg_t) clean_module_class, (void *) &module_number TSRMLS_CC); } /* }}} */ 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 ChromeExtensionsDispatcherDelegate::RegisterNativeHandlers( extensions::Dispatcher* dispatcher, extensions::ModuleSystem* module_system, extensions::ScriptContext* context) { module_system->RegisterNativeHandler( "app", std::unique_ptr<NativeHandler>( new extensions::AppBindings(dispatcher, context))); module_system->RegisterNativeHandler( "sync_file_system", std::unique_ptr<NativeHandler>( new extensions::SyncFileSystemCustomBindings(context))); module_system->RegisterNativeHandler( "file_browser_handler", std::unique_ptr<NativeHandler>( new extensions::FileBrowserHandlerCustomBindings(context))); module_system->RegisterNativeHandler( "file_manager_private", std::unique_ptr<NativeHandler>( new extensions::FileManagerPrivateCustomBindings(context))); module_system->RegisterNativeHandler( "notifications_private", std::unique_ptr<NativeHandler>( new extensions::NotificationsNativeHandler(context))); module_system->RegisterNativeHandler( "mediaGalleries", std::unique_ptr<NativeHandler>( new extensions::MediaGalleriesCustomBindings(context))); module_system->RegisterNativeHandler( "page_capture", std::unique_ptr<NativeHandler>( new extensions::PageCaptureCustomBindings(context))); module_system->RegisterNativeHandler( "platform_keys_natives", std::unique_ptr<NativeHandler>( new extensions::PlatformKeysNatives(context))); module_system->RegisterNativeHandler( "tabs", std::unique_ptr<NativeHandler>( new extensions::TabsCustomBindings(context))); module_system->RegisterNativeHandler( "webstore", std::unique_ptr<NativeHandler>( new extensions::WebstoreBindings(context))); #if defined(ENABLE_WEBRTC) module_system->RegisterNativeHandler( "cast_streaming_natives", std::unique_ptr<NativeHandler>( new extensions::CastStreamingNativeHandler(context))); #endif module_system->RegisterNativeHandler( "automationInternal", std::unique_ptr<NativeHandler>( new extensions::AutomationInternalCustomBindings(context))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284 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: jp2_box_t *jp2_box_get(jas_stream_t *in) { jp2_box_t *box; jp2_boxinfo_t *boxinfo; jas_stream_t *tmpstream; uint_fast32_t len; uint_fast64_t extlen; bool dataflag; box = 0; tmpstream = 0; if (!(box = jas_malloc(sizeof(jp2_box_t)))) { goto error; } box->ops = &jp2_boxinfo_unk.ops; if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) { goto error; } boxinfo = jp2_boxinfolookup(box->type); box->info = boxinfo; box->ops = &boxinfo->ops; box->len = len; if (box->len == 1) { if (jp2_getuint64(in, &extlen)) { goto error; } if (extlen > 0xffffffffUL) { jas_eprintf("warning: cannot handle large 64-bit box length\n"); extlen = 0xffffffffUL; } box->len = extlen; box->datalen = extlen - JP2_BOX_HDRLEN(true); } else { box->datalen = box->len - JP2_BOX_HDRLEN(false); } if (box->len != 0 && box->len < 8) { goto error; } dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA)); if (dataflag) { if (!(tmpstream = jas_stream_memopen(0, 0))) { goto error; } if (jas_stream_copy(tmpstream, in, box->datalen)) { jas_eprintf("cannot copy box data\n"); goto error; } jas_stream_rewind(tmpstream); if (box->ops->getdata) { if ((*box->ops->getdata)(box, tmpstream)) { jas_eprintf("cannot parse box data\n"); goto error; } } jas_stream_close(tmpstream); } if (jas_getdbglevel() >= 1) { jp2_box_dump(box, stderr); } return box; error: if (box) { jp2_box_destroy(box); } if (tmpstream) { jas_stream_close(tmpstream); } return 0; } Commit Message: Fixed a bug that resulted in the destruction of JP2 box data that had never been constructed in the first place. CWE ID: CWE-476 Target: 1 Example 2: Code: static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last) { for(;;) { int n; if (f->eof) return 0; n = get8(f); if (n == 0x4f) { // page header candidate unsigned int retry_loc = stb_vorbis_get_file_offset(f); int i; if (retry_loc - 25 > f->stream_len) return 0; for (i=1; i < 4; ++i) if (get8(f) != ogg_page_header[i]) break; if (f->eof) return 0; if (i == 4) { uint8 header[27]; uint32 i, crc, goal, len; for (i=0; i < 4; ++i) header[i] = ogg_page_header[i]; for (; i < 27; ++i) header[i] = get8(f); if (f->eof) return 0; if (header[4] != 0) goto invalid; goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24); for (i=22; i < 26; ++i) header[i] = 0; crc = 0; for (i=0; i < 27; ++i) crc = crc32_update(crc, header[i]); len = 0; for (i=0; i < header[26]; ++i) { int s = get8(f); crc = crc32_update(crc, s); len += s; } if (len && f->eof) return 0; for (i=0; i < len; ++i) crc = crc32_update(crc, get8(f)); if (crc == goal) { if (end) *end = stb_vorbis_get_file_offset(f); if (last) { if (header[5] & 0x04) *last = 1; else *last = 0; } set_file_offset(f, retry_loc-1); return 1; } } invalid: set_file_offset(f, retry_loc); } } } Commit Message: fix unchecked length in stb_vorbis that could crash on corrupt/invalid files 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 SoundPool::doLoad(sp<Sample>& sample) { ALOGV("doLoad: loading sample sampleID=%d", sample->sampleID()); sample->startLoad(); mDecodeThread->loadSample(sample->sampleID()); } Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread Sample decoding still occurs in SoundPoolThread without holding the SoundPool lock. Bug: 25781119 Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8 CWE ID: CWE-264 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: PassOwnPtr<GraphicsContext> UpdateAtlas::beginPaintingOnAvailableBuffer(ShareableSurface::Handle& handle, const WebCore::IntSize& size, IntPoint& offset) { buildLayoutIfNeeded(); IntRect rect = m_areaAllocator->allocate(size); if (rect.isEmpty()) return PassOwnPtr<GraphicsContext>(); if (!m_surface->createHandle(handle)) return PassOwnPtr<WebCore::GraphicsContext>(); offset = rect.location(); OwnPtr<GraphicsContext> graphicsContext = m_surface->createGraphicsContext(rect); if (flags() & ShareableBitmap::SupportsAlpha) { graphicsContext->setCompositeOperation(CompositeCopy); graphicsContext->fillRect(IntRect(IntPoint::zero(), size), Color::transparent, ColorSpaceDeviceRGB); graphicsContext->setCompositeOperation(CompositeSourceOver); } return graphicsContext.release(); } 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 Target: 1 Example 2: Code: void UnloadController::TabAttachedImpl(content::WebContents* contents) { registrar_.Add( this, content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED, content::Source<content::WebContents>(contents)); } 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: void MediaRecorderHandler::Stop() { DCHECK(main_render_thread_checker_.CalledOnValidThread()); weak_factory_.InvalidateWeakPtrs(); recording_ = false; timeslice_ = TimeDelta::FromMilliseconds(0); video_recorders_.clear(); audio_recorders_.clear(); webm_muxer_.reset(); } Commit Message: Check context is attached before creating MediaRecorder Bug: 896736 Change-Id: I3ccfd2188fb15704af14c8af050e0a5667855d34 Reviewed-on: https://chromium-review.googlesource.com/c/1324231 Commit-Queue: Emircan Uysaler <[email protected]> Reviewed-by: Miguel Casas <[email protected]> Cr-Commit-Position: refs/heads/master@{#606242} 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 generic_new(struct nf_conn *ct, const struct sk_buff *skb, unsigned int dataoff, unsigned int *timeouts) { return true; } Commit Message: netfilter: conntrack: disable generic tracking for known protocols Given following iptables ruleset: -P FORWARD DROP -A FORWARD -m sctp --dport 9 -j ACCEPT -A FORWARD -p tcp --dport 80 -j ACCEPT -A FORWARD -p tcp -m conntrack -m state ESTABLISHED,RELATED -j ACCEPT One would assume that this allows SCTP on port 9 and TCP on port 80. Unfortunately, if the SCTP conntrack module is not loaded, this allows *all* SCTP communication, to pass though, i.e. -p sctp -j ACCEPT, which we think is a security issue. This is because on the first SCTP packet on port 9, we create a dummy "generic l4" conntrack entry without any port information (since conntrack doesn't know how to extract this information). All subsequent packets that are unknown will then be in established state since they will fallback to proto_generic and will match the 'generic' entry. Our originally proposed version [1] completely disabled generic protocol tracking, but Jozsef suggests to not track protocols for which a more suitable helper is available, hence we now mitigate the issue for in tree known ct protocol helpers only, so that at least NAT and direction information will still be preserved for others. [1] http://www.spinics.net/lists/netfilter-devel/msg33430.html Joint work with Daniel Borkmann. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Jozsef Kadlecsik <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-254 Target: 1 Example 2: Code: struct inode *new_inode(struct super_block *sb) { struct inode *inode; spin_lock_prefetch(&inode_sb_list_lock); inode = new_inode_pseudo(sb); if (inode) inode_sb_list_add(inode); 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: static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen) { struct page *pages[NFS4ACL_MAXPAGES] = {NULL, }; struct nfs_getaclargs args = { .fh = NFS_FH(inode), .acl_pages = pages, .acl_len = buflen, }; struct nfs_getaclres res = { .acl_len = buflen, }; void *resp_buf; struct rpc_message msg = { .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL], .rpc_argp = &args, .rpc_resp = &res, }; int ret = -ENOMEM, npages, i, acl_len = 0; npages = (buflen + PAGE_SIZE - 1) >> PAGE_SHIFT; /* As long as we're doing a round trip to the server anyway, * let's be prepared for a page of acl data. */ if (npages == 0) npages = 1; for (i = 0; i < npages; i++) { pages[i] = alloc_page(GFP_KERNEL); if (!pages[i]) goto out_free; } if (npages > 1) { /* for decoding across pages */ res.acl_scratch = alloc_page(GFP_KERNEL); if (!res.acl_scratch) goto out_free; } args.acl_len = npages * PAGE_SIZE; args.acl_pgbase = 0; /* Let decode_getfacl know not to fail if the ACL data is larger than * the page we send as a guess */ if (buf == NULL) res.acl_flags |= NFS4_ACL_LEN_REQUEST; resp_buf = page_address(pages[0]); dprintk("%s buf %p buflen %zu npages %d args.acl_len %zu\n", __func__, buf, buflen, npages, args.acl_len); ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode), &msg, &args.seq_args, &res.seq_res, 0); if (ret) goto out_free; acl_len = res.acl_len - res.acl_data_offset; if (acl_len > args.acl_len) nfs4_write_cached_acl(inode, NULL, acl_len); else nfs4_write_cached_acl(inode, resp_buf + res.acl_data_offset, acl_len); if (buf) { ret = -ERANGE; if (acl_len > buflen) goto out_free; _copy_from_pages(buf, pages, res.acl_data_offset, res.acl_len); } ret = acl_len; out_free: for (i = 0; i < npages; i++) if (pages[i]) __free_page(pages[i]); if (res.acl_scratch) __free_page(res.acl_scratch); return ret; } Commit Message: Fix length of buffer copied in __nfs4_get_acl_uncached _copy_from_pages() used to copy data from the temporary buffer to the user passed buffer is passed the wrong size parameter when copying data. res.acl_len contains both the bitmap and acl lenghts while acl_len contains the acl length after adjusting for the bitmap size. Signed-off-by: Sachin Prabhu <[email protected]> Signed-off-by: Trond Myklebust <[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: png_check_chunk_length(png_const_structrp png_ptr, const png_uint_32 length) { png_alloc_size_t limit = PNG_UINT_31_MAX; # ifdef PNG_SET_USER_LIMITS_SUPPORTED if (png_ptr->user_chunk_malloc_max > 0 && png_ptr->user_chunk_malloc_max < limit) limit = png_ptr->user_chunk_malloc_max; # elif PNG_USER_CHUNK_MALLOC_MAX > 0 if (PNG_USER_CHUNK_MALLOC_MAX < limit) limit = PNG_USER_CHUNK_MALLOC_MAX; # endif if (png_ptr->chunk_name == png_IDAT) { png_alloc_size_t idat_limit = PNG_UINT_31_MAX; size_t row_factor = (png_ptr->width * png_ptr->channels * (png_ptr->bit_depth > 8? 2: 1) + 1 + (png_ptr->interlaced? 6: 0)); if (png_ptr->height > PNG_UINT_32_MAX/row_factor) idat_limit=PNG_UINT_31_MAX; else idat_limit = png_ptr->height * row_factor; row_factor = row_factor > 32566? 32566 : row_factor; idat_limit += 6 + 5*(idat_limit/row_factor+1); /* zlib+deflate overhead */ idat_limit=idat_limit < PNG_UINT_31_MAX? idat_limit : PNG_UINT_31_MAX; limit = limit < idat_limit? idat_limit : limit; } if (length > limit) { png_debug2(0," length = %lu, limit = %lu", (unsigned long)length,(unsigned long)limit); png_chunk_error(png_ptr, "chunk data is too large"); } } Commit Message: [libpng16] Fix the calculation of row_factor in png_check_chunk_length (Bug report by Thuan Pham, SourceForge issue #278) CWE ID: CWE-190 Target: 1 Example 2: Code: aspath_cmp (const void *arg1, const void *arg2) { const struct assegment *seg1 = ((const struct aspath *)arg1)->segments; const struct assegment *seg2 = ((const struct aspath *)arg2)->segments; while (seg1 || seg2) { int i; if ((!seg1 && seg2) || (seg1 && !seg2)) return 0; if (seg1->type != seg2->type) return 0; if (seg1->length != seg2->length) return 0; for (i = 0; i < seg1->length; i++) if (seg1->as[i] != seg2->as[i]) return 0; seg1 = seg1->next; seg2 = seg2->next; } return 1; } Commit Message: 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: tt_cmap4_validate( FT_Byte* table, FT_Validator valid ) { FT_Byte* p; FT_UInt length; FT_Byte *ends, *starts, *offsets, *deltas, *glyph_ids; FT_UInt num_segs; FT_Error error = FT_Err_Ok; if ( table + 2 + 2 > valid->limit ) FT_INVALID_TOO_SHORT; p = table + 2; /* skip format */ length = TT_NEXT_USHORT( p ); if ( length < 16 ) FT_INVALID_TOO_SHORT; /* in certain fonts, the `length' field is invalid and goes */ /* out of bound. We try to correct this here... */ if ( table + length > valid->limit ) /* in certain fonts, the `length' field is invalid and goes */ /* out of bound. We try to correct this here... */ if ( table + length > valid->limit ) { length = (FT_UInt)( valid->limit - table ); } p = table + 6; num_segs = TT_NEXT_USHORT( p ); /* read segCountX2 */ if ( valid->level >= FT_VALIDATE_PARANOID ) { /* check that we have an even value here */ if ( num_segs & 1 ) FT_INVALID_DATA; } num_segs /= 2; if ( length < 16 + num_segs * 2 * 4 ) FT_INVALID_TOO_SHORT; /* check the search parameters - even though we never use them */ /* */ if ( valid->level >= FT_VALIDATE_PARANOID ) { /* check the values of `searchRange', `entrySelector', `rangeShift' */ FT_UInt search_range = TT_NEXT_USHORT( p ); FT_UInt entry_selector = TT_NEXT_USHORT( p ); FT_UInt range_shift = TT_NEXT_USHORT( p ); if ( ( search_range | range_shift ) & 1 ) /* must be even values */ FT_INVALID_DATA; search_range /= 2; range_shift /= 2; /* `search range' is the greatest power of 2 that is <= num_segs */ if ( search_range > num_segs || search_range * 2 < num_segs || search_range + range_shift != num_segs || search_range != ( 1U << entry_selector ) ) FT_INVALID_DATA; } ends = table + 14; starts = table + 16 + num_segs * 2; deltas = starts + num_segs * 2; offsets = deltas + num_segs * 2; glyph_ids = offsets + num_segs * 2; /* check last segment; its end count value must be 0xFFFF */ if ( valid->level >= FT_VALIDATE_PARANOID ) { p = ends + ( num_segs - 1 ) * 2; if ( TT_PEEK_USHORT( p ) != 0xFFFFU ) FT_INVALID_DATA; } { FT_UInt start, end, offset, n; FT_UInt last_start = 0, last_end = 0; FT_Int delta; FT_Byte* p_start = starts; FT_Byte* p_end = ends; FT_Byte* p_delta = deltas; FT_Byte* p_offset = offsets; for ( n = 0; n < num_segs; n++ ) { p = p_offset; start = TT_NEXT_USHORT( p_start ); end = TT_NEXT_USHORT( p_end ); delta = TT_NEXT_SHORT( p_delta ); offset = TT_NEXT_USHORT( p_offset ); if ( start > end ) FT_INVALID_DATA; /* this test should be performed at default validation level; */ /* unfortunately, some popular Asian fonts have overlapping */ /* ranges in their charmaps */ /* */ if ( start <= last_end && n > 0 ) { if ( valid->level >= FT_VALIDATE_TIGHT ) FT_INVALID_DATA; else { /* allow overlapping segments, provided their start points */ /* and end points, respectively, are in ascending order */ /* */ if ( last_start > start || last_end > end ) error |= TT_CMAP_FLAG_UNSORTED; else error |= TT_CMAP_FLAG_OVERLAPPING; } } if ( offset && offset != 0xFFFFU ) { p += offset; /* start of glyph ID array */ /* check that we point within the glyph IDs table only */ if ( valid->level >= FT_VALIDATE_TIGHT ) { if ( p < glyph_ids || p + ( end - start + 1 ) * 2 > table + length ) FT_INVALID_DATA; } /* Some fonts handle the last segment incorrectly. In */ /* theory, 0xFFFF might point to an ordinary glyph -- */ /* a cmap 4 is versatile and could be used for any */ /* encoding, not only Unicode. However, reality shows */ /* that far too many fonts are sloppy and incorrectly */ /* set all fields but `start' and `end' for the last */ /* segment if it contains only a single character. */ /* */ /* We thus omit the test here, delaying it to the */ /* routines which actually access the cmap. */ else if ( n != num_segs - 1 || !( start == 0xFFFFU && end == 0xFFFFU ) ) { if ( p < glyph_ids || p + ( end - start + 1 ) * 2 > valid->limit ) FT_INVALID_DATA; } /* check glyph indices within the segment range */ if ( valid->level >= FT_VALIDATE_TIGHT ) { FT_UInt i, idx; for ( i = start; i < end; i++ ) { idx = FT_NEXT_USHORT( p ); if ( idx != 0 ) { idx = (FT_UInt)( idx + delta ) & 0xFFFFU; if ( idx >= TT_VALID_GLYPH_COUNT( valid ) ) FT_INVALID_GLYPH_ID; } } } } else if ( offset == 0xFFFFU ) { /* some fonts (erroneously?) use a range offset of 0xFFFF */ /* to mean missing glyph in cmap table */ /* */ if ( valid->level >= FT_VALIDATE_PARANOID || n != num_segs - 1 || !( start == 0xFFFFU && end == 0xFFFFU ) ) FT_INVALID_DATA; } last_start = start; last_end = end; } } return error; } 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: static Image *ReadWPGImage(const ImageInfo *image_info, ExceptionInfo *exception) { typedef struct { size_t FileId; MagickOffsetType DataOffset; unsigned int ProductType; unsigned int FileType; unsigned char MajorVersion; unsigned char MinorVersion; unsigned int EncryptKey; unsigned int Reserved; } WPGHeader; typedef struct { unsigned char RecType; size_t RecordLength; } WPGRecord; typedef struct { unsigned char Class; unsigned char RecType; size_t Extension; size_t RecordLength; } WPG2Record; typedef struct { unsigned HorizontalUnits; unsigned VerticalUnits; unsigned char PosSizePrecision; } WPG2Start; typedef struct { unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType1; typedef struct { unsigned int Width; unsigned int Height; unsigned char Depth; unsigned char Compression; } WPG2BitmapType1; typedef struct { unsigned int RotAngle; unsigned int LowLeftX; unsigned int LowLeftY; unsigned int UpRightX; unsigned int UpRightY; unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType2; typedef struct { unsigned int StartIndex; unsigned int NumOfEntries; } WPGColorMapRec; /* typedef struct { size_t PS_unknown1; unsigned int PS_unknown2; unsigned int PS_unknown3; } WPGPSl1Record; */ Image *image; unsigned int status; WPGHeader Header; WPGRecord Rec; WPG2Record Rec2; WPG2Start StartWPG; WPGBitmapType1 BitmapHeader1; WPG2BitmapType1 Bitmap2Header1; WPGBitmapType2 BitmapHeader2; WPGColorMapRec WPG_Palette; int i, bpp, WPG2Flags; ssize_t ldblk; size_t one; unsigned char *BImgBuff; tCTM CTM; /*current transform matrix*/ /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); one=1; image=AcquireImage(image_info); image->depth=8; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read WPG image. */ Header.FileId=ReadBlobLSBLong(image); Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); Header.ProductType=ReadBlobLSBShort(image); Header.FileType=ReadBlobLSBShort(image); Header.MajorVersion=ReadBlobByte(image); Header.MinorVersion=ReadBlobByte(image); Header.EncryptKey=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (Header.EncryptKey!=0) ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported"); image->columns = 1; image->rows = 1; image->colors = 0; bpp=0; BitmapHeader2.RotAngle=0; Rec2.RecordLength = 0; switch(Header.FileType) { case 1: /* WPG level 1 */ while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec.RecordLength); if (Rec.RecordLength > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec.RecordLength; switch(Rec.RecType) { case 0x0B: /* bitmap type 1 */ BitmapHeader1.Width=ReadBlobLSBShort(image); BitmapHeader1.Height=ReadBlobLSBShort(image); if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader1.Depth=ReadBlobLSBShort(image); BitmapHeader1.HorzRes=ReadBlobLSBShort(image); BitmapHeader1.VertRes=ReadBlobLSBShort(image); if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) { image->units=PixelsPerCentimeterResolution; image->x_resolution=BitmapHeader1.HorzRes/470.0; image->y_resolution=BitmapHeader1.VertRes/470.0; } image->columns=BitmapHeader1.Width; image->rows=BitmapHeader1.Height; bpp=BitmapHeader1.Depth; goto UnpackRaster; case 0x0E: /*Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > (Rec2.RecordLength-2-2) / 3) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); image->colors=WPG_Palette.NumOfEntries; if (!AcquireImageColormap(image,image->colors)) goto NoMemory; for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } break; case 0x11: /* Start PS l1 */ if(Rec.RecordLength > 8) image=ExtractPostscript(image,image_info, TellBlob(image)+8, /* skip PS header in the wpg */ (ssize_t) Rec.RecordLength-8,exception); break; case 0x14: /* bitmap type 2 */ BitmapHeader2.RotAngle=ReadBlobLSBShort(image); BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); BitmapHeader2.UpRightX=ReadBlobLSBShort(image); BitmapHeader2.UpRightY=ReadBlobLSBShort(image); BitmapHeader2.Width=ReadBlobLSBShort(image); BitmapHeader2.Height=ReadBlobLSBShort(image); if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader2.Depth=ReadBlobLSBShort(image); BitmapHeader2.HorzRes=ReadBlobLSBShort(image); BitmapHeader2.VertRes=ReadBlobLSBShort(image); image->units=PixelsPerCentimeterResolution; image->page.width=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); image->page.height=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) { image->x_resolution=BitmapHeader2.HorzRes/470.0; image->y_resolution=BitmapHeader2.VertRes/470.0; } image->columns=BitmapHeader2.Width; image->rows=BitmapHeader2.Height; bpp=BitmapHeader2.Depth; UnpackRaster: status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) break; if ((image->colors == 0) && (bpp <= 16)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors)) { NoMemory: ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } /* printf("Load default colormap \n"); */ for (i=0; (i < (int) image->colors) && (i < 256); i++) { image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); } } else { if (bpp < 24) if ( (image->colors < (one << bpp)) && (bpp != 24) ) image->colormap=(PixelPacket *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } if (bpp == 1) { if(image->colormap[0].red==0 && image->colormap[0].green==0 && image->colormap[0].blue==0 && image->colormap[1].red==0 && image->colormap[1].green==0 && image->colormap[1].blue==0) { /* fix crippled monochrome palette */ image->colormap[1].red = image->colormap[1].green = image->colormap[1].blue = QuantumRange; } } if(UnpackWPGRaster(image,bpp) < 0) /* The raster cannot be unpacked */ { DecompressionFailed: ThrowReaderException(CoderError,"UnableToDecompressImage"); } if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) { /* flop command */ if(BitmapHeader2.RotAngle & 0x8000) { Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); ReplaceImageInList(&image,flop_image); } } /* flip command */ if(BitmapHeader2.RotAngle & 0x2000) { Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); ReplaceImageInList(&image,flip_image); } } /* rotate command */ if(BitmapHeader2.RotAngle & 0x0FFF) { Image *rotate_image; rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & 0x0FFF), exception); if (rotate_image != (Image *) NULL) { DuplicateBlob(rotate_image,image); ReplaceImageInList(&image,rotate_image); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x1B: /* Postscript l2 */ if(Rec.RecordLength>0x3C) image=ExtractPostscript(image,image_info, TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ (ssize_t) Rec.RecordLength-0x3C,exception); break; } } break; case 2: /* WPG level 2 */ (void) memset(CTM,0,sizeof(CTM)); StartWPG.PosSizePrecision = 0; while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec2.Class=(i=ReadBlobByte(image)); if(i==EOF) break; Rec2.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec2.Extension); Rd_WP_DWORD(image,&Rec2.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec2.RecordLength; switch(Rec2.RecType) { case 1: StartWPG.HorizontalUnits=ReadBlobLSBShort(image); StartWPG.VerticalUnits=ReadBlobLSBShort(image); StartWPG.PosSizePrecision=ReadBlobByte(image); break; case 0x0C: /* Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > (Rec2.RecordLength-2-2) / 3) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); image->colors=WPG_Palette.NumOfEntries; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((char) ReadBlobByte(image)); (void) ReadBlobByte(image); /*Opacity??*/ } break; case 0x0E: Bitmap2Header1.Width=ReadBlobLSBShort(image); Bitmap2Header1.Height=ReadBlobLSBShort(image); if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); Bitmap2Header1.Depth=ReadBlobByte(image); Bitmap2Header1.Compression=ReadBlobByte(image); if(Bitmap2Header1.Compression > 1) continue; /*Unknown compression method */ switch(Bitmap2Header1.Depth) { case 1: bpp=1; break; case 2: bpp=2; break; case 3: bpp=4; break; case 4: bpp=8; break; case 8: bpp=24; break; default: continue; /*Ignore raster with unknown depth*/ } image->columns=Bitmap2Header1.Width; image->rows=Bitmap2Header1.Height; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) break; if ((image->colors == 0) && (bpp != 24)) { size_t one; one=1; image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors)) goto NoMemory; } else { if(bpp < 24) if( image->colors<(one << bpp) && bpp!=24 ) image->colormap=(PixelPacket *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } switch(Bitmap2Header1.Compression) { case 0: /*Uncompressed raster*/ { ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk+1,sizeof(*BImgBuff)); if (BImgBuff == (unsigned char *) NULL) goto NoMemory; for(i=0; i< (ssize_t) image->rows; i++) { (void) ReadBlob(image,ldblk,BImgBuff); InsertRow(BImgBuff,i,image,bpp); } if(BImgBuff) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); break; } case 1: /*RLE for WPG2 */ { if( UnpackWPG2Raster(image,bpp) < 0) goto DecompressionFailed; break; } } if(CTM[0][0]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); ReplaceImageInList(&image,flop_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); Tx(1,2)=0; Tx(2,2)=1; */ } if(CTM[1][1]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); ReplaceImageInList(&image,flip_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. float_matrix Tx(3,3); Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); Tx(2,2)=1; */ } /* Allocate next image structure. */ AcquireNextImage(image_info,image); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x12: /* Postscript WPG2*/ i=ReadBlobLSBShort(image); if(Rec2.RecordLength > (unsigned int) i) image=ExtractPostscript(image,image_info, TellBlob(image)+i, /*skip PS header in the wpg2*/ (ssize_t) (Rec2.RecordLength-i-2),exception); break; case 0x1B: /*bitmap rectangle*/ WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); (void) WPG2Flags; break; } } break; default: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); } } Finish: (void) 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=(size_t) scene++; } if (image == (Image *) NULL) ThrowReaderException(CorruptImageError, "ImageFileDoesNotContainAnyImageData"); return(image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/851 CWE ID: CWE-119 Target: 1 Example 2: Code: static inline int getPixelOverflowColorTC(gdImagePtr im, const int x, const int y, const int color) { if (gdImageBoundsSafe(im, x, y)) { const int c = im->tpixels[y][x]; if (c == im->transparent) { return gdTrueColorAlpha(0, 0, 0, 127); } return c; } else { register int border = 0; if (y < im->cy1) { border = im->tpixels[0][im->cx1]; goto processborder; } if (y < im->cy1) { border = im->tpixels[0][im->cx1]; goto processborder; } if (y > im->cy2) { if (x >= im->cx1 && x <= im->cx1) { border = im->tpixels[im->cy2][x]; goto processborder; } else { return gdTrueColorAlpha(0, 0, 0, 127); } } /* y is bound safe at this point */ if (x < im->cx1) { border = im->tpixels[y][im->cx1]; goto processborder; } if (x > im->cx2) { border = im->tpixels[y][im->cx2]; } processborder: if (border == im->transparent) { return gdTrueColorAlpha(0, 0, 0, 127); } else{ return gdTrueColorAlpha(gdTrueColorGetRed(border), gdTrueColorGetGreen(border), gdTrueColorGetBlue(border), 127); } } } 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: 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 FileSystemManagerImpl::Write( const GURL& file_path, const std::string& blob_uuid, int64_t position, blink::mojom::FileSystemCancellableOperationRequest op_request, blink::mojom::FileSystemOperationListenerPtr listener) { DCHECK_CURRENTLY_ON(BrowserThread::IO); FileSystemURL url(context_->CrackURL(file_path)); base::Optional<base::File::Error> opt_error = ValidateFileSystemURL(url); if (opt_error) { listener->ErrorOccurred(opt_error.value()); return; } if (!security_policy_->CanWriteFileSystemFile(process_id_, url)) { listener->ErrorOccurred(base::File::FILE_ERROR_SECURITY); return; } std::unique_ptr<storage::BlobDataHandle> blob = blob_storage_context_->context()->GetBlobDataFromUUID(blob_uuid); OperationListenerID listener_id = AddOpListener(std::move(listener)); OperationID op_id = operation_runner()->Write( url, std::move(blob), position, base::BindRepeating(&FileSystemManagerImpl::DidWrite, GetWeakPtr(), listener_id)); cancellable_operations_.AddBinding( std::make_unique<FileSystemCancellableOperationImpl>(op_id, this), std::move(op_request)); } Commit Message: Disable FileSystemManager::CreateWriter if WritableFiles isn't enabled. Bug: 922677 Change-Id: Ib16137cbabb2ec07f1ffc0484722f1d9cc533404 Reviewed-on: https://chromium-review.googlesource.com/c/1416570 Commit-Queue: Marijn Kruisselbrink <[email protected]> Reviewed-by: Victor Costan <[email protected]> Cr-Commit-Position: refs/heads/master@{#623552} 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: IMPEG2D_ERROR_CODES_T impeg2d_dec_pic_ext_data(dec_state_t *ps_dec) { stream_t *ps_stream; UWORD32 u4_start_code; IMPEG2D_ERROR_CODES_T e_error; e_error = (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; ps_stream = &ps_dec->s_bit_stream; u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); while ( (u4_start_code == EXTENSION_START_CODE || u4_start_code == USER_DATA_START_CODE) && (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE == e_error) { if(u4_start_code == USER_DATA_START_CODE) { impeg2d_dec_user_data(ps_dec); } else { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u4_start_code = impeg2d_bit_stream_nxt(ps_stream,EXT_ID_LEN); switch(u4_start_code) { case QUANT_MATRIX_EXT_ID: impeg2d_dec_quant_matrix_ext(ps_dec); break; case COPYRIGHT_EXT_ID: impeg2d_dec_copyright_ext(ps_dec); break; case PIC_DISPLAY_EXT_ID: impeg2d_dec_pic_disp_ext(ps_dec); break; case CAMERA_PARAM_EXT_ID: impeg2d_dec_cam_param_ext(ps_dec); break; case ITU_T_EXT_ID: impeg2d_dec_itu_t_ext(ps_dec); break; case PIC_SPATIAL_SCALABLE_EXT_ID: case PIC_TEMPORAL_SCALABLE_EXT_ID: e_error = IMPEG2D_SCALABLITY_NOT_SUP; break; default: /* In case its a reserved extension code */ impeg2d_bit_stream_flush(ps_stream,EXT_ID_LEN); impeg2d_next_start_code(ps_dec); break; } } u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); } return e_error; } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254 Target: 1 Example 2: Code: vlog_message(const int facility, const char* format, va_list args) { #if !HAVE_VSYSLOG char buf[MAX_LOG_MSG+1]; vsnprintf(buf, sizeof(buf), format, args); #endif /* Don't write syslog if testing configuration */ if (__test_bit(CONFIG_TEST_BIT, &debug)) return; if (log_file || (__test_bit(DONT_FORK_BIT, &debug) && log_console)) { #if HAVE_VSYSLOG va_list args1; char buf[2 * MAX_LOG_MSG + 1]; va_copy(args1, args); vsnprintf(buf, sizeof(buf), format, args1); va_end(args1); #endif /* timestamp setup */ time_t t = time(NULL); struct tm tm; localtime_r(&t, &tm); char timestamp[64]; strftime(timestamp, sizeof(timestamp), "%c", &tm); if (log_console && __test_bit(DONT_FORK_BIT, &debug)) fprintf(stderr, "%s: %s\n", timestamp, buf); if (log_file) { fprintf(log_file, "%s: %s\n", timestamp, buf); if (always_flush_log_file) fflush(log_file); } } if (!__test_bit(NO_SYSLOG_BIT, &debug)) #if HAVE_VSYSLOG vsyslog(facility, format, args); #else syslog(facility, "%s", buf); #endif } Commit Message: When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-59 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 AudioRendererAlgorithm::FillBuffer( uint8* dest, int requested_frames) { DCHECK_NE(bytes_per_frame_, 0); if (playback_rate_ == 0.0f) return 0; int total_frames_rendered = 0; uint8* output_ptr = dest; while (total_frames_rendered < requested_frames) { if (index_into_window_ == window_size_) ResetWindow(); bool rendered_frame = true; if (playback_rate_ > 1.0) rendered_frame = OutputFasterPlayback(output_ptr); else if (playback_rate_ < 1.0) rendered_frame = OutputSlowerPlayback(output_ptr); else rendered_frame = OutputNormalPlayback(output_ptr); if (!rendered_frame) { needs_more_data_ = true; break; } output_ptr += bytes_per_frame_; total_frames_rendered++; } return total_frames_rendered; } Commit Message: Protect AudioRendererAlgorithm from invalid step sizes. BUG=165430 TEST=unittests and asan pass. Review URL: https://codereview.chromium.org/11573023 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 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 tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen, const unsigned char *sess_id, int sesslen, SSL_SESSION **psess) { SSL_SESSION *sess; unsigned char *sdec; const unsigned char *p; int slen, mlen, renew_ticket = 0, ret = -1; unsigned char tick_hmac[EVP_MAX_MD_SIZE]; HMAC_CTX *hctx = NULL; EVP_CIPHER_CTX *ctx; SSL_CTX *tctx = s->initial_ctx; /* Need at least keyname + iv + some encrypted data */ if (eticklen < 48) return 2; /* Initialize session ticket encryption and HMAC contexts */ hctx = HMAC_CTX_new(); if (hctx == NULL) hctx = HMAC_CTX_new(); if (hctx == NULL) return -2; ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { ret = -2; goto err; } if (tctx->tlsext_ticket_key_cb) { unsigned char *nctick = (unsigned char *)etick; int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16, ctx, hctx, 0); if (rv < 0) goto err; if (rv == 0) { ret = 2; goto err; } if (rv == 2) renew_ticket = 1; } else { /* Check key name matches */ if (memcmp(etick, tctx->tlsext_tick_key_name, sizeof(tctx->tlsext_tick_key_name)) != 0) { ret = 2; goto err; } if (HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key, sizeof(tctx->tlsext_tick_hmac_key), EVP_sha256(), NULL) <= 0 || EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, tctx->tlsext_tick_aes_key, etick + sizeof(tctx->tlsext_tick_key_name)) <= 0) { goto err; } } /* * Attempt to process session ticket, first conduct sanity and integrity * checks on ticket. if (mlen < 0) { goto err; } eticklen -= mlen; /* Check HMAC of encrypted ticket */ if (HMAC_Update(hctx, etick, eticklen) <= 0 if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) { EVP_CIPHER_CTX_free(ctx); return 2; } /* Attempt to decrypt session data */ /* Move p after IV to start of encrypted ticket, update length */ p = etick + 16 + EVP_CIPHER_CTX_iv_length(ctx); eticklen -= 16 + EVP_CIPHER_CTX_iv_length(ctx); sdec = OPENSSL_malloc(eticklen); if (sdec == NULL || EVP_DecryptUpdate(ctx, sdec, &slen, p, eticklen) <= 0) { EVP_CIPHER_CTX_free(ctx); OPENSSL_free(sdec); return -1; } if (EVP_DecryptFinal(ctx, sdec + slen, &mlen) <= 0) { EVP_CIPHER_CTX_free(ctx); OPENSSL_free(sdec); return 2; } slen += mlen; EVP_CIPHER_CTX_free(ctx); ctx = NULL; p = sdec; sess = d2i_SSL_SESSION(NULL, &p, slen); OPENSSL_free(sdec); if (sess) { /* * The session ID, if non-empty, is used by some clients to detect * that the ticket has been accepted. So we copy it to the session * structure. If it is empty set length to zero as required by * standard. */ if (sesslen) memcpy(sess->session_id, sess_id, sesslen); sess->session_id_length = sesslen; *psess = sess; if (renew_ticket) return 4; else return 3; } ERR_clear_error(); /* * For session parse failure, indicate that we need to send a new ticket. */ return 2; err: EVP_CIPHER_CTX_free(ctx); HMAC_CTX_free(hctx); return ret; } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: static long btrfs_ioctl_scrub_cancel(struct btrfs_root *root, void __user *arg) { if (!capable(CAP_SYS_ADMIN)) return -EPERM; return btrfs_scrub_cancel(root->fs_info); } 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 GfxImageColorMap::getRGBLine(Guchar *in, unsigned int *out, int length) { int i, j; Guchar *inp, *tmp_line; switch (colorSpace->getMode()) { case csIndexed: case csSeparation: tmp_line = (Guchar *) gmalloc (length * nComps2); for (i = 0; i < length; i++) { for (j = 0; j < nComps2; j++) { tmp_line[i * nComps2 + j] = byte_lookup[in[i] * nComps2 + j]; } } colorSpace2->getRGBLine(tmp_line, out, length); gfree (tmp_line); break; default: inp = in; for (j = 0; j < length; j++) for (i = 0; i < nComps; i++) { *inp = byte_lookup[*inp * nComps + i]; inp++; } colorSpace->getRGBLine(in, out, length); break; } } 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: IMPEG2D_ERROR_CODES_T impeg2d_dec_p_b_slice(dec_state_t *ps_dec) { WORD16 *pi2_vld_out; UWORD32 i; yuv_buf_t *ps_cur_frm_buf = &ps_dec->s_cur_frm_buf; UWORD32 u4_frm_offset = 0; const dec_mb_params_t *ps_dec_mb_params; IMPEG2D_ERROR_CODES_T e_error = (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; pi2_vld_out = ps_dec->ai2_vld_buf; memset(ps_dec->ai2_pred_mv,0,sizeof(ps_dec->ai2_pred_mv)); ps_dec->u2_prev_intra_mb = 0; ps_dec->u2_first_mb = 1; ps_dec->u2_picture_width = ps_dec->u2_frame_width; if(ps_dec->u2_picture_structure != FRAME_PICTURE) { ps_dec->u2_picture_width <<= 1; if(ps_dec->u2_picture_structure == BOTTOM_FIELD) { u4_frm_offset = ps_dec->u2_frame_width; } } do { UWORD32 u4_x_offset, u4_y_offset; UWORD32 u4_x_dst_offset = 0; UWORD32 u4_y_dst_offset = 0; UWORD8 *pu1_out_p; UWORD8 *pu1_pred; WORD32 u4_pred_strd; IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y); if(ps_dec->e_pic_type == B_PIC) impeg2d_dec_pnb_mb_params(ps_dec); else impeg2d_dec_p_mb_params(ps_dec); IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y); u4_x_dst_offset = u4_frm_offset + (ps_dec->u2_mb_x << 4); u4_y_dst_offset = (ps_dec->u2_mb_y << 4) * ps_dec->u2_picture_width; pu1_out_p = ps_cur_frm_buf->pu1_y + u4_x_dst_offset + u4_y_dst_offset; if(ps_dec->u2_prev_intra_mb == 0) { UWORD32 offset_x, offset_y, stride; UWORD16 index = (ps_dec->u2_motion_type); /*only for non intra mb's*/ if(ps_dec->e_mb_pred == BIDIRECT) { ps_dec_mb_params = &ps_dec->ps_func_bi_direct[index]; } else { ps_dec_mb_params = &ps_dec->ps_func_forw_or_back[index]; } stride = ps_dec->u2_picture_width; offset_x = u4_frm_offset + (ps_dec->u2_mb_x << 4); offset_y = (ps_dec->u2_mb_y << 4); ps_dec->s_dest_buf.pu1_y = ps_cur_frm_buf->pu1_y + offset_y * stride + offset_x; stride = stride >> 1; ps_dec->s_dest_buf.pu1_u = ps_cur_frm_buf->pu1_u + (offset_y >> 1) * stride + (offset_x >> 1); ps_dec->s_dest_buf.pu1_v = ps_cur_frm_buf->pu1_v + (offset_y >> 1) * stride + (offset_x >> 1); PROFILE_DISABLE_MC_IF0 ps_dec_mb_params->pf_mc(ps_dec); } for(i = 0; i < NUM_LUMA_BLKS; ++i) { if((ps_dec->u2_cbp & (1 << (BLOCKS_IN_MB - 1 - i))) != 0) { e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, ps_dec->u2_prev_intra_mb, Y_LUMA, 0); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } u4_x_offset = gai2_impeg2_blk_x_off[i]; if(ps_dec->u2_field_dct == 0) u4_y_offset = gai2_impeg2_blk_y_off_frm[i] ; else u4_y_offset = gai2_impeg2_blk_y_off_fld[i] ; IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); PROFILE_DISABLE_IDCT_IF0 { WORD32 idx; if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) idx = 0; else idx = 1; if(0 == ps_dec->u2_prev_intra_mb) { pu1_pred = pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset; u4_pred_strd = ps_dec->u2_picture_width << ps_dec->u2_field_dct; } else { pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; u4_pred_strd = 8; } ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, ps_dec->ai2_idct_stg1, pu1_pred, pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset, 8, u4_pred_strd, ps_dec->u2_picture_width << ps_dec->u2_field_dct, ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); } } } /* For U and V blocks, divide the x and y offsets by 2. */ u4_x_dst_offset >>= 1; u4_y_dst_offset >>= 2; /* In case of chrominance blocks the DCT will be frame DCT */ /* i = 0, U component and i = 1 is V componet */ if((ps_dec->u2_cbp & 0x02) != 0) { pu1_out_p = ps_cur_frm_buf->pu1_u + u4_x_dst_offset + u4_y_dst_offset; e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, ps_dec->u2_prev_intra_mb, U_CHROMA, 0); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); PROFILE_DISABLE_IDCT_IF0 { WORD32 idx; if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) idx = 0; else idx = 1; if(0 == ps_dec->u2_prev_intra_mb) { pu1_pred = pu1_out_p; u4_pred_strd = ps_dec->u2_picture_width >> 1; } else { pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; u4_pred_strd = 8; } ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, ps_dec->ai2_idct_stg1, pu1_pred, pu1_out_p, 8, u4_pred_strd, ps_dec->u2_picture_width >> 1, ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); } } if((ps_dec->u2_cbp & 0x01) != 0) { pu1_out_p = ps_cur_frm_buf->pu1_v + u4_x_dst_offset + u4_y_dst_offset; e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, ps_dec->u2_prev_intra_mb, V_CHROMA, 0); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); PROFILE_DISABLE_IDCT_IF0 { WORD32 idx; if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) idx = 0; else idx = 1; if(0 == ps_dec->u2_prev_intra_mb) { pu1_pred = pu1_out_p; u4_pred_strd = ps_dec->u2_picture_width >> 1; } else { pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; u4_pred_strd = 8; } ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, ps_dec->ai2_idct_stg1, pu1_pred, pu1_out_p, 8, u4_pred_strd, ps_dec->u2_picture_width >> 1, ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); } } ps_dec->u2_num_mbs_left--; ps_dec->u2_first_mb = 0; ps_dec->u2_mb_x++; if(ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset) { return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR; } else if (ps_dec->u2_mb_x == ps_dec->u2_num_horiz_mb) { ps_dec->u2_mb_x = 0; ps_dec->u2_mb_y++; } } while(ps_dec->u2_num_mbs_left != 0 && impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,23) != 0x0); return e_error; } Commit Message: Return error for wrong mb_type If mb_type decoded returns an invalid type of MB, then return error Bug: 26070014 Change-Id: I66abcad5de1352dd42d05b1a13bb4176153b133c CWE ID: CWE-119 Target: 1 Example 2: Code: static void nfs4_setup_readdir(u64 cookie, __be32 *verifier, struct dentry *dentry, struct nfs4_readdir_arg *readdir) { __be32 *start, *p; BUG_ON(readdir->count < 80); if (cookie > 2) { readdir->cookie = cookie; memcpy(&readdir->verifier, verifier, sizeof(readdir->verifier)); return; } readdir->cookie = 0; memset(&readdir->verifier, 0, sizeof(readdir->verifier)); if (cookie == 2) return; /* * NFSv4 servers do not return entries for '.' and '..' * Therefore, we fake these entries here. We let '.' * have cookie 0 and '..' have cookie 1. Note that * when talking to the server, we always send cookie 0 * instead of 1 or 2. */ start = p = kmap_atomic(*readdir->pages, KM_USER0); if (cookie == 0) { *p++ = xdr_one; /* next */ *p++ = xdr_zero; /* cookie, first word */ *p++ = xdr_one; /* cookie, second word */ *p++ = xdr_one; /* entry len */ memcpy(p, ".\0\0\0", 4); /* entry */ p++; *p++ = xdr_one; /* bitmap length */ *p++ = htonl(FATTR4_WORD0_FILEID); /* bitmap */ *p++ = htonl(8); /* attribute buffer length */ p = xdr_encode_hyper(p, NFS_FILEID(dentry->d_inode)); } *p++ = xdr_one; /* next */ *p++ = xdr_zero; /* cookie, first word */ *p++ = xdr_two; /* cookie, second word */ *p++ = xdr_two; /* entry len */ memcpy(p, "..\0\0", 4); /* entry */ p++; *p++ = xdr_one; /* bitmap length */ *p++ = htonl(FATTR4_WORD0_FILEID); /* bitmap */ *p++ = htonl(8); /* attribute buffer length */ p = xdr_encode_hyper(p, NFS_FILEID(dentry->d_parent->d_inode)); readdir->pgbase = (char *)p - (char *)start; readdir->count -= readdir->pgbase; kunmap_atomic(start, KM_USER0); } 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: char *dentry_path(struct dentry *dentry, char *buf, int buflen) { char *p = NULL; char *retval; if (d_unlinked(dentry)) { p = buf + buflen; if (prepend(&p, &buflen, "//deleted", 10) != 0) goto Elong; buflen++; } retval = __dentry_path(dentry, buf, buflen); if (!IS_ERR(retval) && p) *p = '/'; /* restore '/' overriden with '\0' */ return retval; Elong: return ERR_PTR(-ENAMETOOLONG); } Commit Message: dentry name snapshots take_dentry_name_snapshot() takes a safe snapshot of dentry name; if the name is a short one, it gets copied into caller-supplied structure, otherwise an extra reference to external name is grabbed (those are never modified). In either case the pointer to stable string is stored into the same structure. dentry must be held by the caller of take_dentry_name_snapshot(), but may be freely dropped afterwards - the snapshot will stay until destroyed by release_dentry_name_snapshot(). Intended use: struct name_snapshot s; take_dentry_name_snapshot(&s, dentry); ... access s.name ... release_dentry_name_snapshot(&s); Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name to pass down with event. Signed-off-by: Al Viro <[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 SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size) { register ssize_t i; MagickOffsetType offset; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20 Target: 1 Example 2: Code: hook_connect (struct t_weechat_plugin *plugin, const char *proxy, const char *address, int port, int sock, int ipv6, void *gnutls_sess, void *gnutls_cb, int gnutls_dhkey_size, const char *local_hostname, t_hook_callback_connect *callback, void *callback_data) { struct t_hook *new_hook; struct t_hook_connect *new_hook_connect; #ifndef HAVE_GNUTLS /* make C compiler happy */ (void) gnutls_sess; (void) gnutls_cb; (void) gnutls_dhkey_size; #endif if ((sock < 0) || !address || (port <= 0) || !callback) return NULL; new_hook = malloc (sizeof (*new_hook)); if (!new_hook) return NULL; new_hook_connect = malloc (sizeof (*new_hook_connect)); if (!new_hook_connect) { free (new_hook); return NULL; } hook_init_data (new_hook, plugin, HOOK_TYPE_CONNECT, HOOK_PRIORITY_DEFAULT, callback_data); new_hook->hook_data = new_hook_connect; new_hook_connect->callback = callback; new_hook_connect->proxy = (proxy) ? strdup (proxy) : NULL; new_hook_connect->address = strdup (address); new_hook_connect->port = port; new_hook_connect->sock = sock; new_hook_connect->ipv6 = ipv6; #ifdef HAVE_GNUTLS new_hook_connect->gnutls_sess = gnutls_sess; new_hook_connect->gnutls_cb = gnutls_cb; new_hook_connect->gnutls_dhkey_size = gnutls_dhkey_size; #endif new_hook_connect->local_hostname = (local_hostname) ? strdup (local_hostname) : NULL; new_hook_connect->child_read = -1; new_hook_connect->child_write = -1; new_hook_connect->child_pid = 0; new_hook_connect->hook_fd = NULL; new_hook_connect->handshake_hook_fd = NULL; new_hook_connect->handshake_hook_timer = NULL; new_hook_connect->handshake_fd_flags = 0; new_hook_connect->handshake_ip_address = NULL; hook_add_to_list (new_hook); network_connect_with_fork (new_hook); return new_hook; } Commit Message: 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 Image *ReadEXRImage(const ImageInfo *image_info,ExceptionInfo *exception) { const ImfHeader *hdr_info; Image *image; ImageInfo *read_info; ImfInputFile *file; ImfRgba *scanline; int max_x, max_y, min_x, min_y; MagickBooleanType status; register ssize_t x; register PixelPacket *q; ssize_t y; /* Open 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); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } read_info=CloneImageInfo(image_info); if (IsPathAccessible(read_info->filename) == MagickFalse) { (void) AcquireUniqueFilename(read_info->filename); (void) ImageToFile(image,read_info->filename,exception); } file=ImfOpenInputFile(read_info->filename); if (file == (ImfInputFile *) NULL) { ThrowFileException(exception,BlobError,"UnableToOpenBlob", ImfErrorMessage()); if (LocaleCompare(image_info->filename,read_info->filename) != 0) (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); return((Image *) NULL); } hdr_info=ImfInputHeader(file); ImfHeaderDisplayWindow(hdr_info,&min_x,&min_y,&max_x,&max_y); image->columns=max_x-min_x+1UL; image->rows=max_y-min_y+1UL; image->matte=MagickTrue; SetImageColorspace(image,RGBColorspace); if (image_info->ping != MagickFalse) { (void) ImfCloseInputFile(file); if (LocaleCompare(image_info->filename,read_info->filename) != 0) (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } scanline=(ImfRgba *) AcquireQuantumMemory(image->columns,sizeof(*scanline)); if (scanline == (ImfRgba *) NULL) { (void) ImfCloseInputFile(file); if (LocaleCompare(image_info->filename,read_info->filename) != 0) (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; ResetMagickMemory(scanline,0,image->columns*sizeof(*scanline)); ImfInputSetFrameBuffer(file,scanline-min_x-image->columns*(min_y+y),1, image->columns); ImfInputReadPixels(file,min_y+y,min_y+y); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum((MagickRealType) QuantumRange* ImfHalfToFloat(scanline[x].r))); SetPixelGreen(q,ClampToQuantum((MagickRealType) QuantumRange* ImfHalfToFloat(scanline[x].g))); SetPixelBlue(q,ClampToQuantum((MagickRealType) QuantumRange* ImfHalfToFloat(scanline[x].b))); SetPixelAlpha(q,ClampToQuantum((MagickRealType) QuantumRange* ImfHalfToFloat(scanline[x].a))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } scanline=(ImfRgba *) RelinquishMagickMemory(scanline); (void) ImfCloseInputFile(file); if (LocaleCompare(image_info->filename,read_info->filename) != 0) (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } 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: static void *btif_hh_poll_event_thread(void *arg) { btif_hh_device_t *p_dev = arg; APPL_TRACE_DEBUG("%s: Thread created fd = %d", __FUNCTION__, p_dev->fd); struct pollfd pfds[1]; int ret; pfds[0].fd = p_dev->fd; pfds[0].events = POLLIN; uhid_set_non_blocking(p_dev->fd); while(p_dev->hh_keep_polling){ ret = poll(pfds, 1, 50); if (ret < 0) { APPL_TRACE_ERROR("%s: Cannot poll for fds: %s\n", __FUNCTION__, strerror(errno)); break; } if (pfds[0].revents & POLLIN) { APPL_TRACE_DEBUG("btif_hh_poll_event_thread: POLLIN"); ret = uhid_event(p_dev); if (ret){ break; } } } p_dev->hh_poll_thread_id = -1; return 0; } 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 Target: 1 Example 2: Code: void ChromeWebContentsDelegateAndroid::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_FIND_RESULT_AVAILABLE: OnFindResultAvailable( content::Source<WebContents>(source).ptr(), content::Details<FindNotificationDetails>(details).ptr()); break; default: NOTREACHED() << "Unexpected notification: " << type; break; } } Commit Message: Revert "Load web contents after tab is created." This reverts commit 4c55f398def3214369aefa9f2f2e8f5940d3799d. BUG=432562 [email protected],[email protected],[email protected] Review URL: https://codereview.chromium.org/894003005 Cr-Commit-Position: refs/heads/master@{#314469} 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 usbhid_parse(struct hid_device *hid) { struct usb_interface *intf = to_usb_interface(hid->dev.parent); struct usb_host_interface *interface = intf->cur_altsetting; struct usb_device *dev = interface_to_usbdev (intf); struct hid_descriptor *hdesc; u32 quirks = 0; unsigned int rsize = 0; char *rdesc; int ret, n; quirks = usbhid_lookup_quirk(le16_to_cpu(dev->descriptor.idVendor), le16_to_cpu(dev->descriptor.idProduct)); if (quirks & HID_QUIRK_IGNORE) return -ENODEV; /* Many keyboards and mice don't like to be polled for reports, * so we will always set the HID_QUIRK_NOGET flag for them. */ if (interface->desc.bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT) { if (interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_KEYBOARD || interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_MOUSE) quirks |= HID_QUIRK_NOGET; } if (usb_get_extra_descriptor(interface, HID_DT_HID, &hdesc) && (!interface->desc.bNumEndpoints || usb_get_extra_descriptor(&interface->endpoint[0], HID_DT_HID, &hdesc))) { dbg_hid("class descriptor not present\n"); return -ENODEV; } hid->version = le16_to_cpu(hdesc->bcdHID); hid->country = hdesc->bCountryCode; for (n = 0; n < hdesc->bNumDescriptors; n++) if (hdesc->desc[n].bDescriptorType == HID_DT_REPORT) rsize = le16_to_cpu(hdesc->desc[n].wDescriptorLength); if (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) { dbg_hid("weird size of report descriptor (%u)\n", rsize); return -EINVAL; } rdesc = kmalloc(rsize, GFP_KERNEL); if (!rdesc) return -ENOMEM; hid_set_idle(dev, interface->desc.bInterfaceNumber, 0, 0); ret = hid_get_class_descriptor(dev, interface->desc.bInterfaceNumber, HID_DT_REPORT, rdesc, rsize); if (ret < 0) { dbg_hid("reading report descriptor failed\n"); kfree(rdesc); goto err; } ret = hid_parse_report(hid, rdesc, rsize); kfree(rdesc); if (ret) { dbg_hid("parsing report descriptor failed\n"); goto err; } hid->quirks |= quirks; return 0; err: return ret; } Commit Message: HID: usbhid: fix out-of-bounds bug The hid descriptor identifies the length and type of subordinate descriptors for a device. If the received hid descriptor is smaller than the size of the struct hid_descriptor, it is possible to cause out-of-bounds. In addition, if bNumDescriptors of the hid descriptor have an incorrect value, this can also cause out-of-bounds while approaching hdesc->desc[n]. So check the size of hid descriptor and bNumDescriptors. BUG: KASAN: slab-out-of-bounds in usbhid_parse+0x9b1/0xa20 Read of size 1 at addr ffff88006c5f8edf by task kworker/1:2/1261 CPU: 1 PID: 1261 Comm: kworker/1:2 Not tainted 4.14.0-rc1-42251-gebb2c2437d80 #169 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 Workqueue: usb_hub_wq hub_event Call Trace: __dump_stack lib/dump_stack.c:16 dump_stack+0x292/0x395 lib/dump_stack.c:52 print_address_description+0x78/0x280 mm/kasan/report.c:252 kasan_report_error mm/kasan/report.c:351 kasan_report+0x22f/0x340 mm/kasan/report.c:409 __asan_report_load1_noabort+0x19/0x20 mm/kasan/report.c:427 usbhid_parse+0x9b1/0xa20 drivers/hid/usbhid/hid-core.c:1004 hid_add_device+0x16b/0xb30 drivers/hid/hid-core.c:2944 usbhid_probe+0xc28/0x1100 drivers/hid/usbhid/hid-core.c:1369 usb_probe_interface+0x35d/0x8e0 drivers/usb/core/driver.c:361 really_probe drivers/base/dd.c:413 driver_probe_device+0x610/0xa00 drivers/base/dd.c:557 __device_attach_driver+0x230/0x290 drivers/base/dd.c:653 bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463 __device_attach+0x26e/0x3d0 drivers/base/dd.c:710 device_initial_probe+0x1f/0x30 drivers/base/dd.c:757 bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523 device_add+0xd0b/0x1660 drivers/base/core.c:1835 usb_set_configuration+0x104e/0x1870 drivers/usb/core/message.c:1932 generic_probe+0x73/0xe0 drivers/usb/core/generic.c:174 usb_probe_device+0xaf/0xe0 drivers/usb/core/driver.c:266 really_probe drivers/base/dd.c:413 driver_probe_device+0x610/0xa00 drivers/base/dd.c:557 __device_attach_driver+0x230/0x290 drivers/base/dd.c:653 bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463 __device_attach+0x26e/0x3d0 drivers/base/dd.c:710 device_initial_probe+0x1f/0x30 drivers/base/dd.c:757 bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523 device_add+0xd0b/0x1660 drivers/base/core.c:1835 usb_new_device+0x7b8/0x1020 drivers/usb/core/hub.c:2457 hub_port_connect drivers/usb/core/hub.c:4903 hub_port_connect_change drivers/usb/core/hub.c:5009 port_event drivers/usb/core/hub.c:5115 hub_event+0x194d/0x3740 drivers/usb/core/hub.c:5195 process_one_work+0xc7f/0x1db0 kernel/workqueue.c:2119 worker_thread+0x221/0x1850 kernel/workqueue.c:2253 kthread+0x3a1/0x470 kernel/kthread.c:231 ret_from_fork+0x2a/0x40 arch/x86/entry/entry_64.S:431 Cc: [email protected] Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: Jaejoong Kim <[email protected]> Tested-by: Andrey Konovalov <[email protected]> Acked-by: Alan Stern <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> 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: void OnZipAnalysisFinished(const zip_analyzer::Results& results) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_EQ(ClientDownloadRequest::ZIPPED_EXECUTABLE, type_); if (!service_) return; if (results.success) { zipped_executable_ = results.has_executable; archived_binary_.CopyFrom(results.archived_binary); DVLOG(1) << "Zip analysis finished for " << item_->GetFullPath().value() << ", has_executable=" << results.has_executable << " has_archive=" << results.has_archive; } else { DVLOG(1) << "Zip analysis failed for " << item_->GetFullPath().value(); } UMA_HISTOGRAM_BOOLEAN("SBClientDownload.ZipFileHasExecutable", zipped_executable_); UMA_HISTOGRAM_BOOLEAN("SBClientDownload.ZipFileHasArchiveButNoExecutable", results.has_archive && !zipped_executable_); UMA_HISTOGRAM_TIMES("SBClientDownload.ExtractZipFeaturesTime", base::TimeTicks::Now() - zip_analysis_start_time_); for (const auto& file_extension : results.archived_archive_filetypes) RecordArchivedArchiveFileExtensionType(file_extension); if (!zipped_executable_ && !results.has_archive) { PostFinishTask(UNKNOWN, REASON_ARCHIVE_WITHOUT_BINARIES); return; } if (!zipped_executable_ && results.has_archive) type_ = ClientDownloadRequest::ZIPPED_ARCHIVE; OnFileFeatureExtractionDone(); } Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService. BUG=496898,464083 [email protected], [email protected], [email protected], [email protected] Review URL: https://codereview.chromium.org/1299223006 . Cr-Commit-Position: refs/heads/master@{#344876} CWE ID: Target: 1 Example 2: Code: std::string DownloadResourceHandler::DebugString() const { const ResourceRequestInfoImpl* info = GetRequestInfo(); return base::StringPrintf("{" " url_ = " "\"%s\"" " info = {" " child_id = " "%d" " request_id = " "%d" " route_id = " "%d" " }" " }", request() ? request()->url().spec().c_str() : "<NULL request>", info->GetChildID(), info->GetRequestID(), info->GetRouteID()); } Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <[email protected]> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#629547} CWE ID: CWE-284 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 LocalFrameClientImpl::SetVirtualTimePauser( WebScopedVirtualTimePauser virtual_time_pauser) { virtual_time_pauser_ = std::move(virtual_time_pauser); } Commit Message: Prevent renderer initiated back navigation to cancel a browser one. Renderer initiated back/forward navigations must not be able to cancel ongoing browser initiated navigation if they are not user initiated. Note: 'normal' renderer initiated navigation uses the FrameHost::BeginNavigation() path. A code similar to this patch is done in NavigatorImpl::OnBeginNavigation(). Test: ----- Added: NavigationBrowserTest. * HistoryBackInBeforeUnload * HistoryBackInBeforeUnloadAfterSetTimeout * HistoryBackCancelPendingNavigationNoUserGesture * HistoryBackCancelPendingNavigationUserGesture Fixed: * (WPT) .../the-history-interface/traverse_the_history_2.html * (WPT) .../the-history-interface/traverse_the_history_3.html * (WPT) .../the-history-interface/traverse_the_history_4.html * (WPT) .../the-history-interface/traverse_the_history_5.html Bug: 879965 Change-Id: I1a9bfaaea1ffc219e6c32f6e676b660e746c578c Reviewed-on: https://chromium-review.googlesource.com/1209744 Commit-Queue: Arthur Sonzogni <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Mustaq Ahmed <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Reviewed-by: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#592823} CWE ID: CWE-254 Output:
0