instruction
stringclasses
1 value
input
stringlengths
90
9.34k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int cap_bprm_set_creds(struct linux_binprm *bprm) { const struct cred *old = current_cred(); struct cred *new = bprm->cred; bool effective, has_cap = false; int ret; effective = false; ret = get_file_caps(bprm, &effective, &has_cap); if (ret < 0) return ret; if (!issecure(SECURE_NOROOT)) { /* * If the legacy file capability is set, then don't set privs * for a setuid root binary run by a non-root user. Do set it * for a root user just to cause least surprise to an admin. */ if (has_cap && new->uid != 0 && new->euid == 0) { warn_setuid_and_fcaps_mixed(bprm->filename); goto skip; } /* * To support inheritance of root-permissions and suid-root * executables under compatibility mode, we override the * capability sets for the file. * * If only the real uid is 0, we do not set the effective bit. */ if (new->euid == 0 || new->uid == 0) { /* pP' = (cap_bset & ~0) | (pI & ~0) */ new->cap_permitted = cap_combine(old->cap_bset, old->cap_inheritable); } if (new->euid == 0) effective = true; } skip: /* Don't let someone trace a set[ug]id/setpcap binary with the revised * credentials unless they have the appropriate permit */ if ((new->euid != old->uid || new->egid != old->gid || !cap_issubset(new->cap_permitted, old->cap_permitted)) && bprm->unsafe & ~LSM_UNSAFE_PTRACE_CAP) { /* downgrade; they get no more than they had, and maybe less */ if (!capable(CAP_SETUID)) { new->euid = new->uid; new->egid = new->gid; } new->cap_permitted = cap_intersect(new->cap_permitted, old->cap_permitted); } new->suid = new->fsuid = new->euid; new->sgid = new->fsgid = new->egid; if (effective) new->cap_effective = new->cap_permitted; else cap_clear(new->cap_effective); bprm->cap_effective = effective; /* * Audit candidate if current->cap_effective is set * * We do not bother to audit if 3 things are true: * 1) cap_effective has all caps * 2) we are root * 3) root is supposed to have all caps (SECURE_NOROOT) * Since this is just a normal root execing a process. * * Number 1 above might fail if you don't have a full bset, but I think * that is interesting information to audit. */ if (!cap_isclear(new->cap_effective)) { if (!cap_issubset(CAP_FULL_SET, new->cap_effective) || new->euid != 0 || new->uid != 0 || issecure(SECURE_NOROOT)) { ret = audit_log_bprm_fcaps(bprm, new, old); if (ret < 0) return ret; } } new->securebits &= ~issecure_mask(SECURE_KEEP_CAPS); return 0; } Commit Message: fcaps: clear the same personality flags as suid when fcaps are used If a process increases permissions using fcaps all of the dangerous personality flags which are cleared for suid apps should also be cleared. Thus programs given priviledge with fcaps will continue to have address space randomization enabled even if the parent tried to disable it to make it easier to attack. Signed-off-by: Eric Paris <[email protected]> Reviewed-by: Serge Hallyn <[email protected]> Signed-off-by: James Morris <[email protected]> CWE ID: CWE-264
int cap_bprm_set_creds(struct linux_binprm *bprm) { const struct cred *old = current_cred(); struct cred *new = bprm->cred; bool effective, has_cap = false; int ret; effective = false; ret = get_file_caps(bprm, &effective, &has_cap); if (ret < 0) return ret; if (!issecure(SECURE_NOROOT)) { /* * If the legacy file capability is set, then don't set privs * for a setuid root binary run by a non-root user. Do set it * for a root user just to cause least surprise to an admin. */ if (has_cap && new->uid != 0 && new->euid == 0) { warn_setuid_and_fcaps_mixed(bprm->filename); goto skip; } /* * To support inheritance of root-permissions and suid-root * executables under compatibility mode, we override the * capability sets for the file. * * If only the real uid is 0, we do not set the effective bit. */ if (new->euid == 0 || new->uid == 0) { /* pP' = (cap_bset & ~0) | (pI & ~0) */ new->cap_permitted = cap_combine(old->cap_bset, old->cap_inheritable); } if (new->euid == 0) effective = true; } skip: /* if we have fs caps, clear dangerous personality flags */ if (!cap_issubset(new->cap_permitted, old->cap_permitted)) bprm->per_clear |= PER_CLEAR_ON_SETID; /* Don't let someone trace a set[ug]id/setpcap binary with the revised * credentials unless they have the appropriate permit */ if ((new->euid != old->uid || new->egid != old->gid || !cap_issubset(new->cap_permitted, old->cap_permitted)) && bprm->unsafe & ~LSM_UNSAFE_PTRACE_CAP) { /* downgrade; they get no more than they had, and maybe less */ if (!capable(CAP_SETUID)) { new->euid = new->uid; new->egid = new->gid; } new->cap_permitted = cap_intersect(new->cap_permitted, old->cap_permitted); } new->suid = new->fsuid = new->euid; new->sgid = new->fsgid = new->egid; if (effective) new->cap_effective = new->cap_permitted; else cap_clear(new->cap_effective); bprm->cap_effective = effective; /* * Audit candidate if current->cap_effective is set * * We do not bother to audit if 3 things are true: * 1) cap_effective has all caps * 2) we are root * 3) root is supposed to have all caps (SECURE_NOROOT) * Since this is just a normal root execing a process. * * Number 1 above might fail if you don't have a full bset, but I think * that is interesting information to audit. */ if (!cap_isclear(new->cap_effective)) { if (!cap_issubset(CAP_FULL_SET, new->cap_effective) || new->euid != 0 || new->uid != 0 || issecure(SECURE_NOROOT)) { ret = audit_log_bprm_fcaps(bprm, new, old); if (ret < 0) return ret; } } new->securebits &= ~issecure_mask(SECURE_KEEP_CAPS); return 0; }
165,616
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int svc_rdma_map_xdr(struct svcxprt_rdma *xprt, struct xdr_buf *xdr, struct svc_rdma_req_map *vec, bool write_chunk_present) { int sge_no; u32 sge_bytes; u32 page_bytes; u32 page_off; int page_no; if (xdr->len != (xdr->head[0].iov_len + xdr->page_len + xdr->tail[0].iov_len)) { pr_err("svcrdma: %s: XDR buffer length error\n", __func__); return -EIO; } /* Skip the first sge, this is for the RPCRDMA header */ sge_no = 1; /* Head SGE */ vec->sge[sge_no].iov_base = xdr->head[0].iov_base; vec->sge[sge_no].iov_len = xdr->head[0].iov_len; sge_no++; /* pages SGE */ page_no = 0; page_bytes = xdr->page_len; page_off = xdr->page_base; while (page_bytes) { vec->sge[sge_no].iov_base = page_address(xdr->pages[page_no]) + page_off; sge_bytes = min_t(u32, page_bytes, (PAGE_SIZE - page_off)); page_bytes -= sge_bytes; vec->sge[sge_no].iov_len = sge_bytes; sge_no++; page_no++; page_off = 0; /* reset for next time through loop */ } /* Tail SGE */ if (xdr->tail[0].iov_len) { unsigned char *base = xdr->tail[0].iov_base; size_t len = xdr->tail[0].iov_len; u32 xdr_pad = xdr_padsize(xdr->page_len); if (write_chunk_present && xdr_pad) { base += xdr_pad; len -= xdr_pad; } if (len) { vec->sge[sge_no].iov_base = base; vec->sge[sge_no].iov_len = len; sge_no++; } } dprintk("svcrdma: %s: sge_no %d page_no %d " "page_base %u page_len %u head_len %zu tail_len %zu\n", __func__, sge_no, page_no, xdr->page_base, xdr->page_len, xdr->head[0].iov_len, xdr->tail[0].iov_len); vec->count = sge_no; return 0; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
int svc_rdma_map_xdr(struct svcxprt_rdma *xprt, /* Returns length of transport header, in bytes. */ static unsigned int svc_rdma_reply_hdr_len(__be32 *rdma_resp) { unsigned int nsegs; __be32 *p; p = rdma_resp; /* RPC-over-RDMA V1 replies never have a Read list. */ p += rpcrdma_fixed_maxsz + 1; /* Skip Write list. */ while (*p++ != xdr_zero) { nsegs = be32_to_cpup(p++); p += nsegs * rpcrdma_segment_maxsz; } /* Skip Reply chunk. */ if (*p++ != xdr_zero) { nsegs = be32_to_cpup(p++); p += nsegs * rpcrdma_segment_maxsz; } return (unsigned long)p - (unsigned long)rdma_resp; } /* One Write chunk is copied from Call transport header to Reply * transport header. Each segment's length field is updated to * reflect number of bytes consumed in the segment. * * Returns number of segments in this chunk. */ static unsigned int xdr_encode_write_chunk(__be32 *dst, __be32 *src, unsigned int remaining) { unsigned int i, nsegs; u32 seg_len; /* Write list discriminator */ *dst++ = *src++; /* number of segments in this chunk */ nsegs = be32_to_cpup(src); *dst++ = *src++; for (i = nsegs; i; i--) { /* segment's RDMA handle */ *dst++ = *src++; /* bytes returned in this segment */ seg_len = be32_to_cpu(*src); if (remaining >= seg_len) { /* entire segment was consumed */ *dst = *src; remaining -= seg_len; } else { /* segment only partly filled */ *dst = cpu_to_be32(remaining); remaining = 0; } dst++; src++; /* segment's RDMA offset */ *dst++ = *src++; *dst++ = *src++; } return nsegs; }
168,173
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SubpelVarianceTest<SubpelVarianceFunctionType>::RefTest() { for (int x = 0; x < 16; ++x) { for (int y = 0; y < 16; ++y) { for (int j = 0; j < block_size_; j++) { src_[j] = rnd.Rand8(); } for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) { ref_[j] = rnd.Rand8(); } unsigned int sse1, sse2; unsigned int var1; REGISTER_STATE_CHECK(var1 = subpel_variance_(ref_, width_ + 1, x, y, src_, width_, &sse1)); const unsigned int var2 = subpel_variance_ref(ref_, src_, log2width_, log2height_, x, y, &sse2); EXPECT_EQ(sse1, sse2) << "at position " << x << ", " << y; EXPECT_EQ(var1, var2) << "at position " << x << ", " << y; } } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void SubpelVarianceTest<SubpelVarianceFunctionType>::RefTest() { for (int x = 0; x < 8; ++x) { for (int y = 0; y < 8; ++y) { if (!use_high_bit_depth_) { for (int j = 0; j < block_size_; j++) { src_[j] = rnd_.Rand8(); } for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) { ref_[j] = rnd_.Rand8(); } #if CONFIG_VP9_HIGHBITDEPTH } else { for (int j = 0; j < block_size_; j++) { CONVERT_TO_SHORTPTR(src_)[j] = rnd_.Rand16() & mask_; } for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) { CONVERT_TO_SHORTPTR(ref_)[j] = rnd_.Rand16() & mask_; } #endif // CONFIG_VP9_HIGHBITDEPTH } unsigned int sse1, sse2; unsigned int var1; ASM_REGISTER_STATE_CHECK(var1 = subpel_variance_(ref_, width_ + 1, x, y, src_, width_, &sse1)); const unsigned int var2 = subpel_variance_ref(ref_, src_, log2width_, log2height_, x, y, &sse2, use_high_bit_depth_, bit_depth_); EXPECT_EQ(sse1, sse2) << "at position " << x << ", " << y; EXPECT_EQ(var1, var2) << "at position " << x << ", " << y; } } }
174,587
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ip_send_reply(struct sock *sk, struct sk_buff *skb, struct ip_reply_arg *arg, unsigned int len) { struct inet_sock *inet = inet_sk(sk); struct { struct ip_options opt; char data[40]; } replyopts; struct ipcm_cookie ipc; __be32 daddr; struct rtable *rt = skb_rtable(skb); if (ip_options_echo(&replyopts.opt, skb)) return; daddr = ipc.addr = rt->rt_src; ipc.opt = NULL; ipc.tx_flags = 0; if (replyopts.opt.optlen) { ipc.opt = &replyopts.opt; if (ipc.opt->srr) daddr = replyopts.opt.faddr; } { struct flowi4 fl4; flowi4_init_output(&fl4, arg->bound_dev_if, 0, RT_TOS(ip_hdr(skb)->tos), RT_SCOPE_UNIVERSE, sk->sk_protocol, ip_reply_arg_flowi_flags(arg), daddr, rt->rt_spec_dst, tcp_hdr(skb)->source, tcp_hdr(skb)->dest); security_skb_classify_flow(skb, flowi4_to_flowi(&fl4)); rt = ip_route_output_key(sock_net(sk), &fl4); if (IS_ERR(rt)) return; } /* And let IP do all the hard work. This chunk is not reenterable, hence spinlock. Note that it uses the fact, that this function is called with locally disabled BH and that sk cannot be already spinlocked. */ bh_lock_sock(sk); inet->tos = ip_hdr(skb)->tos; sk->sk_priority = skb->priority; sk->sk_protocol = ip_hdr(skb)->protocol; sk->sk_bound_dev_if = arg->bound_dev_if; ip_append_data(sk, ip_reply_glue_bits, arg->iov->iov_base, len, 0, &ipc, &rt, MSG_DONTWAIT); if ((skb = skb_peek(&sk->sk_write_queue)) != NULL) { if (arg->csumoffset >= 0) *((__sum16 *)skb_transport_header(skb) + arg->csumoffset) = csum_fold(csum_add(skb->csum, arg->csum)); skb->ip_summed = CHECKSUM_NONE; ip_push_pending_frames(sk); } bh_unlock_sock(sk); ip_rt_put(rt); } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
void ip_send_reply(struct sock *sk, struct sk_buff *skb, struct ip_reply_arg *arg, unsigned int len) { struct inet_sock *inet = inet_sk(sk); struct ip_options_data replyopts; struct ipcm_cookie ipc; __be32 daddr; struct rtable *rt = skb_rtable(skb); if (ip_options_echo(&replyopts.opt.opt, skb)) return; daddr = ipc.addr = rt->rt_src; ipc.opt = NULL; ipc.tx_flags = 0; if (replyopts.opt.opt.optlen) { ipc.opt = &replyopts.opt; if (replyopts.opt.opt.srr) daddr = replyopts.opt.opt.faddr; } { struct flowi4 fl4; flowi4_init_output(&fl4, arg->bound_dev_if, 0, RT_TOS(ip_hdr(skb)->tos), RT_SCOPE_UNIVERSE, sk->sk_protocol, ip_reply_arg_flowi_flags(arg), daddr, rt->rt_spec_dst, tcp_hdr(skb)->source, tcp_hdr(skb)->dest); security_skb_classify_flow(skb, flowi4_to_flowi(&fl4)); rt = ip_route_output_key(sock_net(sk), &fl4); if (IS_ERR(rt)) return; } /* And let IP do all the hard work. This chunk is not reenterable, hence spinlock. Note that it uses the fact, that this function is called with locally disabled BH and that sk cannot be already spinlocked. */ bh_lock_sock(sk); inet->tos = ip_hdr(skb)->tos; sk->sk_priority = skb->priority; sk->sk_protocol = ip_hdr(skb)->protocol; sk->sk_bound_dev_if = arg->bound_dev_if; ip_append_data(sk, ip_reply_glue_bits, arg->iov->iov_base, len, 0, &ipc, &rt, MSG_DONTWAIT); if ((skb = skb_peek(&sk->sk_write_queue)) != NULL) { if (arg->csumoffset >= 0) *((__sum16 *)skb_transport_header(skb) + arg->csumoffset) = csum_fold(csum_add(skb->csum, arg->csum)); skb->ip_summed = CHECKSUM_NONE; ip_push_pending_frames(sk); } bh_unlock_sock(sk); ip_rt_put(rt); }
165,564
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void locationAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->location()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void locationAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); RefPtr<TestNode> imp = WTF::getPtr(proxyImp->location()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); }
171,685
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_siz_t *siz = &ms->parms.siz; unsigned int i; uint_fast8_t tmp; /* Eliminate compiler warning about unused variables. */ cstate = 0; if (jpc_getuint16(in, &siz->caps) || jpc_getuint32(in, &siz->width) || jpc_getuint32(in, &siz->height) || jpc_getuint32(in, &siz->xoff) || jpc_getuint32(in, &siz->yoff) || jpc_getuint32(in, &siz->tilewidth) || jpc_getuint32(in, &siz->tileheight) || jpc_getuint32(in, &siz->tilexoff) || jpc_getuint32(in, &siz->tileyoff) || jpc_getuint16(in, &siz->numcomps)) { return -1; } if (!siz->width || !siz->height || !siz->tilewidth || !siz->tileheight || !siz->numcomps) { return -1; } if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) { return -1; } for (i = 0; i < siz->numcomps; ++i) { if (jpc_getuint8(in, &tmp) || jpc_getuint8(in, &siz->comps[i].hsamp) || jpc_getuint8(in, &siz->comps[i].vsamp)) { jas_free(siz->comps); return -1; } siz->comps[i].sgnd = (tmp >> 7) & 1; siz->comps[i].prec = (tmp & 0x7f) + 1; } if (jas_stream_eof(in)) { jas_free(siz->comps); return -1; } return 0; } Commit Message: Added range check on XRsiz and YRsiz fields of SIZ marker segment. CWE ID: CWE-369
static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_siz_t *siz = &ms->parms.siz; unsigned int i; uint_fast8_t tmp; /* Eliminate compiler warning about unused variables. */ cstate = 0; if (jpc_getuint16(in, &siz->caps) || jpc_getuint32(in, &siz->width) || jpc_getuint32(in, &siz->height) || jpc_getuint32(in, &siz->xoff) || jpc_getuint32(in, &siz->yoff) || jpc_getuint32(in, &siz->tilewidth) || jpc_getuint32(in, &siz->tileheight) || jpc_getuint32(in, &siz->tilexoff) || jpc_getuint32(in, &siz->tileyoff) || jpc_getuint16(in, &siz->numcomps)) { return -1; } if (!siz->width || !siz->height || !siz->tilewidth || !siz->tileheight || !siz->numcomps) { return -1; } if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) { return -1; } for (i = 0; i < siz->numcomps; ++i) { if (jpc_getuint8(in, &tmp) || jpc_getuint8(in, &siz->comps[i].hsamp) || jpc_getuint8(in, &siz->comps[i].vsamp)) { jas_free(siz->comps); return -1; } if (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) { jas_eprintf("invalid XRsiz value %d\n", siz->comps[i].hsamp); jas_free(siz->comps); return -1; } if (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) { jas_eprintf("invalid YRsiz value %d\n", siz->comps[i].vsamp); jas_free(siz->comps); return -1; } siz->comps[i].sgnd = (tmp >> 7) & 1; siz->comps[i].prec = (tmp & 0x7f) + 1; } if (jas_stream_eof(in)) { jas_free(siz->comps); return -1; } return 0; }
168,760
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltAddTemplate(xsltStylesheetPtr style, xsltTemplatePtr cur, const xmlChar *mode, const xmlChar *modeURI) { xsltCompMatchPtr pat, list, next; /* * 'top' will point to style->xxxMatch ptr - declaring as 'void' * avoids gcc 'type-punned pointer' warning. */ void **top = NULL; const xmlChar *name = NULL; float priority; /* the priority */ if ((style == NULL) || (cur == NULL) || (cur->match == NULL)) return(-1); priority = cur->priority; pat = xsltCompilePatternInternal(cur->match, style->doc, cur->elem, style, NULL, 1); if (pat == NULL) return(-1); while (pat) { next = pat->next; pat->next = NULL; name = NULL; pat->template = cur; if (mode != NULL) pat->mode = xmlDictLookup(style->dict, mode, -1); if (modeURI != NULL) pat->modeURI = xmlDictLookup(style->dict, modeURI, -1); if (priority != XSLT_PAT_NO_PRIORITY) pat->priority = priority; /* * insert it in the hash table list corresponding to its lookup name */ switch (pat->steps[0].op) { case XSLT_OP_ATTR: if (pat->steps[0].value != NULL) name = pat->steps[0].value; else top = &(style->attrMatch); break; case XSLT_OP_PARENT: case XSLT_OP_ANCESTOR: top = &(style->elemMatch); break; case XSLT_OP_ROOT: top = &(style->rootMatch); break; case XSLT_OP_KEY: top = &(style->keyMatch); break; case XSLT_OP_ID: /* TODO optimize ID !!! */ case XSLT_OP_NS: case XSLT_OP_ALL: top = &(style->elemMatch); break; case XSLT_OP_END: case XSLT_OP_PREDICATE: xsltTransformError(NULL, style, NULL, "xsltAddTemplate: invalid compiled pattern\n"); xsltFreeCompMatch(pat); return(-1); /* * TODO: some flags at the top level about type based patterns * would be faster than inclusion in the hash table. */ case XSLT_OP_PI: if (pat->steps[0].value != NULL) name = pat->steps[0].value; else top = &(style->piMatch); break; case XSLT_OP_COMMENT: top = &(style->commentMatch); break; case XSLT_OP_TEXT: top = &(style->textMatch); break; case XSLT_OP_ELEM: case XSLT_OP_NODE: if (pat->steps[0].value != NULL) name = pat->steps[0].value; else top = &(style->elemMatch); break; } if (name != NULL) { if (style->templatesHash == NULL) { style->templatesHash = xmlHashCreate(1024); if (style->templatesHash == NULL) { xsltFreeCompMatch(pat); return(-1); } xmlHashAddEntry3(style->templatesHash, name, mode, modeURI, pat); } else { list = (xsltCompMatchPtr) xmlHashLookup3(style->templatesHash, name, mode, modeURI); if (list == NULL) { xmlHashAddEntry3(style->templatesHash, name, mode, modeURI, pat); } else { /* * Note '<=' since one must choose among the matching * template rules that are left, the one that occurs * last in the stylesheet */ if (list->priority <= pat->priority) { pat->next = list; xmlHashUpdateEntry3(style->templatesHash, name, mode, modeURI, pat, NULL); } else { while (list->next != NULL) { if (list->next->priority <= pat->priority) break; list = list->next; } pat->next = list->next; list->next = pat; } } } } else if (top != NULL) { list = *top; if (list == NULL) { *top = pat; pat->next = NULL; } else if (list->priority <= pat->priority) { pat->next = list; *top = pat; } else { while (list->next != NULL) { if (list->next->priority <= pat->priority) break; list = list->next; } pat->next = list->next; list->next = pat; } } else { xsltTransformError(NULL, style, NULL, "xsltAddTemplate: invalid compiled pattern\n"); xsltFreeCompMatch(pat); return(-1); } #ifdef WITH_XSLT_DEBUG_PATTERN if (mode) xsltGenericDebug(xsltGenericDebugContext, "added pattern : '%s' mode '%s' priority %f\n", pat->pattern, pat->mode, pat->priority); else xsltGenericDebug(xsltGenericDebugContext, "added pattern : '%s' priority %f\n", pat->pattern, pat->priority); #endif pat = next; } return(0); } 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
xsltAddTemplate(xsltStylesheetPtr style, xsltTemplatePtr cur, const xmlChar *mode, const xmlChar *modeURI) { xsltCompMatchPtr pat, list, next; /* * 'top' will point to style->xxxMatch ptr - declaring as 'void' * avoids gcc 'type-punned pointer' warning. */ void **top = NULL; const xmlChar *name = NULL; float priority; /* the priority */ if ((style == NULL) || (cur == NULL)) return(-1); /* Register named template */ if (cur->name != NULL) { if (style->namedTemplates == NULL) { style->namedTemplates = xmlHashCreate(10); if (style->namedTemplates == NULL) return(-1); } else { void *dup = xmlHashLookup2(style->namedTemplates, cur->name, cur->nameURI); if (dup != NULL) { xsltTransformError(NULL, style, NULL, "xsl:template: error duplicate name '%s'\n", cur->name); style->errors++; return(-1); } } xmlHashAddEntry2(style->namedTemplates, cur->name, cur->nameURI, cur); } if (cur->match == NULL) return(0); priority = cur->priority; pat = xsltCompilePatternInternal(cur->match, style->doc, cur->elem, style, NULL, 1); if (pat == NULL) return(-1); while (pat) { next = pat->next; pat->next = NULL; name = NULL; pat->template = cur; if (mode != NULL) pat->mode = xmlDictLookup(style->dict, mode, -1); if (modeURI != NULL) pat->modeURI = xmlDictLookup(style->dict, modeURI, -1); if (priority != XSLT_PAT_NO_PRIORITY) pat->priority = priority; /* * insert it in the hash table list corresponding to its lookup name */ switch (pat->steps[0].op) { case XSLT_OP_ATTR: if (pat->steps[0].value != NULL) name = pat->steps[0].value; else top = &(style->attrMatch); break; case XSLT_OP_PARENT: case XSLT_OP_ANCESTOR: top = &(style->elemMatch); break; case XSLT_OP_ROOT: top = &(style->rootMatch); break; case XSLT_OP_KEY: top = &(style->keyMatch); break; case XSLT_OP_ID: /* TODO optimize ID !!! */ case XSLT_OP_NS: case XSLT_OP_ALL: top = &(style->elemMatch); break; case XSLT_OP_END: case XSLT_OP_PREDICATE: xsltTransformError(NULL, style, NULL, "xsltAddTemplate: invalid compiled pattern\n"); xsltFreeCompMatch(pat); return(-1); /* * TODO: some flags at the top level about type based patterns * would be faster than inclusion in the hash table. */ case XSLT_OP_PI: if (pat->steps[0].value != NULL) name = pat->steps[0].value; else top = &(style->piMatch); break; case XSLT_OP_COMMENT: top = &(style->commentMatch); break; case XSLT_OP_TEXT: top = &(style->textMatch); break; case XSLT_OP_ELEM: case XSLT_OP_NODE: if (pat->steps[0].value != NULL) name = pat->steps[0].value; else top = &(style->elemMatch); break; } if (name != NULL) { if (style->templatesHash == NULL) { style->templatesHash = xmlHashCreate(1024); if (style->templatesHash == NULL) { xsltFreeCompMatch(pat); return(-1); } xmlHashAddEntry3(style->templatesHash, name, mode, modeURI, pat); } else { list = (xsltCompMatchPtr) xmlHashLookup3(style->templatesHash, name, mode, modeURI); if (list == NULL) { xmlHashAddEntry3(style->templatesHash, name, mode, modeURI, pat); } else { /* * Note '<=' since one must choose among the matching * template rules that are left, the one that occurs * last in the stylesheet */ if (list->priority <= pat->priority) { pat->next = list; xmlHashUpdateEntry3(style->templatesHash, name, mode, modeURI, pat, NULL); } else { while (list->next != NULL) { if (list->next->priority <= pat->priority) break; list = list->next; } pat->next = list->next; list->next = pat; } } } } else if (top != NULL) { list = *top; if (list == NULL) { *top = pat; pat->next = NULL; } else if (list->priority <= pat->priority) { pat->next = list; *top = pat; } else { while (list->next != NULL) { if (list->next->priority <= pat->priority) break; list = list->next; } pat->next = list->next; list->next = pat; } } else { xsltTransformError(NULL, style, NULL, "xsltAddTemplate: invalid compiled pattern\n"); xsltFreeCompMatch(pat); return(-1); } #ifdef WITH_XSLT_DEBUG_PATTERN if (mode) xsltGenericDebug(xsltGenericDebugContext, "added pattern : '%s' mode '%s' priority %f\n", pat->pattern, pat->mode, pat->priority); else xsltGenericDebug(xsltGenericDebugContext, "added pattern : '%s' priority %f\n", pat->pattern, pat->priority); #endif pat = next; } return(0); }
173,310
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PluginChannel::OnChannelError() { base::CloseProcessHandle(renderer_handle_); renderer_handle_ = 0; NPChannelBase::OnChannelError(); CleanUp(); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void PluginChannel::OnChannelError() { NPChannelBase::OnChannelError(); CleanUp(); }
170,949
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AccessControlStatus ScriptResource::CalculateAccessControlStatus() const { if (GetCORSStatus() == CORSStatus::kServiceWorkerOpaque) return kOpaqueResource; if (IsSameOriginOrCORSSuccessful()) return kSharableCrossOrigin; return kNotSharableCrossOrigin; } Commit Message: Check CORS using PassesAccessControlCheck() with supplied SecurityOrigin Partial revert of https://chromium-review.googlesource.com/535694. Bug: 799477 Change-Id: I878bb9bcb83afaafe8601293db9aa644fc5929b3 Reviewed-on: https://chromium-review.googlesource.com/898427 Commit-Queue: Hiroshige Hayashizaki <[email protected]> Reviewed-by: Kouhei Ueno <[email protected]> Reviewed-by: Yutaka Hirano <[email protected]> Reviewed-by: Takeshi Yoshino <[email protected]> Cr-Commit-Position: refs/heads/master@{#535176} CWE ID: CWE-200
AccessControlStatus ScriptResource::CalculateAccessControlStatus() const { AccessControlStatus ScriptResource::CalculateAccessControlStatus( const SecurityOrigin* security_origin) const { if (GetResponse().WasFetchedViaServiceWorker()) { if (GetCORSStatus() == CORSStatus::kServiceWorkerOpaque) return kOpaqueResource; return kSharableCrossOrigin; } if (security_origin && PassesAccessControlCheck(*security_origin)) return kSharableCrossOrigin; return kNotSharableCrossOrigin; }
172,889
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: zrestore(i_ctx_t *i_ctx_p) { os_ptr op = osp; alloc_save_t *asave; bool last; vm_save_t *vmsave; int code = restore_check_operand(op, &asave, idmemory); if (code < 0) return code; if_debug2m('u', imemory, "[u]vmrestore 0x%lx, id = %lu\n", (ulong) alloc_save_client_data(asave), (ulong) op->value.saveid); if (I_VALIDATE_BEFORE_RESTORE) ivalidate_clean_spaces(i_ctx_p); ivalidate_clean_spaces(i_ctx_p); /* Check the contents of the stacks. */ { int code; if ((code = restore_check_stack(i_ctx_p, &o_stack, asave, false)) < 0 || (code = restore_check_stack(i_ctx_p, &e_stack, asave, true)) < 0 || (code = restore_check_stack(i_ctx_p, &d_stack, asave, false)) < 0 ) { osp++; return code; } } /* Reset l_new in all stack entries if the new save level is zero. */ /* Also do some special fixing on the e-stack. */ restore_fix_stack(i_ctx_p, &o_stack, asave, false); } Commit Message: CWE ID: CWE-78
zrestore(i_ctx_t *i_ctx_p) restore_check_save(i_ctx_t *i_ctx_p, alloc_save_t **asave) { os_ptr op = osp; int code = restore_check_operand(op, asave, idmemory); if (code < 0) return code; if_debug2m('u', imemory, "[u]vmrestore 0x%lx, id = %lu\n", (ulong) alloc_save_client_data(*asave), (ulong) op->value.saveid); if (I_VALIDATE_BEFORE_RESTORE) ivalidate_clean_spaces(i_ctx_p); ivalidate_clean_spaces(i_ctx_p); /* Check the contents of the stacks. */ { int code; if ((code = restore_check_stack(i_ctx_p, &o_stack, *asave, false)) < 0 || (code = restore_check_stack(i_ctx_p, &e_stack, *asave, true)) < 0 || (code = restore_check_stack(i_ctx_p, &d_stack, *asave, false)) < 0 ) { osp++; return code; } } osp++; return 0; } /* the semantics of restore differ slightly between Level 1 and Level 2 and later - the latter includes restoring the device state (whilst Level 1 didn't have "page devices" as such). Hence we have two restore operators - one here (Level 1) and one in zdevice2.c (Level 2+). For that reason, the operand checking and guts of the restore operation are separated so both implementations can use them to best effect. */ int dorestore(i_ctx_t *i_ctx_p, alloc_save_t *asave) { os_ptr op = osp; bool last; vm_save_t *vmsave; int code; osp--; /* Reset l_new in all stack entries if the new save level is zero. */ /* Also do some special fixing on the e-stack. */ restore_fix_stack(i_ctx_p, &o_stack, asave, false); }
164,688
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DOMHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { host_ = frame_host; } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void DOMHandler::SetRenderer(RenderProcessHost* process_host, void DOMHandler::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { host_ = frame_host; }
172,745
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static unsigned int seedsize(struct crypto_alg *alg) { struct rng_alg *ralg = container_of(alg, struct rng_alg, base); return alg->cra_rng.rng_make_random ? alg->cra_rng.seedsize : ralg->seedsize; } Commit Message: crypto: rng - Remove old low-level rng interface Now that all rng implementations have switched over to the new interface, we can remove the old low-level interface. Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-476
static unsigned int seedsize(struct crypto_alg *alg) { struct rng_alg *ralg = container_of(alg, struct rng_alg, base); return ralg->seedsize; }
167,735
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: omx_vdec::omx_vdec(): m_error_propogated(false), m_state(OMX_StateInvalid), m_app_data(NULL), m_inp_mem_ptr(NULL), m_out_mem_ptr(NULL), input_flush_progress (false), output_flush_progress (false), input_use_buffer (false), output_use_buffer (false), ouput_egl_buffers(false), m_use_output_pmem(OMX_FALSE), m_out_mem_region_smi(OMX_FALSE), m_out_pvt_entry_pmem(OMX_FALSE), pending_input_buffers(0), pending_output_buffers(0), m_out_bm_count(0), m_inp_bm_count(0), m_inp_bPopulated(OMX_FALSE), m_out_bPopulated(OMX_FALSE), m_flags(0), #ifdef _ANDROID_ m_heap_ptr(NULL), #endif m_inp_bEnabled(OMX_TRUE), m_out_bEnabled(OMX_TRUE), m_in_alloc_cnt(0), m_platform_list(NULL), m_platform_entry(NULL), m_pmem_info(NULL), h264_parser(NULL), arbitrary_bytes (true), psource_frame (NULL), pdest_frame (NULL), m_inp_heap_ptr (NULL), m_phdr_pmem_ptr(NULL), m_heap_inp_bm_count (0), codec_type_parse ((codec_type)0), first_frame_meta (true), frame_count (0), nal_count (0), nal_length(0), look_ahead_nal (false), first_frame(0), first_buffer(NULL), first_frame_size (0), m_device_file_ptr(NULL), m_vc1_profile((vc1_profile_type)0), h264_last_au_ts(LLONG_MAX), h264_last_au_flags(0), m_disp_hor_size(0), m_disp_vert_size(0), prev_ts(LLONG_MAX), rst_prev_ts(true), frm_int(0), in_reconfig(false), m_display_id(NULL), client_extradata(0), m_reject_avc_1080p_mp (0), #ifdef _ANDROID_ m_enable_android_native_buffers(OMX_FALSE), m_use_android_native_buffers(OMX_FALSE), iDivXDrmDecrypt(NULL), #endif m_desc_buffer_ptr(NULL), secure_mode(false), m_other_extradata(NULL), m_profile(0), client_set_fps(false), m_last_rendered_TS(-1), m_queued_codec_config_count(0), secure_scaling_to_non_secure_opb(false) { /* Assumption is that , to begin with , we have all the frames with decoder */ DEBUG_PRINT_HIGH("In %u bit OMX vdec Constructor", (unsigned int)sizeof(long) * 8); memset(&m_debug,0,sizeof(m_debug)); #ifdef _ANDROID_ char property_value[PROPERTY_VALUE_MAX] = {0}; property_get("vidc.debug.level", property_value, "1"); debug_level = atoi(property_value); property_value[0] = '\0'; DEBUG_PRINT_HIGH("In OMX vdec Constructor"); property_get("vidc.dec.debug.perf", property_value, "0"); perf_flag = atoi(property_value); if (perf_flag) { DEBUG_PRINT_HIGH("vidc.dec.debug.perf is %d", perf_flag); dec_time.start(); proc_frms = latency = 0; } prev_n_filled_len = 0; property_value[0] = '\0'; property_get("vidc.dec.debug.ts", property_value, "0"); m_debug_timestamp = atoi(property_value); DEBUG_PRINT_HIGH("vidc.dec.debug.ts value is %d",m_debug_timestamp); if (m_debug_timestamp) { time_stamp_dts.set_timestamp_reorder_mode(true); time_stamp_dts.enable_debug_print(true); } property_value[0] = '\0'; property_get("vidc.dec.debug.concealedmb", property_value, "0"); m_debug_concealedmb = atoi(property_value); DEBUG_PRINT_HIGH("vidc.dec.debug.concealedmb value is %d",m_debug_concealedmb); property_value[0] = '\0'; property_get("vidc.dec.profile.check", property_value, "0"); m_reject_avc_1080p_mp = atoi(property_value); DEBUG_PRINT_HIGH("vidc.dec.profile.check value is %d",m_reject_avc_1080p_mp); property_value[0] = '\0'; property_get("vidc.dec.log.in", property_value, "0"); m_debug.in_buffer_log = atoi(property_value); property_value[0] = '\0'; property_get("vidc.dec.log.out", property_value, "0"); m_debug.out_buffer_log = atoi(property_value); sprintf(m_debug.log_loc, "%s", BUFFER_LOG_LOC); property_value[0] = '\0'; property_get("vidc.log.loc", property_value, ""); if (*property_value) strlcpy(m_debug.log_loc, property_value, PROPERTY_VALUE_MAX); property_value[0] = '\0'; property_get("vidc.dec.120fps.enabled", property_value, "0"); if(atoi(property_value)) { DEBUG_PRINT_LOW("feature 120 FPS decode enabled"); m_last_rendered_TS = 0; } property_value[0] = '\0'; property_get("vidc.dec.debug.dyn.disabled", property_value, "0"); m_disable_dynamic_buf_mode = atoi(property_value); DEBUG_PRINT_HIGH("vidc.dec.debug.dyn.disabled value is %d",m_disable_dynamic_buf_mode); #endif memset(&m_cmp,0,sizeof(m_cmp)); memset(&m_cb,0,sizeof(m_cb)); memset (&drv_ctx,0,sizeof(drv_ctx)); memset (&h264_scratch,0,sizeof (OMX_BUFFERHEADERTYPE)); memset (m_hwdevice_name,0,sizeof(m_hwdevice_name)); memset(m_demux_offsets, 0, ( sizeof(OMX_U32) * 8192) ); memset(&m_custom_buffersize, 0, sizeof(m_custom_buffersize)); m_demux_entries = 0; msg_thread_id = 0; async_thread_id = 0; msg_thread_created = false; async_thread_created = false; #ifdef _ANDROID_ICS_ memset(&native_buffer, 0 ,(sizeof(struct nativebuffer) * MAX_NUM_INPUT_OUTPUT_BUFFERS)); #endif memset(&drv_ctx.extradata_info, 0, sizeof(drv_ctx.extradata_info)); /* invalidate m_frame_pack_arrangement */ memset(&m_frame_pack_arrangement, 0, sizeof(OMX_QCOM_FRAME_PACK_ARRANGEMENT)); m_frame_pack_arrangement.cancel_flag = 1; drv_ctx.timestamp_adjust = false; drv_ctx.video_driver_fd = -1; m_vendor_config.pData = NULL; pthread_mutex_init(&m_lock, NULL); pthread_mutex_init(&c_lock, NULL); sem_init(&m_cmd_lock,0,0); sem_init(&m_safe_flush, 0, 0); streaming[CAPTURE_PORT] = streaming[OUTPUT_PORT] = false; #ifdef _ANDROID_ char extradata_value[PROPERTY_VALUE_MAX] = {0}; property_get("vidc.dec.debug.extradata", extradata_value, "0"); m_debug_extradata = atoi(extradata_value); DEBUG_PRINT_HIGH("vidc.dec.debug.extradata value is %d",m_debug_extradata); #endif m_fill_output_msg = OMX_COMPONENT_GENERATE_FTB; client_buffers.set_vdec_client(this); dynamic_buf_mode = false; out_dynamic_list = NULL; is_down_scalar_enabled = false; m_smoothstreaming_mode = false; m_smoothstreaming_width = 0; m_smoothstreaming_height = 0; is_q6_platform = false; } Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states (per the spec) ETB/FTB should not be handled in states other than Executing, Paused and Idle. This avoids accessing invalid buffers. Also add a lock to protect the private-buffers from being deleted while accessing from another thread. Bug: 27890802 Security Vulnerability - Heap Use-After-Free and Possible LPE in MediaServer (libOmxVdec problem #6) CRs-Fixed: 1008882 Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e CWE ID:
omx_vdec::omx_vdec(): m_error_propogated(false), m_state(OMX_StateInvalid), m_app_data(NULL), m_inp_mem_ptr(NULL), m_out_mem_ptr(NULL), input_flush_progress (false), output_flush_progress (false), input_use_buffer (false), output_use_buffer (false), ouput_egl_buffers(false), m_use_output_pmem(OMX_FALSE), m_out_mem_region_smi(OMX_FALSE), m_out_pvt_entry_pmem(OMX_FALSE), pending_input_buffers(0), pending_output_buffers(0), m_out_bm_count(0), m_inp_bm_count(0), m_inp_bPopulated(OMX_FALSE), m_out_bPopulated(OMX_FALSE), m_flags(0), #ifdef _ANDROID_ m_heap_ptr(NULL), #endif m_inp_bEnabled(OMX_TRUE), m_out_bEnabled(OMX_TRUE), m_in_alloc_cnt(0), m_platform_list(NULL), m_platform_entry(NULL), m_pmem_info(NULL), h264_parser(NULL), arbitrary_bytes (true), psource_frame (NULL), pdest_frame (NULL), m_inp_heap_ptr (NULL), m_phdr_pmem_ptr(NULL), m_heap_inp_bm_count (0), codec_type_parse ((codec_type)0), first_frame_meta (true), frame_count (0), nal_count (0), nal_length(0), look_ahead_nal (false), first_frame(0), first_buffer(NULL), first_frame_size (0), m_device_file_ptr(NULL), m_vc1_profile((vc1_profile_type)0), h264_last_au_ts(LLONG_MAX), h264_last_au_flags(0), m_disp_hor_size(0), m_disp_vert_size(0), prev_ts(LLONG_MAX), rst_prev_ts(true), frm_int(0), in_reconfig(false), m_display_id(NULL), client_extradata(0), m_reject_avc_1080p_mp (0), #ifdef _ANDROID_ m_enable_android_native_buffers(OMX_FALSE), m_use_android_native_buffers(OMX_FALSE), iDivXDrmDecrypt(NULL), #endif m_desc_buffer_ptr(NULL), secure_mode(false), m_other_extradata(NULL), m_profile(0), client_set_fps(false), m_last_rendered_TS(-1), m_queued_codec_config_count(0), secure_scaling_to_non_secure_opb(false) { /* Assumption is that , to begin with , we have all the frames with decoder */ DEBUG_PRINT_HIGH("In %u bit OMX vdec Constructor", (unsigned int)sizeof(long) * 8); memset(&m_debug,0,sizeof(m_debug)); #ifdef _ANDROID_ char property_value[PROPERTY_VALUE_MAX] = {0}; property_get("vidc.debug.level", property_value, "1"); debug_level = atoi(property_value); property_value[0] = '\0'; DEBUG_PRINT_HIGH("In OMX vdec Constructor"); property_get("vidc.dec.debug.perf", property_value, "0"); perf_flag = atoi(property_value); if (perf_flag) { DEBUG_PRINT_HIGH("vidc.dec.debug.perf is %d", perf_flag); dec_time.start(); proc_frms = latency = 0; } prev_n_filled_len = 0; property_value[0] = '\0'; property_get("vidc.dec.debug.ts", property_value, "0"); m_debug_timestamp = atoi(property_value); DEBUG_PRINT_HIGH("vidc.dec.debug.ts value is %d",m_debug_timestamp); if (m_debug_timestamp) { time_stamp_dts.set_timestamp_reorder_mode(true); time_stamp_dts.enable_debug_print(true); } property_value[0] = '\0'; property_get("vidc.dec.debug.concealedmb", property_value, "0"); m_debug_concealedmb = atoi(property_value); DEBUG_PRINT_HIGH("vidc.dec.debug.concealedmb value is %d",m_debug_concealedmb); property_value[0] = '\0'; property_get("vidc.dec.profile.check", property_value, "0"); m_reject_avc_1080p_mp = atoi(property_value); DEBUG_PRINT_HIGH("vidc.dec.profile.check value is %d",m_reject_avc_1080p_mp); property_value[0] = '\0'; property_get("vidc.dec.log.in", property_value, "0"); m_debug.in_buffer_log = atoi(property_value); property_value[0] = '\0'; property_get("vidc.dec.log.out", property_value, "0"); m_debug.out_buffer_log = atoi(property_value); sprintf(m_debug.log_loc, "%s", BUFFER_LOG_LOC); property_value[0] = '\0'; property_get("vidc.log.loc", property_value, ""); if (*property_value) strlcpy(m_debug.log_loc, property_value, PROPERTY_VALUE_MAX); property_value[0] = '\0'; property_get("vidc.dec.120fps.enabled", property_value, "0"); if(atoi(property_value)) { DEBUG_PRINT_LOW("feature 120 FPS decode enabled"); m_last_rendered_TS = 0; } property_value[0] = '\0'; property_get("vidc.dec.debug.dyn.disabled", property_value, "0"); m_disable_dynamic_buf_mode = atoi(property_value); DEBUG_PRINT_HIGH("vidc.dec.debug.dyn.disabled value is %d",m_disable_dynamic_buf_mode); #endif memset(&m_cmp,0,sizeof(m_cmp)); memset(&m_cb,0,sizeof(m_cb)); memset (&drv_ctx,0,sizeof(drv_ctx)); memset (&h264_scratch,0,sizeof (OMX_BUFFERHEADERTYPE)); memset (m_hwdevice_name,0,sizeof(m_hwdevice_name)); memset(m_demux_offsets, 0, ( sizeof(OMX_U32) * 8192) ); memset(&m_custom_buffersize, 0, sizeof(m_custom_buffersize)); m_demux_entries = 0; msg_thread_id = 0; async_thread_id = 0; msg_thread_created = false; async_thread_created = false; #ifdef _ANDROID_ICS_ memset(&native_buffer, 0 ,(sizeof(struct nativebuffer) * MAX_NUM_INPUT_OUTPUT_BUFFERS)); #endif memset(&drv_ctx.extradata_info, 0, sizeof(drv_ctx.extradata_info)); /* invalidate m_frame_pack_arrangement */ memset(&m_frame_pack_arrangement, 0, sizeof(OMX_QCOM_FRAME_PACK_ARRANGEMENT)); m_frame_pack_arrangement.cancel_flag = 1; drv_ctx.timestamp_adjust = false; drv_ctx.video_driver_fd = -1; m_vendor_config.pData = NULL; pthread_mutex_init(&m_lock, NULL); pthread_mutex_init(&c_lock, NULL); pthread_mutex_init(&buf_lock, NULL); sem_init(&m_cmd_lock,0,0); sem_init(&m_safe_flush, 0, 0); streaming[CAPTURE_PORT] = streaming[OUTPUT_PORT] = false; #ifdef _ANDROID_ char extradata_value[PROPERTY_VALUE_MAX] = {0}; property_get("vidc.dec.debug.extradata", extradata_value, "0"); m_debug_extradata = atoi(extradata_value); DEBUG_PRINT_HIGH("vidc.dec.debug.extradata value is %d",m_debug_extradata); #endif m_fill_output_msg = OMX_COMPONENT_GENERATE_FTB; client_buffers.set_vdec_client(this); dynamic_buf_mode = false; out_dynamic_list = NULL; is_down_scalar_enabled = false; m_smoothstreaming_mode = false; m_smoothstreaming_width = 0; m_smoothstreaming_height = 0; is_q6_platform = false; }
173,753
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ComponentControllerImpl::ComponentControllerImpl(WebContentRunner* runner) : runner_(runner), controller_binding_(this), frame_observer_binding_(this) { DCHECK(runner); } Commit Message: [fuchsia] Implement browser tests for WebRunner Context service. Tests may interact with the WebRunner FIDL services and the underlying browser objects for end to end testing of service and browser functionality. * Add a browser test launcher main() for WebRunner. * Add some simple navigation tests. * Wire up GoBack()/GoForward() FIDL calls. * Add embedded test server resources and initialization logic. * Add missing deletion & notification calls to BrowserContext dtor. * Use FIDL events for navigation state changes. * Bug fixes: ** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(), so that they may use the MessageLoop during teardown. ** Fix Frame dtor to allow for null WindowTreeHosts (headless case) ** Fix std::move logic in Frame ctor which lead to no WebContents observer being registered. Bug: 871594 Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac Reviewed-on: https://chromium-review.googlesource.com/1164539 Commit-Queue: Kevin Marshall <[email protected]> Reviewed-by: Wez <[email protected]> Reviewed-by: Fabrice de Gans-Riberi <[email protected]> Reviewed-by: Scott Violet <[email protected]> Cr-Commit-Position: refs/heads/master@{#584155} CWE ID: CWE-264
ComponentControllerImpl::ComponentControllerImpl(WebContentRunner* runner) : runner_(runner), controller_binding_(this) { DCHECK(runner); }
172,149
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool NuMediaExtractor::getTotalBitrate(int64_t *bitrate) const { if (mTotalBitrate >= 0) { *bitrate = mTotalBitrate; return true; } off64_t size; if (mDurationUs >= 0 && mDataSource->getSize(&size) == OK) { *bitrate = size * 8000000ll / mDurationUs; // in bits/sec return true; } return false; } Commit Message: Fix integer overflow and divide-by-zero Bug: 35763994 Test: ran CTS with and without fix Change-Id: If835e97ce578d4fa567e33e349e48fb7b2559e0e (cherry picked from commit 8538a603ef992e75f29336499cb783f3ec19f18c) CWE ID: CWE-190
bool NuMediaExtractor::getTotalBitrate(int64_t *bitrate) const { if (mTotalBitrate >= 0) { *bitrate = mTotalBitrate; return true; } off64_t size; if (mDurationUs > 0 && mDataSource->getSize(&size) == OK) { *bitrate = size * 8000000ll / mDurationUs; // in bits/sec return true; } return false; }
174,003
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void EventBindings::AttachFilteredEvent( const v8::FunctionCallbackInfo<v8::Value>& args) { CHECK_EQ(2, args.Length()); CHECK(args[0]->IsString()); CHECK(args[1]->IsObject()); std::string event_name = *v8::String::Utf8Value(args[0]); if (!context()->HasAccessOrThrowError(event_name)) return; std::unique_ptr<base::DictionaryValue> filter; { std::unique_ptr<content::V8ValueConverter> converter( content::V8ValueConverter::create()); std::unique_ptr<base::Value> filter_value(converter->FromV8Value( v8::Local<v8::Object>::Cast(args[1]), context()->v8_context())); if (!filter_value || !filter_value->IsType(base::Value::TYPE_DICTIONARY)) { args.GetReturnValue().Set(static_cast<int32_t>(-1)); return; } filter = base::DictionaryValue::From(std::move(filter_value)); } base::DictionaryValue* filter_weak = filter.get(); int id = g_event_filter.Get().AddEventMatcher( event_name, ParseEventMatcher(std::move(filter))); attached_matcher_ids_.insert(id); std::string extension_id = context()->GetExtensionID(); if (AddFilter(event_name, extension_id, *filter_weak)) { bool lazy = ExtensionFrameHelper::IsContextForEventPage(context()); content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener( extension_id, event_name, *filter_weak, lazy)); } args.GetReturnValue().Set(static_cast<int32_t>(id)); } Commit Message: Ignore filtered event if an event matcher cannot be added. BUG=625404 Review-Url: https://codereview.chromium.org/2236133002 Cr-Commit-Position: refs/heads/master@{#411472} CWE ID: CWE-416
void EventBindings::AttachFilteredEvent( const v8::FunctionCallbackInfo<v8::Value>& args) { CHECK_EQ(2, args.Length()); CHECK(args[0]->IsString()); CHECK(args[1]->IsObject()); std::string event_name = *v8::String::Utf8Value(args[0]); if (!context()->HasAccessOrThrowError(event_name)) return; std::unique_ptr<base::DictionaryValue> filter; { std::unique_ptr<content::V8ValueConverter> converter( content::V8ValueConverter::create()); std::unique_ptr<base::Value> filter_value(converter->FromV8Value( v8::Local<v8::Object>::Cast(args[1]), context()->v8_context())); if (!filter_value || !filter_value->IsType(base::Value::TYPE_DICTIONARY)) { args.GetReturnValue().Set(static_cast<int32_t>(-1)); return; } filter = base::DictionaryValue::From(std::move(filter_value)); } int id = g_event_filter.Get().AddEventMatcher( event_name, ParseEventMatcher(std::move(filter))); if (id == -1) { args.GetReturnValue().Set(static_cast<int32_t>(-1)); return; } attached_matcher_ids_.insert(id); const EventMatcher* matcher = g_event_filter.Get().GetEventMatcher(id); DCHECK(matcher); base::DictionaryValue* filter_weak = matcher->value(); std::string extension_id = context()->GetExtensionID(); if (AddFilter(event_name, extension_id, *filter_weak)) { bool lazy = ExtensionFrameHelper::IsContextForEventPage(context()); content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener( extension_id, event_name, *filter_weak, lazy)); } args.GetReturnValue().Set(static_cast<int32_t>(id)); }
172,060
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int klsi_105_get_line_state(struct usb_serial_port *port, unsigned long *line_state_p) { int rc; u8 *status_buf; __u16 status; dev_info(&port->serial->dev->dev, "sending SIO Poll request\n"); status_buf = kmalloc(KLSI_STATUSBUF_LEN, GFP_KERNEL); if (!status_buf) return -ENOMEM; status_buf[0] = 0xff; status_buf[1] = 0xff; rc = usb_control_msg(port->serial->dev, usb_rcvctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_POLL, USB_TYPE_VENDOR | USB_DIR_IN, 0, /* value */ 0, /* index */ status_buf, KLSI_STATUSBUF_LEN, 10000 ); if (rc < 0) dev_err(&port->dev, "Reading line status failed (error = %d)\n", rc); else { status = get_unaligned_le16(status_buf); dev_info(&port->serial->dev->dev, "read status %x %x\n", status_buf[0], status_buf[1]); *line_state_p = klsi_105_status2linestate(status); } kfree(status_buf); return rc; } Commit Message: USB: serial: kl5kusb105: fix line-state error handling The current implementation failed to detect short transfers when attempting to read the line state, and also, to make things worse, logged the content of the uninitialised heap transfer buffer. Fixes: abf492e7b3ae ("USB: kl5kusb105: fix DMA buffers on stack") Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable <[email protected]> Reviewed-by: Greg Kroah-Hartman <[email protected]> Signed-off-by: Johan Hovold <[email protected]> CWE ID: CWE-532
static int klsi_105_get_line_state(struct usb_serial_port *port, unsigned long *line_state_p) { int rc; u8 *status_buf; __u16 status; dev_info(&port->serial->dev->dev, "sending SIO Poll request\n"); status_buf = kmalloc(KLSI_STATUSBUF_LEN, GFP_KERNEL); if (!status_buf) return -ENOMEM; status_buf[0] = 0xff; status_buf[1] = 0xff; rc = usb_control_msg(port->serial->dev, usb_rcvctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_POLL, USB_TYPE_VENDOR | USB_DIR_IN, 0, /* value */ 0, /* index */ status_buf, KLSI_STATUSBUF_LEN, 10000 ); if (rc != KLSI_STATUSBUF_LEN) { dev_err(&port->dev, "reading line status failed: %d\n", rc); if (rc >= 0) rc = -EIO; } else { status = get_unaligned_le16(status_buf); dev_info(&port->serial->dev->dev, "read status %x %x\n", status_buf[0], status_buf[1]); *line_state_p = klsi_105_status2linestate(status); } kfree(status_buf); return rc; }
168,389
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MediaRecorder::MediaRecorder(const String16& opPackageName) : mSurfaceMediaSource(NULL) { ALOGV("constructor"); const sp<IMediaPlayerService>& service(getMediaPlayerService()); if (service != NULL) { mMediaRecorder = service->createMediaRecorder(opPackageName); } if (mMediaRecorder != NULL) { mCurrentState = MEDIA_RECORDER_IDLE; } doCleanUp(); } Commit Message: Don't use sp<>& because they may end up pointing to NULL after a NULL check was performed. Bug: 28166152 Change-Id: Iab2ea30395b620628cc6f3d067dd4f6fcda824fe CWE ID: CWE-476
MediaRecorder::MediaRecorder(const String16& opPackageName) : mSurfaceMediaSource(NULL) { ALOGV("constructor"); const sp<IMediaPlayerService> service(getMediaPlayerService()); if (service != NULL) { mMediaRecorder = service->createMediaRecorder(opPackageName); } if (mMediaRecorder != NULL) { mCurrentState = MEDIA_RECORDER_IDLE; } doCleanUp(); }
173,540
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ovl_fill_super(struct super_block *sb, void *data, int silent) { struct path lowerpath; struct path upperpath; struct path workpath; struct inode *root_inode; struct dentry *root_dentry; struct ovl_entry *oe; struct ovl_fs *ufs; struct kstatfs statfs; int err; err = -ENOMEM; ufs = kzalloc(sizeof(struct ovl_fs), GFP_KERNEL); if (!ufs) goto out; err = ovl_parse_opt((char *) data, &ufs->config); if (err) goto out_free_config; /* FIXME: workdir is not needed for a R/O mount */ err = -EINVAL; if (!ufs->config.upperdir || !ufs->config.lowerdir || !ufs->config.workdir) { pr_err("overlayfs: missing upperdir or lowerdir or workdir\n"); goto out_free_config; } err = -ENOMEM; oe = ovl_alloc_entry(); if (oe == NULL) goto out_free_config; err = ovl_mount_dir(ufs->config.upperdir, &upperpath); if (err) goto out_free_oe; err = ovl_mount_dir(ufs->config.lowerdir, &lowerpath); if (err) goto out_put_upperpath; err = ovl_mount_dir(ufs->config.workdir, &workpath); if (err) goto out_put_lowerpath; err = -EINVAL; if (!S_ISDIR(upperpath.dentry->d_inode->i_mode) || !S_ISDIR(lowerpath.dentry->d_inode->i_mode) || !S_ISDIR(workpath.dentry->d_inode->i_mode)) { pr_err("overlayfs: upperdir or lowerdir or workdir not a directory\n"); goto out_put_workpath; } if (upperpath.mnt != workpath.mnt) { pr_err("overlayfs: workdir and upperdir must reside under the same mount\n"); goto out_put_workpath; } if (!ovl_workdir_ok(workpath.dentry, upperpath.dentry)) { pr_err("overlayfs: workdir and upperdir must be separate subtrees\n"); goto out_put_workpath; } if (!ovl_is_allowed_fs_type(upperpath.dentry)) { pr_err("overlayfs: filesystem of upperdir is not supported\n"); goto out_put_workpath; } if (!ovl_is_allowed_fs_type(lowerpath.dentry)) { pr_err("overlayfs: filesystem of lowerdir is not supported\n"); goto out_put_workpath; } err = vfs_statfs(&lowerpath, &statfs); if (err) { pr_err("overlayfs: statfs failed on lowerpath\n"); goto out_put_workpath; } ufs->lower_namelen = statfs.f_namelen; ufs->upper_mnt = clone_private_mount(&upperpath); err = PTR_ERR(ufs->upper_mnt); if (IS_ERR(ufs->upper_mnt)) { pr_err("overlayfs: failed to clone upperpath\n"); goto out_put_workpath; } ufs->lower_mnt = clone_private_mount(&lowerpath); err = PTR_ERR(ufs->lower_mnt); if (IS_ERR(ufs->lower_mnt)) { pr_err("overlayfs: failed to clone lowerpath\n"); goto out_put_upper_mnt; } ufs->workdir = ovl_workdir_create(ufs->upper_mnt, workpath.dentry); err = PTR_ERR(ufs->workdir); if (IS_ERR(ufs->workdir)) { pr_err("overlayfs: failed to create directory %s/%s\n", ufs->config.workdir, OVL_WORKDIR_NAME); goto out_put_lower_mnt; } /* * Make lower_mnt R/O. That way fchmod/fchown on lower file * will fail instead of modifying lower fs. */ ufs->lower_mnt->mnt_flags |= MNT_READONLY; /* If the upper fs is r/o, we mark overlayfs r/o too */ if (ufs->upper_mnt->mnt_sb->s_flags & MS_RDONLY) sb->s_flags |= MS_RDONLY; sb->s_d_op = &ovl_dentry_operations; err = -ENOMEM; root_inode = ovl_new_inode(sb, S_IFDIR, oe); if (!root_inode) goto out_put_workdir; root_dentry = d_make_root(root_inode); if (!root_dentry) goto out_put_workdir; mntput(upperpath.mnt); mntput(lowerpath.mnt); path_put(&workpath); oe->__upperdentry = upperpath.dentry; oe->lowerdentry = lowerpath.dentry; root_dentry->d_fsdata = oe; sb->s_magic = OVERLAYFS_SUPER_MAGIC; sb->s_op = &ovl_super_operations; sb->s_root = root_dentry; sb->s_fs_info = ufs; return 0; out_put_workdir: dput(ufs->workdir); out_put_lower_mnt: mntput(ufs->lower_mnt); out_put_upper_mnt: mntput(ufs->upper_mnt); out_put_workpath: path_put(&workpath); out_put_lowerpath: path_put(&lowerpath); out_put_upperpath: path_put(&upperpath); out_free_oe: kfree(oe); out_free_config: kfree(ufs->config.lowerdir); kfree(ufs->config.upperdir); kfree(ufs->config.workdir); kfree(ufs); out: return err; } Commit Message: fs: limit filesystem stacking depth Add a simple read-only counter to super_block that indicates how deep this is in the stack of filesystems. Previously ecryptfs was the only stackable filesystem and it explicitly disallowed multiple layers of itself. Overlayfs, however, can be stacked recursively and also may be stacked on top of ecryptfs or vice versa. To limit the kernel stack usage we must limit the depth of the filesystem stack. Initially the limit is set to 2. Signed-off-by: Miklos Szeredi <[email protected]> CWE ID: CWE-264
static int ovl_fill_super(struct super_block *sb, void *data, int silent) { struct path lowerpath; struct path upperpath; struct path workpath; struct inode *root_inode; struct dentry *root_dentry; struct ovl_entry *oe; struct ovl_fs *ufs; struct kstatfs statfs; int err; err = -ENOMEM; ufs = kzalloc(sizeof(struct ovl_fs), GFP_KERNEL); if (!ufs) goto out; err = ovl_parse_opt((char *) data, &ufs->config); if (err) goto out_free_config; /* FIXME: workdir is not needed for a R/O mount */ err = -EINVAL; if (!ufs->config.upperdir || !ufs->config.lowerdir || !ufs->config.workdir) { pr_err("overlayfs: missing upperdir or lowerdir or workdir\n"); goto out_free_config; } err = -ENOMEM; oe = ovl_alloc_entry(); if (oe == NULL) goto out_free_config; err = ovl_mount_dir(ufs->config.upperdir, &upperpath); if (err) goto out_free_oe; err = ovl_mount_dir(ufs->config.lowerdir, &lowerpath); if (err) goto out_put_upperpath; err = ovl_mount_dir(ufs->config.workdir, &workpath); if (err) goto out_put_lowerpath; err = -EINVAL; if (!S_ISDIR(upperpath.dentry->d_inode->i_mode) || !S_ISDIR(lowerpath.dentry->d_inode->i_mode) || !S_ISDIR(workpath.dentry->d_inode->i_mode)) { pr_err("overlayfs: upperdir or lowerdir or workdir not a directory\n"); goto out_put_workpath; } if (upperpath.mnt != workpath.mnt) { pr_err("overlayfs: workdir and upperdir must reside under the same mount\n"); goto out_put_workpath; } if (!ovl_workdir_ok(workpath.dentry, upperpath.dentry)) { pr_err("overlayfs: workdir and upperdir must be separate subtrees\n"); goto out_put_workpath; } if (!ovl_is_allowed_fs_type(upperpath.dentry)) { pr_err("overlayfs: filesystem of upperdir is not supported\n"); goto out_put_workpath; } if (!ovl_is_allowed_fs_type(lowerpath.dentry)) { pr_err("overlayfs: filesystem of lowerdir is not supported\n"); goto out_put_workpath; } err = vfs_statfs(&lowerpath, &statfs); if (err) { pr_err("overlayfs: statfs failed on lowerpath\n"); goto out_put_workpath; } ufs->lower_namelen = statfs.f_namelen; sb->s_stack_depth = max(upperpath.mnt->mnt_sb->s_stack_depth, lowerpath.mnt->mnt_sb->s_stack_depth) + 1; err = -EINVAL; if (sb->s_stack_depth > FILESYSTEM_MAX_STACK_DEPTH) { pr_err("overlayfs: maximum fs stacking depth exceeded\n"); goto out_put_workpath; } ufs->upper_mnt = clone_private_mount(&upperpath); err = PTR_ERR(ufs->upper_mnt); if (IS_ERR(ufs->upper_mnt)) { pr_err("overlayfs: failed to clone upperpath\n"); goto out_put_workpath; } ufs->lower_mnt = clone_private_mount(&lowerpath); err = PTR_ERR(ufs->lower_mnt); if (IS_ERR(ufs->lower_mnt)) { pr_err("overlayfs: failed to clone lowerpath\n"); goto out_put_upper_mnt; } ufs->workdir = ovl_workdir_create(ufs->upper_mnt, workpath.dentry); err = PTR_ERR(ufs->workdir); if (IS_ERR(ufs->workdir)) { pr_err("overlayfs: failed to create directory %s/%s\n", ufs->config.workdir, OVL_WORKDIR_NAME); goto out_put_lower_mnt; } /* * Make lower_mnt R/O. That way fchmod/fchown on lower file * will fail instead of modifying lower fs. */ ufs->lower_mnt->mnt_flags |= MNT_READONLY; /* If the upper fs is r/o, we mark overlayfs r/o too */ if (ufs->upper_mnt->mnt_sb->s_flags & MS_RDONLY) sb->s_flags |= MS_RDONLY; sb->s_d_op = &ovl_dentry_operations; err = -ENOMEM; root_inode = ovl_new_inode(sb, S_IFDIR, oe); if (!root_inode) goto out_put_workdir; root_dentry = d_make_root(root_inode); if (!root_dentry) goto out_put_workdir; mntput(upperpath.mnt); mntput(lowerpath.mnt); path_put(&workpath); oe->__upperdentry = upperpath.dentry; oe->lowerdentry = lowerpath.dentry; root_dentry->d_fsdata = oe; sb->s_magic = OVERLAYFS_SUPER_MAGIC; sb->s_op = &ovl_super_operations; sb->s_root = root_dentry; sb->s_fs_info = ufs; return 0; out_put_workdir: dput(ufs->workdir); out_put_lower_mnt: mntput(ufs->lower_mnt); out_put_upper_mnt: mntput(ufs->upper_mnt); out_put_workpath: path_put(&workpath); out_put_lowerpath: path_put(&lowerpath); out_put_upperpath: path_put(&upperpath); out_free_oe: kfree(oe); out_free_config: kfree(ufs->config.lowerdir); kfree(ufs->config.upperdir); kfree(ufs->config.workdir); kfree(ufs); out: return err; }
168,896
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AvailableSpaceQueryTask( QuotaManager* manager, const AvailableSpaceCallback& callback) : QuotaThreadTask(manager, manager->db_thread_), profile_path_(manager->profile_path_), space_(-1), get_disk_space_fn_(manager->get_disk_space_fn_), callback_(callback) { DCHECK(get_disk_space_fn_); } Commit Message: Wipe out QuotaThreadTask. This is a one of a series of refactoring patches for QuotaManager. http://codereview.chromium.org/10872054/ http://codereview.chromium.org/10917060/ BUG=139270 Review URL: https://chromiumcodereview.appspot.com/10919070 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@154987 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
AvailableSpaceQueryTask(
170,668
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sp<MediaSource> MPEG4Extractor::getTrack(size_t index) { status_t err; if ((err = readMetaData()) != OK) { return NULL; } Track *track = mFirstTrack; while (index > 0) { if (track == NULL) { return NULL; } track = track->next; --index; } if (track == NULL) { return NULL; } Trex *trex = NULL; int32_t trackId; if (track->meta->findInt32(kKeyTrackID, &trackId)) { for (size_t i = 0; i < mTrex.size(); i++) { Trex *t = &mTrex.editItemAt(index); if (t->track_ID == (uint32_t) trackId) { trex = t; break; } } } ALOGV("getTrack called, pssh: %zu", mPssh.size()); return new MPEG4Source(this, track->meta, mDataSource, track->timescale, track->sampleTable, mSidxEntries, trex, mMoofOffset); } Commit Message: MPEG4Extractor: ensure kKeyTrackID exists before creating an MPEG4Source as track. GenericSource: return error when no track exists. SampleIterator: make sure mSamplesPerChunk is not zero before using it as divisor. Bug: 21657957 Bug: 23705695 Bug: 22802344 Bug: 28799341 Change-Id: I7664992ade90b935d3f255dcd43ecc2898f30b04 (cherry picked from commit 0386c91b8a910a134e5898ffa924c1b6c7560b13) CWE ID: CWE-119
sp<MediaSource> MPEG4Extractor::getTrack(size_t index) { status_t err; if ((err = readMetaData()) != OK) { return NULL; } Track *track = mFirstTrack; while (index > 0) { if (track == NULL) { return NULL; } track = track->next; --index; } if (track == NULL) { return NULL; } Trex *trex = NULL; int32_t trackId; if (track->meta->findInt32(kKeyTrackID, &trackId)) { for (size_t i = 0; i < mTrex.size(); i++) { Trex *t = &mTrex.editItemAt(index); if (t->track_ID == (uint32_t) trackId) { trex = t; break; } } } else { ALOGE("b/21657957"); return NULL; } ALOGV("getTrack called, pssh: %zu", mPssh.size()); return new MPEG4Source(this, track->meta, mDataSource, track->timescale, track->sampleTable, mSidxEntries, trex, mMoofOffset); }
173,764
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Chapters::Edition::ParseAtom( IMkvReader* pReader, long long pos, long long size) { if (!ExpandAtomsArray()) return -1; Atom& a = m_atoms[m_atoms_count++]; a.Init(); return a.Parse(pReader, pos, size); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Chapters::Edition::ParseAtom( SegmentInfo::~SegmentInfo() { delete[] m_pMuxingAppAsUTF8; m_pMuxingAppAsUTF8 = NULL; delete[] m_pWritingAppAsUTF8; m_pWritingAppAsUTF8 = NULL; delete[] m_pTitleAsUTF8; m_pTitleAsUTF8 = NULL; }
174,415
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ApiTestEnvironment::RegisterModules() { v8_schema_registry_.reset(new V8SchemaRegistry); const std::vector<std::pair<std::string, int> > resources = Dispatcher::GetJsResources(); for (std::vector<std::pair<std::string, int> >::const_iterator resource = resources.begin(); resource != resources.end(); ++resource) { if (resource->first != "test_environment_specific_bindings") env()->RegisterModule(resource->first, resource->second); } Dispatcher::RegisterNativeHandlers(env()->module_system(), env()->context(), NULL, NULL, v8_schema_registry_.get()); env()->module_system()->RegisterNativeHandler( "process", scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler( env()->context(), env()->context()->GetExtensionID(), env()->context()->GetContextTypeDescription(), false, false, 2, false))); env()->RegisterTestFile("test_environment_specific_bindings", "unit_test_environment_specific_bindings.js"); env()->OverrideNativeHandler("activityLogger", "exports.LogAPICall = function() {};"); env()->OverrideNativeHandler( "apiDefinitions", "exports.GetExtensionAPIDefinitionsForTest = function() { return [] };"); env()->OverrideNativeHandler( "event_natives", "exports.AttachEvent = function() {};" "exports.DetachEvent = function() {};" "exports.AttachFilteredEvent = function() {};" "exports.AttachFilteredEvent = function() {};" "exports.MatchAgainstEventFilter = function() { return [] };"); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), mojo::js::Core::kModuleName, mojo::js::Core::GetModule(env()->isolate())); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), mojo::js::Support::kModuleName, mojo::js::Support::GetModule(env()->isolate())); gin::Handle<TestServiceProvider> service_provider = TestServiceProvider::Create(env()->isolate()); service_provider_ = service_provider.get(); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), "content/public/renderer/service_provider", service_provider.ToV8()); } Commit Message: [Extensions] Don't allow built-in extensions code to be overridden BUG=546677 Review URL: https://codereview.chromium.org/1417513003 Cr-Commit-Position: refs/heads/master@{#356654} CWE ID: CWE-264
void ApiTestEnvironment::RegisterModules() { v8_schema_registry_.reset(new V8SchemaRegistry); const std::vector<std::pair<std::string, int> > resources = Dispatcher::GetJsResources(); for (std::vector<std::pair<std::string, int> >::const_iterator resource = resources.begin(); resource != resources.end(); ++resource) { if (resource->first != "test_environment_specific_bindings") env()->RegisterModule(resource->first, resource->second); } Dispatcher::RegisterNativeHandlers(env()->module_system(), env()->context(), NULL, NULL, v8_schema_registry_.get()); env()->module_system()->RegisterNativeHandler( "process", scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler( env()->context(), env()->context()->GetExtensionID(), env()->context()->GetContextTypeDescription(), false, false, 2, false))); env()->RegisterTestFile("test_environment_specific_bindings", "unit_test_environment_specific_bindings.js"); env()->OverrideNativeHandler("activityLogger", "exports.$set('LogAPICall', function() {});"); env()->OverrideNativeHandler( "apiDefinitions", "exports.$set('GetExtensionAPIDefinitionsForTest'," "function() { return [] });"); env()->OverrideNativeHandler( "event_natives", "exports.$set('AttachEvent', function() {});" "exports.$set('DetachEvent', function() {});" "exports.$set('AttachFilteredEvent', function() {});" "exports.$set('AttachFilteredEvent', function() {});" "exports.$set('MatchAgainstEventFilter', function() { return [] });"); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), mojo::js::Core::kModuleName, mojo::js::Core::GetModule(env()->isolate())); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), mojo::js::Support::kModuleName, mojo::js::Support::GetModule(env()->isolate())); gin::Handle<TestServiceProvider> service_provider = TestServiceProvider::Create(env()->isolate()); service_provider_ = service_provider.get(); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), "content/public/renderer/service_provider", service_provider.ToV8()); }
172,286
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AddPolicyForRenderer(sandbox::TargetPolicy* policy) { sandbox::ResultCode result; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) { NOTREACHED(); return false; } policy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0); sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED; if (base::win::GetVersion() > base::win::VERSION_XP) { initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS; } policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN); policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAltWinstation); if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) { DLOG(WARNING) << "Failed to apply desktop security to the renderer"; } AddGenericDllEvictionPolicy(policy); return true; } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool AddPolicyForRenderer(sandbox::TargetPolicy* policy) { // Renderers need to copy sections for plugin DIBs and GPU. sandbox::ResultCode result; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) return false; // Renderers need to share events with plugins. result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Event"); if (result != sandbox::SBOX_ALL_OK) return false; policy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0); sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED; if (base::win::GetVersion() > base::win::VERSION_XP) { initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS; } policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN); policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAltWinstation); if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) { DLOG(WARNING) << "Failed to apply desktop security to the renderer"; } AddGenericDllEvictionPolicy(policy); return true; }
170,945
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static pfunc check_literal(struct jv_parser* p) { if (p->tokenpos == 0) return 0; const char* pattern = 0; int plen; jv v; switch (p->tokenbuf[0]) { case 't': pattern = "true"; plen = 4; v = jv_true(); break; case 'f': pattern = "false"; plen = 5; v = jv_false(); break; case 'n': pattern = "null"; plen = 4; v = jv_null(); break; } if (pattern) { if (p->tokenpos != plen) return "Invalid literal"; for (int i=0; i<plen; i++) if (p->tokenbuf[i] != pattern[i]) return "Invalid literal"; TRY(value(p, v)); } else { p->tokenbuf[p->tokenpos] = 0; // FIXME: invalid char* end = 0; double d = jvp_strtod(&p->dtoa, p->tokenbuf, &end); if (end == 0 || *end != 0) return "Invalid numeric literal"; TRY(value(p, jv_number(d))); } p->tokenpos = 0; return 0; } Commit Message: Heap buffer overflow in tokenadd() (fix #105) This was an off-by one: the NUL terminator byte was not allocated on resize. This was triggered by JSON-encoded numbers longer than 256 bytes. CWE ID: CWE-119
static pfunc check_literal(struct jv_parser* p) { if (p->tokenpos == 0) return 0; const char* pattern = 0; int plen; jv v; switch (p->tokenbuf[0]) { case 't': pattern = "true"; plen = 4; v = jv_true(); break; case 'f': pattern = "false"; plen = 5; v = jv_false(); break; case 'n': pattern = "null"; plen = 4; v = jv_null(); break; } if (pattern) { if (p->tokenpos != plen) return "Invalid literal"; for (int i=0; i<plen; i++) if (p->tokenbuf[i] != pattern[i]) return "Invalid literal"; TRY(value(p, v)); } else { p->tokenbuf[p->tokenpos] = 0; char* end = 0; double d = jvp_strtod(&p->dtoa, p->tokenbuf, &end); if (end == 0 || *end != 0) return "Invalid numeric literal"; TRY(value(p, jv_number(d))); } p->tokenpos = 0; return 0; }
167,476
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: XineramaXvShmPutImage(ClientPtr client) { REQUEST(xvShmPutImageReq); PanoramiXRes *draw, *gc, *port; Bool send_event = stuff->send_event; Bool isRoot; int result, i, x, y; REQUEST_SIZE_MATCH(xvShmPutImageReq); result = dixLookupResourceByClass((void **) &draw, stuff->drawable, XRC_DRAWABLE, client, DixWriteAccess); if (result != Success) result = dixLookupResourceByType((void **) &gc, stuff->gc, XRT_GC, client, DixReadAccess); if (result != Success) return result; result = dixLookupResourceByType((void **) &port, stuff->port, XvXRTPort, client, DixReadAccess); if (result != Success) return result; isRoot = (draw->type == XRT_WINDOW) && draw->u.win.root; x = stuff->drw_x; y = stuff->drw_y; FOR_NSCREENS_BACKWARD(i) { if (port->info[i].id) { stuff->drawable = draw->info[i].id; stuff->port = port->info[i].id; stuff->gc = gc->info[i].id; stuff->drw_x = x; stuff->drw_y = y; if (isRoot) { stuff->drw_x -= screenInfo.screens[i]->x; stuff->drw_y -= screenInfo.screens[i]->y; } stuff->send_event = (send_event && !i) ? 1 : 0; result = ProcXvShmPutImage(client); } } return result; } Commit Message: CWE ID: CWE-20
XineramaXvShmPutImage(ClientPtr client) { REQUEST(xvShmPutImageReq); PanoramiXRes *draw, *gc, *port; Bool send_event; Bool isRoot; int result, i, x, y; REQUEST_SIZE_MATCH(xvShmPutImageReq); send_event = stuff->send_event; result = dixLookupResourceByClass((void **) &draw, stuff->drawable, XRC_DRAWABLE, client, DixWriteAccess); if (result != Success) result = dixLookupResourceByType((void **) &gc, stuff->gc, XRT_GC, client, DixReadAccess); if (result != Success) return result; result = dixLookupResourceByType((void **) &port, stuff->port, XvXRTPort, client, DixReadAccess); if (result != Success) return result; isRoot = (draw->type == XRT_WINDOW) && draw->u.win.root; x = stuff->drw_x; y = stuff->drw_y; FOR_NSCREENS_BACKWARD(i) { if (port->info[i].id) { stuff->drawable = draw->info[i].id; stuff->port = port->info[i].id; stuff->gc = gc->info[i].id; stuff->drw_x = x; stuff->drw_y = y; if (isRoot) { stuff->drw_x -= screenInfo.screens[i]->x; stuff->drw_y -= screenInfo.screens[i]->y; } stuff->send_event = (send_event && !i) ? 1 : 0; result = ProcXvShmPutImage(client); } } return result; }
165,436
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: EC_KEY *d2i_ECPrivateKey(EC_KEY **a, const unsigned char **in, long len) { int ok = 0; EC_KEY *ret = NULL; EC_PRIVATEKEY *priv_key = NULL; if ((priv_key = EC_PRIVATEKEY_new()) == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE); return NULL; } if ((priv_key = d2i_EC_PRIVATEKEY(&priv_key, in, len)) == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB); EC_PRIVATEKEY_free(priv_key); return NULL; } if (a == NULL || *a == NULL) { if ((ret = EC_KEY_new()) == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE); goto err; } if (a) *a = ret; } else ret = *a; ret = *a; if (priv_key->parameters) { if (ret->group) EC_GROUP_clear_free(ret->group); ret->group = ec_asn1_pkparameters2group(priv_key->parameters); } if (ret->group == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB); goto err; } ret->version = priv_key->version; if (priv_key->privateKey) { ret->priv_key = BN_bin2bn(M_ASN1_STRING_data(priv_key->privateKey), M_ASN1_STRING_length(priv_key->privateKey), ret->priv_key); if (ret->priv_key == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_BN_LIB); goto err; } } else { ECerr(EC_F_D2I_ECPRIVATEKEY, EC_R_MISSING_PRIVATE_KEY); goto err; } if (priv_key->publicKey) { const unsigned char *pub_oct; size_t pub_oct_len; if (ret->pub_key) EC_POINT_clear_free(ret->pub_key); ret->pub_key = EC_POINT_new(ret->group); if (ret->pub_key == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB); goto err; } pub_oct = M_ASN1_STRING_data(priv_key->publicKey); pub_oct_len = M_ASN1_STRING_length(priv_key->publicKey); /* save the point conversion form */ ret->conv_form = (point_conversion_form_t) (pub_oct[0] & ~0x01); if (!EC_POINT_oct2point(ret->group, ret->pub_key, pub_oct, pub_oct_len, NULL)) { } } ok = 1; err: if (!ok) { if (ret) EC_KEY_free(ret); ret = NULL; } if (priv_key) EC_PRIVATEKEY_free(priv_key); return (ret); } Commit Message: CWE ID:
EC_KEY *d2i_ECPrivateKey(EC_KEY **a, const unsigned char **in, long len) { int ok = 0; EC_KEY *ret = NULL; EC_PRIVATEKEY *priv_key = NULL; if ((priv_key = EC_PRIVATEKEY_new()) == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE); return NULL; } if ((priv_key = d2i_EC_PRIVATEKEY(&priv_key, in, len)) == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB); EC_PRIVATEKEY_free(priv_key); return NULL; } if (a == NULL || *a == NULL) { if ((ret = EC_KEY_new()) == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE); goto err; } } else ret = *a; ret = *a; if (priv_key->parameters) { if (ret->group) EC_GROUP_clear_free(ret->group); ret->group = ec_asn1_pkparameters2group(priv_key->parameters); } if (ret->group == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB); goto err; } ret->version = priv_key->version; if (priv_key->privateKey) { ret->priv_key = BN_bin2bn(M_ASN1_STRING_data(priv_key->privateKey), M_ASN1_STRING_length(priv_key->privateKey), ret->priv_key); if (ret->priv_key == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_BN_LIB); goto err; } } else { ECerr(EC_F_D2I_ECPRIVATEKEY, EC_R_MISSING_PRIVATE_KEY); goto err; } if (priv_key->publicKey) { const unsigned char *pub_oct; size_t pub_oct_len; if (ret->pub_key) EC_POINT_clear_free(ret->pub_key); ret->pub_key = EC_POINT_new(ret->group); if (ret->pub_key == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB); goto err; } pub_oct = M_ASN1_STRING_data(priv_key->publicKey); pub_oct_len = M_ASN1_STRING_length(priv_key->publicKey); /* save the point conversion form */ ret->conv_form = (point_conversion_form_t) (pub_oct[0] & ~0x01); if (!EC_POINT_oct2point(ret->group, ret->pub_key, pub_oct, pub_oct_len, NULL)) { } } if (a) *a = ret; ok = 1; err: if (!ok) { if (ret && (a == NULL || *a != ret)) EC_KEY_free(ret); ret = NULL; } if (priv_key) EC_PRIVATEKEY_free(priv_key); return (ret); }
164,819
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CairoOutputDev::drawMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, Stream *maskStr, int maskWidth, int maskHeight, GBool maskInvert) { ImageStream *maskImgStr; maskImgStr = new ImageStream(maskStr, maskWidth, 1, 1); maskImgStr->reset(); int row_stride = (maskWidth + 3) & ~3; unsigned char *maskBuffer; maskBuffer = (unsigned char *)gmalloc (row_stride * maskHeight); unsigned char *maskDest; cairo_surface_t *maskImage; cairo_pattern_t *maskPattern; Guchar *pix; int x, y; int invert_bit; invert_bit = maskInvert ? 1 : 0; for (y = 0; y < maskHeight; y++) { pix = maskImgStr->getLine(); maskDest = maskBuffer + y * row_stride; for (x = 0; x < maskWidth; x++) { if (pix[x] ^ invert_bit) *maskDest++ = 0; else *maskDest++ = 255; } } maskImage = cairo_image_surface_create_for_data (maskBuffer, CAIRO_FORMAT_A8, maskWidth, maskHeight, row_stride); delete maskImgStr; maskStr->close(); unsigned char *buffer; unsigned int *dest; cairo_surface_t *image; cairo_pattern_t *pattern; ImageStream *imgStr; cairo_matrix_t matrix; int is_identity_transform; buffer = (unsigned char *)gmalloc (width * height * 4); /* TODO: Do we want to cache these? */ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgStr->reset(); /* ICCBased color space doesn't do any color correction * so check its underlying color space as well */ is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || (colorMap->getColorSpace()->getMode() == csICCBased && ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); } image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_RGB24, width, height, width * 4); if (image == NULL) { delete imgStr; return; } pattern = cairo_pattern_create_for_surface (image); maskPattern = cairo_pattern_create_for_surface (maskImage); if (pattern == NULL) { delete imgStr; return; } LOG (printf ("drawMaskedImage %dx%d\n", width, height)); cairo_matrix_init_translate (&matrix, 0, height); cairo_matrix_scale (&matrix, width, -height); /* scale the mask to the size of the image unlike softMask */ cairo_pattern_set_matrix (pattern, &matrix); cairo_pattern_set_matrix (maskPattern, &matrix); cairo_pattern_set_filter (pattern, CAIRO_FILTER_BILINEAR); cairo_set_source (cairo, pattern); cairo_mask (cairo, maskPattern); if (cairo_shape) { #if 0 cairo_rectangle (cairo_shape, 0., 0., width, height); cairo_fill (cairo_shape); #else cairo_save (cairo_shape); /* this should draw a rectangle the size of the image * we use this instead of rect,fill because of the lack * of EXTEND_PAD */ /* NOTE: this will multiply the edges of the image twice */ cairo_set_source (cairo_shape, pattern); cairo_mask (cairo_shape, pattern); cairo_restore (cairo_shape); #endif } cairo_pattern_destroy (maskPattern); cairo_surface_destroy (maskImage); cairo_pattern_destroy (pattern); cairo_surface_destroy (image); free (buffer); free (maskBuffer); delete imgStr; } Commit Message: CWE ID: CWE-189
void CairoOutputDev::drawMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, Stream *maskStr, int maskWidth, int maskHeight, GBool maskInvert) { ImageStream *maskImgStr; maskImgStr = new ImageStream(maskStr, maskWidth, 1, 1); maskImgStr->reset(); int row_stride = (maskWidth + 3) & ~3; unsigned char *maskBuffer; maskBuffer = (unsigned char *)gmallocn (row_stride, maskHeight); unsigned char *maskDest; cairo_surface_t *maskImage; cairo_pattern_t *maskPattern; Guchar *pix; int x, y; int invert_bit; invert_bit = maskInvert ? 1 : 0; for (y = 0; y < maskHeight; y++) { pix = maskImgStr->getLine(); maskDest = maskBuffer + y * row_stride; for (x = 0; x < maskWidth; x++) { if (pix[x] ^ invert_bit) *maskDest++ = 0; else *maskDest++ = 255; } } maskImage = cairo_image_surface_create_for_data (maskBuffer, CAIRO_FORMAT_A8, maskWidth, maskHeight, row_stride); delete maskImgStr; maskStr->close(); unsigned char *buffer; unsigned int *dest; cairo_surface_t *image; cairo_pattern_t *pattern; ImageStream *imgStr; cairo_matrix_t matrix; int is_identity_transform; buffer = (unsigned char *)gmallocn3 (width, height, 4); /* TODO: Do we want to cache these? */ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgStr->reset(); /* ICCBased color space doesn't do any color correction * so check its underlying color space as well */ is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || (colorMap->getColorSpace()->getMode() == csICCBased && ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); } image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_RGB24, width, height, width * 4); if (image == NULL) { delete imgStr; return; } pattern = cairo_pattern_create_for_surface (image); maskPattern = cairo_pattern_create_for_surface (maskImage); if (pattern == NULL) { delete imgStr; return; } LOG (printf ("drawMaskedImage %dx%d\n", width, height)); cairo_matrix_init_translate (&matrix, 0, height); cairo_matrix_scale (&matrix, width, -height); /* scale the mask to the size of the image unlike softMask */ cairo_pattern_set_matrix (pattern, &matrix); cairo_pattern_set_matrix (maskPattern, &matrix); cairo_pattern_set_filter (pattern, CAIRO_FILTER_BILINEAR); cairo_set_source (cairo, pattern); cairo_mask (cairo, maskPattern); if (cairo_shape) { #if 0 cairo_rectangle (cairo_shape, 0., 0., width, height); cairo_fill (cairo_shape); #else cairo_save (cairo_shape); /* this should draw a rectangle the size of the image * we use this instead of rect,fill because of the lack * of EXTEND_PAD */ /* NOTE: this will multiply the edges of the image twice */ cairo_set_source (cairo_shape, pattern); cairo_mask (cairo_shape, pattern); cairo_restore (cairo_shape); #endif } cairo_pattern_destroy (maskPattern); cairo_surface_destroy (maskImage); cairo_pattern_destroy (pattern); cairo_surface_destroy (image); free (buffer); free (maskBuffer); delete imgStr; }
164,606
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void pipe_advance(struct iov_iter *i, size_t size) { struct pipe_inode_info *pipe = i->pipe; struct pipe_buffer *buf; int idx = i->idx; size_t off = i->iov_offset, orig_sz; if (unlikely(i->count < size)) size = i->count; orig_sz = size; if (size) { if (off) /* make it relative to the beginning of buffer */ size += off - pipe->bufs[idx].offset; while (1) { buf = &pipe->bufs[idx]; if (size <= buf->len) break; size -= buf->len; idx = next_idx(idx, pipe); } buf->len = size; i->idx = idx; off = i->iov_offset = buf->offset + size; } if (off) idx = next_idx(idx, pipe); if (pipe->nrbufs) { int unused = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1); /* [curbuf,unused) is in use. Free [idx,unused) */ while (idx != unused) { pipe_buf_release(pipe, &pipe->bufs[idx]); idx = next_idx(idx, pipe); pipe->nrbufs--; } } i->count -= orig_sz; } Commit Message: fix a fencepost error in pipe_advance() The logics in pipe_advance() used to release all buffers past the new position failed in cases when the number of buffers to release was equal to pipe->buffers. If that happened, none of them had been released, leaving pipe full. Worse, it was trivial to trigger and we end up with pipe full of uninitialized pages. IOW, it's an infoleak. Cc: [email protected] # v4.9 Reported-by: "Alan J. Wylie" <[email protected]> Tested-by: "Alan J. Wylie" <[email protected]> Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-200
static void pipe_advance(struct iov_iter *i, size_t size) { struct pipe_inode_info *pipe = i->pipe; if (unlikely(i->count < size)) size = i->count; if (size) { struct pipe_buffer *buf; size_t off = i->iov_offset, left = size; int idx = i->idx; if (off) /* make it relative to the beginning of buffer */ left += off - pipe->bufs[idx].offset; while (1) { buf = &pipe->bufs[idx]; if (left <= buf->len) break; left -= buf->len; idx = next_idx(idx, pipe); } i->idx = idx; i->iov_offset = buf->offset + left; } i->count -= size; /* ... and discard everything past that point */ pipe_truncate(i); }
168,388
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SimpleBlock::SimpleBlock( Cluster* pCluster, long idx, long long start, long long size) : BlockEntry(pCluster, idx), m_block(start, size, 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
SimpleBlock::SimpleBlock(
174,444
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebPluginProxy::SetWindowlessPumpEvent(HANDLE pump_messages_event) { HANDLE pump_messages_event_for_renderer = NULL; DuplicateHandle(GetCurrentProcess(), pump_messages_event, channel_->renderer_handle(), &pump_messages_event_for_renderer, 0, FALSE, DUPLICATE_SAME_ACCESS); DCHECK(pump_messages_event_for_renderer != NULL); Send(new PluginHostMsg_SetWindowlessPumpEvent( route_id_, pump_messages_event_for_renderer)); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void WebPluginProxy::SetWindowlessPumpEvent(HANDLE pump_messages_event) { HANDLE pump_messages_event_for_renderer = NULL; sandbox::BrokerDuplicateHandle(pump_messages_event, channel_->peer_pid(), &pump_messages_event_for_renderer, SYNCHRONIZE | EVENT_MODIFY_STATE, 0); DCHECK(pump_messages_event_for_renderer != NULL); Send(new PluginHostMsg_SetWindowlessPumpEvent( route_id_, pump_messages_event_for_renderer)); }
170,953
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool NaClProcessHost::ReplyToRenderer( const IPC::ChannelHandle& channel_handle) { std::vector<nacl::FileDescriptor> handles_for_renderer; for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) { #if defined(OS_WIN) HANDLE handle_in_renderer; if (!DuplicateHandle(base::GetCurrentProcessHandle(), reinterpret_cast<HANDLE>( internal_->sockets_for_renderer[i]), chrome_render_message_filter_->peer_handle(), &handle_in_renderer, 0, // Unused given DUPLICATE_SAME_ACCESS. FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) { DLOG(ERROR) << "DuplicateHandle() failed"; return false; } handles_for_renderer.push_back( reinterpret_cast<nacl::FileDescriptor>(handle_in_renderer)); #else nacl::FileDescriptor imc_handle; imc_handle.fd = internal_->sockets_for_renderer[i]; imc_handle.auto_close = true; handles_for_renderer.push_back(imc_handle); #endif } #if defined(OS_WIN) if (RunningOnWOW64()) { if (!content::BrokerAddTargetPeer(process_->GetData().handle)) { DLOG(ERROR) << "Failed to add NaCl process PID"; return false; } } #endif ChromeViewHostMsg_LaunchNaCl::WriteReplyParams( reply_msg_, handles_for_renderer, channel_handle); chrome_render_message_filter_->Send(reply_msg_); chrome_render_message_filter_ = NULL; reply_msg_ = NULL; internal_->sockets_for_renderer.clear(); return true; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool NaClProcessHost::ReplyToRenderer( bool NaClProcessHost::ReplyToRenderer() { std::vector<nacl::FileDescriptor> handles_for_renderer; for (size_t i = 0; i < internal_->sockets_for_renderer.size(); i++) { #if defined(OS_WIN) HANDLE handle_in_renderer; if (!DuplicateHandle(base::GetCurrentProcessHandle(), reinterpret_cast<HANDLE>( internal_->sockets_for_renderer[i]), chrome_render_message_filter_->peer_handle(), &handle_in_renderer, 0, // Unused given DUPLICATE_SAME_ACCESS. FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) { DLOG(ERROR) << "DuplicateHandle() failed"; return false; } handles_for_renderer.push_back( reinterpret_cast<nacl::FileDescriptor>(handle_in_renderer)); #else nacl::FileDescriptor imc_handle; imc_handle.fd = internal_->sockets_for_renderer[i]; imc_handle.auto_close = true; handles_for_renderer.push_back(imc_handle); #endif } #if defined(OS_WIN) if (RunningOnWOW64()) { if (!content::BrokerAddTargetPeer(process_->GetData().handle)) { DLOG(ERROR) << "Failed to add NaCl process PID"; return false; } } #endif ChromeViewHostMsg_LaunchNaCl::WriteReplyParams( reply_msg_, handles_for_renderer); chrome_render_message_filter_->Send(reply_msg_); chrome_render_message_filter_ = NULL; reply_msg_ = NULL; internal_->sockets_for_renderer.clear(); return true; }
170,727
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { if ((fields->BufferOffset + fields->Len) > Stream_Length(s)) return -1; fields->Buffer = (PBYTE) malloc(fields->Len); if (!fields->Buffer) return -1; Stream_SetPosition(s, fields->BufferOffset); Stream_Read(s, fields->Buffer, fields->Len); } return 1; } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125
int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) static int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { const UINT64 offset = (UINT64)fields->BufferOffset + (UINT64)fields->Len; if (offset > Stream_Length(s)) return -1; fields->Buffer = (PBYTE) malloc(fields->Len); if (!fields->Buffer) return -1; Stream_SetPosition(s, fields->BufferOffset); Stream_Read(s, fields->Buffer, fields->Len); } return 1; }
169,277
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct pid *good_sigevent(sigevent_t * event) { struct task_struct *rtn = current->group_leader; if ((event->sigev_notify & SIGEV_THREAD_ID ) && (!(rtn = find_task_by_vpid(event->sigev_notify_thread_id)) || !same_thread_group(rtn, current) || (event->sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_SIGNAL)) return NULL; if (((event->sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_NONE) && ((event->sigev_signo <= 0) || (event->sigev_signo > SIGRTMAX))) return NULL; return task_pid(rtn); } Commit Message: posix-timer: Properly check sigevent->sigev_notify timer_create() specifies via sigevent->sigev_notify the signal delivery for the new timer. The valid modes are SIGEV_NONE, SIGEV_SIGNAL, SIGEV_THREAD and (SIGEV_SIGNAL | SIGEV_THREAD_ID). The sanity check in good_sigevent() is only checking the valid combination for the SIGEV_THREAD_ID bit, i.e. SIGEV_SIGNAL, but if SIGEV_THREAD_ID is not set it accepts any random value. This has no real effects on the posix timer and signal delivery code, but it affects show_timer() which handles the output of /proc/$PID/timers. That function uses a string array to pretty print sigev_notify. The access to that array has no bound checks, so random sigev_notify cause access beyond the array bounds. Add proper checks for the valid notify modes and remove the SIGEV_THREAD_ID masking from various code pathes as SIGEV_NONE can never be set in combination with SIGEV_THREAD_ID. Reported-by: Eric Biggers <[email protected]> Reported-by: Dmitry Vyukov <[email protected]> Reported-by: Alexey Dobriyan <[email protected]> Signed-off-by: Thomas Gleixner <[email protected]> Cc: John Stultz <[email protected]> Cc: [email protected] CWE ID: CWE-125
static struct pid *good_sigevent(sigevent_t * event) { struct task_struct *rtn = current->group_leader; switch (event->sigev_notify) { case SIGEV_SIGNAL | SIGEV_THREAD_ID: rtn = find_task_by_vpid(event->sigev_notify_thread_id); if (!rtn || !same_thread_group(rtn, current)) return NULL; /* FALLTHRU */ case SIGEV_SIGNAL: case SIGEV_THREAD: if (event->sigev_signo <= 0 || event->sigev_signo > SIGRTMAX) return NULL; /* FALLTHRU */ case SIGEV_NONE: return task_pid(rtn); default: return NULL; } }
169,373
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ExtensionApiTest::InitializeEmbeddedTestServer() { if (!embedded_test_server()->InitializeAndListen()) return false; test_config_->SetInteger(kEmbeddedTestServerPort, embedded_test_server()->port()); return true; } 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
bool ExtensionApiTest::InitializeEmbeddedTestServer() { if (!embedded_test_server()->InitializeAndListen()) return false; if (test_config_) { test_config_->SetInteger(kEmbeddedTestServerPort, embedded_test_server()->port()); } // else SetUpOnMainThread has not been called yet. Possibly because the // caller needs a valid port in an overridden SetUpCommandLine method. return true; }
172,669
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppCacheHost::SelectCacheForSharedWorker(int64 appcache_id) { DCHECK(pending_start_update_callback_.is_null() && pending_swap_cache_callback_.is_null() && pending_get_status_callback_.is_null() && !is_selection_pending() && !was_select_cache_called_); was_select_cache_called_ = true; if (appcache_id != kAppCacheNoCacheId) { LoadSelectedCache(appcache_id); return; } FinishCacheSelection(NULL, NULL); } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID:
void AppCacheHost::SelectCacheForSharedWorker(int64 appcache_id) { bool AppCacheHost::SelectCacheForSharedWorker(int64 appcache_id) { if (was_select_cache_called_) return false; DCHECK(pending_start_update_callback_.is_null() && pending_swap_cache_callback_.is_null() && pending_get_status_callback_.is_null() && !is_selection_pending()); was_select_cache_called_ = true; if (appcache_id != kAppCacheNoCacheId) { LoadSelectedCache(appcache_id); return true; } FinishCacheSelection(NULL, NULL); return true; }
171,741
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int inet6_create(struct net *net, struct socket *sock, int protocol, int kern) { struct inet_sock *inet; struct ipv6_pinfo *np; struct sock *sk; struct inet_protosw *answer; struct proto *answer_prot; unsigned char answer_flags; int try_loading_module = 0; int err; /* Look for the requested type/protocol pair. */ lookup_protocol: err = -ESOCKTNOSUPPORT; rcu_read_lock(); list_for_each_entry_rcu(answer, &inetsw6[sock->type], list) { err = 0; /* Check the non-wild match. */ if (protocol == answer->protocol) { if (protocol != IPPROTO_IP) break; } else { /* Check for the two wild cases. */ if (IPPROTO_IP == protocol) { protocol = answer->protocol; break; } if (IPPROTO_IP == answer->protocol) break; } err = -EPROTONOSUPPORT; } if (err) { if (try_loading_module < 2) { rcu_read_unlock(); /* * Be more specific, e.g. net-pf-10-proto-132-type-1 * (net-pf-PF_INET6-proto-IPPROTO_SCTP-type-SOCK_STREAM) */ if (++try_loading_module == 1) request_module("net-pf-%d-proto-%d-type-%d", PF_INET6, protocol, sock->type); /* * Fall back to generic, e.g. net-pf-10-proto-132 * (net-pf-PF_INET6-proto-IPPROTO_SCTP) */ else request_module("net-pf-%d-proto-%d", PF_INET6, protocol); goto lookup_protocol; } else goto out_rcu_unlock; } err = -EPERM; if (sock->type == SOCK_RAW && !kern && !ns_capable(net->user_ns, CAP_NET_RAW)) goto out_rcu_unlock; sock->ops = answer->ops; answer_prot = answer->prot; answer_flags = answer->flags; rcu_read_unlock(); WARN_ON(!answer_prot->slab); err = -ENOBUFS; sk = sk_alloc(net, PF_INET6, GFP_KERNEL, answer_prot, kern); if (!sk) goto out; sock_init_data(sock, sk); err = 0; if (INET_PROTOSW_REUSE & answer_flags) sk->sk_reuse = SK_CAN_REUSE; inet = inet_sk(sk); inet->is_icsk = (INET_PROTOSW_ICSK & answer_flags) != 0; if (SOCK_RAW == sock->type) { inet->inet_num = protocol; if (IPPROTO_RAW == protocol) inet->hdrincl = 1; } sk->sk_destruct = inet_sock_destruct; sk->sk_family = PF_INET6; sk->sk_protocol = protocol; sk->sk_backlog_rcv = answer->prot->backlog_rcv; inet_sk(sk)->pinet6 = np = inet6_sk_generic(sk); np->hop_limit = -1; np->mcast_hops = IPV6_DEFAULT_MCASTHOPS; np->mc_loop = 1; np->pmtudisc = IPV6_PMTUDISC_WANT; np->autoflowlabel = ip6_default_np_autolabel(sock_net(sk)); sk->sk_ipv6only = net->ipv6.sysctl.bindv6only; /* Init the ipv4 part of the socket since we can have sockets * using v6 API for ipv4. */ inet->uc_ttl = -1; inet->mc_loop = 1; inet->mc_ttl = 1; inet->mc_index = 0; inet->mc_list = NULL; inet->rcv_tos = 0; if (net->ipv4.sysctl_ip_no_pmtu_disc) inet->pmtudisc = IP_PMTUDISC_DONT; else inet->pmtudisc = IP_PMTUDISC_WANT; /* * Increment only the relevant sk_prot->socks debug field, this changes * the previous behaviour of incrementing both the equivalent to * answer->prot->socks (inet6_sock_nr) and inet_sock_nr. * * This allows better debug granularity as we'll know exactly how many * UDPv6, TCPv6, etc socks were allocated, not the sum of all IPv6 * transport protocol socks. -acme */ sk_refcnt_debug_inc(sk); if (inet->inet_num) { /* It assumes that any protocol which allows * the user to assign a number at socket * creation time automatically shares. */ inet->inet_sport = htons(inet->inet_num); sk->sk_prot->hash(sk); } if (sk->sk_prot->init) { err = sk->sk_prot->init(sk); if (err) { sk_common_release(sk); goto out; } } out: return err; out_rcu_unlock: rcu_read_unlock(); goto out; } Commit Message: net: add validation for the socket syscall protocol argument 郭永刚 reported that one could simply crash the kernel as root by using a simple program: int socket_fd; struct sockaddr_in addr; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_family = 10; socket_fd = socket(10,3,0x40000000); connect(socket_fd , &addr,16); AF_INET, AF_INET6 sockets actually only support 8-bit protocol identifiers. inet_sock's skc_protocol field thus is sized accordingly, thus larger protocol identifiers simply cut off the higher bits and store a zero in the protocol fields. This could lead to e.g. NULL function pointer because as a result of the cut off inet_num is zero and we call down to inet_autobind, which is NULL for raw sockets. kernel: Call Trace: kernel: [<ffffffff816db90e>] ? inet_autobind+0x2e/0x70 kernel: [<ffffffff816db9a4>] inet_dgram_connect+0x54/0x80 kernel: [<ffffffff81645069>] SYSC_connect+0xd9/0x110 kernel: [<ffffffff810ac51b>] ? ptrace_notify+0x5b/0x80 kernel: [<ffffffff810236d8>] ? syscall_trace_enter_phase2+0x108/0x200 kernel: [<ffffffff81645e0e>] SyS_connect+0xe/0x10 kernel: [<ffffffff81779515>] tracesys_phase2+0x84/0x89 I found no particular commit which introduced this problem. CVE: CVE-2015-8543 Cc: Cong Wang <[email protected]> Reported-by: 郭永刚 <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static int inet6_create(struct net *net, struct socket *sock, int protocol, int kern) { struct inet_sock *inet; struct ipv6_pinfo *np; struct sock *sk; struct inet_protosw *answer; struct proto *answer_prot; unsigned char answer_flags; int try_loading_module = 0; int err; if (protocol < 0 || protocol >= IPPROTO_MAX) return -EINVAL; /* Look for the requested type/protocol pair. */ lookup_protocol: err = -ESOCKTNOSUPPORT; rcu_read_lock(); list_for_each_entry_rcu(answer, &inetsw6[sock->type], list) { err = 0; /* Check the non-wild match. */ if (protocol == answer->protocol) { if (protocol != IPPROTO_IP) break; } else { /* Check for the two wild cases. */ if (IPPROTO_IP == protocol) { protocol = answer->protocol; break; } if (IPPROTO_IP == answer->protocol) break; } err = -EPROTONOSUPPORT; } if (err) { if (try_loading_module < 2) { rcu_read_unlock(); /* * Be more specific, e.g. net-pf-10-proto-132-type-1 * (net-pf-PF_INET6-proto-IPPROTO_SCTP-type-SOCK_STREAM) */ if (++try_loading_module == 1) request_module("net-pf-%d-proto-%d-type-%d", PF_INET6, protocol, sock->type); /* * Fall back to generic, e.g. net-pf-10-proto-132 * (net-pf-PF_INET6-proto-IPPROTO_SCTP) */ else request_module("net-pf-%d-proto-%d", PF_INET6, protocol); goto lookup_protocol; } else goto out_rcu_unlock; } err = -EPERM; if (sock->type == SOCK_RAW && !kern && !ns_capable(net->user_ns, CAP_NET_RAW)) goto out_rcu_unlock; sock->ops = answer->ops; answer_prot = answer->prot; answer_flags = answer->flags; rcu_read_unlock(); WARN_ON(!answer_prot->slab); err = -ENOBUFS; sk = sk_alloc(net, PF_INET6, GFP_KERNEL, answer_prot, kern); if (!sk) goto out; sock_init_data(sock, sk); err = 0; if (INET_PROTOSW_REUSE & answer_flags) sk->sk_reuse = SK_CAN_REUSE; inet = inet_sk(sk); inet->is_icsk = (INET_PROTOSW_ICSK & answer_flags) != 0; if (SOCK_RAW == sock->type) { inet->inet_num = protocol; if (IPPROTO_RAW == protocol) inet->hdrincl = 1; } sk->sk_destruct = inet_sock_destruct; sk->sk_family = PF_INET6; sk->sk_protocol = protocol; sk->sk_backlog_rcv = answer->prot->backlog_rcv; inet_sk(sk)->pinet6 = np = inet6_sk_generic(sk); np->hop_limit = -1; np->mcast_hops = IPV6_DEFAULT_MCASTHOPS; np->mc_loop = 1; np->pmtudisc = IPV6_PMTUDISC_WANT; np->autoflowlabel = ip6_default_np_autolabel(sock_net(sk)); sk->sk_ipv6only = net->ipv6.sysctl.bindv6only; /* Init the ipv4 part of the socket since we can have sockets * using v6 API for ipv4. */ inet->uc_ttl = -1; inet->mc_loop = 1; inet->mc_ttl = 1; inet->mc_index = 0; inet->mc_list = NULL; inet->rcv_tos = 0; if (net->ipv4.sysctl_ip_no_pmtu_disc) inet->pmtudisc = IP_PMTUDISC_DONT; else inet->pmtudisc = IP_PMTUDISC_WANT; /* * Increment only the relevant sk_prot->socks debug field, this changes * the previous behaviour of incrementing both the equivalent to * answer->prot->socks (inet6_sock_nr) and inet_sock_nr. * * This allows better debug granularity as we'll know exactly how many * UDPv6, TCPv6, etc socks were allocated, not the sum of all IPv6 * transport protocol socks. -acme */ sk_refcnt_debug_inc(sk); if (inet->inet_num) { /* It assumes that any protocol which allows * the user to assign a number at socket * creation time automatically shares. */ inet->inet_sport = htons(inet->inet_num); sk->sk_prot->hash(sk); } if (sk->sk_prot->init) { err = sk->sk_prot->init(sk); if (err) { sk_common_release(sk); goto out; } } out: return err; out_rcu_unlock: rcu_read_unlock(); goto out; }
166,565
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: krb5_gss_process_context_token(minor_status, context_handle, token_buffer) OM_uint32 *minor_status; gss_ctx_id_t context_handle; gss_buffer_t token_buffer; { krb5_gss_ctx_id_rec *ctx; OM_uint32 majerr; ctx = (krb5_gss_ctx_id_t) context_handle; if (! ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } /* "unseal" the token */ if (GSS_ERROR(majerr = kg_unseal(minor_status, context_handle, token_buffer, GSS_C_NO_BUFFER, NULL, NULL, KG_TOK_DEL_CTX))) return(majerr); /* that's it. delete the context */ return(krb5_gss_delete_sec_context(minor_status, &context_handle, GSS_C_NO_BUFFER)); } Commit Message: Fix gss_process_context_token() [CVE-2014-5352] [MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not actually delete the context; that leaves the caller with a dangling pointer and no way to know that it is invalid. Instead, mark the context as terminated, and check for terminated contexts in the GSS functions which expect established contexts. Also add checks in export_sec_context and pseudo_random, and adjust t_prf.c for the pseudo_random check. ticket: 8055 (new) target_version: 1.13.1 tags: pullup CWE ID:
krb5_gss_process_context_token(minor_status, context_handle, token_buffer) OM_uint32 *minor_status; gss_ctx_id_t context_handle; gss_buffer_t token_buffer; { krb5_gss_ctx_id_rec *ctx; OM_uint32 majerr; ctx = (krb5_gss_ctx_id_t) context_handle; if (ctx->terminated || !ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } /* We only support context deletion tokens for now, and RFC 4121 does not * define a context deletion token. */ if (ctx->proto) { *minor_status = 0; return(GSS_S_DEFECTIVE_TOKEN); } /* "unseal" the token */ if (GSS_ERROR(majerr = kg_unseal(minor_status, context_handle, token_buffer, GSS_C_NO_BUFFER, NULL, NULL, KG_TOK_DEL_CTX))) return(majerr); /* Mark the context as terminated, but do not delete it (as that would * leave the caller with a dangling context handle). */ ctx->terminated = 1; return(GSS_S_COMPLETE); }
166,823
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void VRDisplay::ProcessScheduledWindowAnimations(double timestamp) { TRACE_EVENT1("gpu", "VRDisplay::window.rAF", "frame", vr_frame_id_); auto doc = navigator_vr_->GetDocument(); if (!doc) return; auto page = doc->GetPage(); if (!page) return; page->Animator().ServiceScriptedAnimations(timestamp); } Commit Message: WebVR: fix initial vsync Applications sometimes use window.rAF while not presenting, then switch to vrDisplay.rAF after presentation starts. Depending on the animation loop's timing, this can cause a race condition where presentation has been started but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync being processed after presentation starts so that a queued window.rAF can run and schedule a vrDisplay.rAF. BUG=711789 Review-Url: https://codereview.chromium.org/2848483003 Cr-Commit-Position: refs/heads/master@{#468167} CWE ID:
void VRDisplay::ProcessScheduledWindowAnimations(double timestamp) { TRACE_EVENT1("gpu", "VRDisplay::window.rAF", "frame", vr_frame_id_); auto doc = navigator_vr_->GetDocument(); if (!doc) return; auto page = doc->GetPage(); if (!page) return; bool had_pending_vrdisplay_raf = pending_vrdisplay_raf_; page->Animator().ServiceScriptedAnimations(timestamp); if (had_pending_vrdisplay_raf != pending_vrdisplay_raf_) { DVLOG(1) << __FUNCTION__ << ": window.rAF fallback successfully scheduled VRDisplay.rAF"; } if (!pending_vrdisplay_raf_) { // There wasn't any call to vrDisplay.rAF, so we will not be getting new // frames from now on unless the application schedules one down the road in // reaction to a separate event or timeout. TODO(klausw,crbug.com/716087): // do something more useful here? DVLOG(1) << __FUNCTION__ << ": no scheduled VRDisplay.requestAnimationFrame, presentation " "broken?"; } }
171,999
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: vbf_stp_error(struct worker *wrk, struct busyobj *bo) { ssize_t l, ll, o; double now; uint8_t *ptr; struct vsb *synth_body; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC); AN(bo->fetch_objcore->flags & OC_F_BUSY); assert(bo->director_state == DIR_S_NULL); wrk->stats->fetch_failed++; now = W_TIM_real(wrk); VSLb_ts_busyobj(bo, "Error", now); if (bo->fetch_objcore->stobj->stevedore != NULL) ObjFreeObj(bo->wrk, bo->fetch_objcore); HTTP_Setup(bo->beresp, bo->ws, bo->vsl, SLT_BerespMethod); http_PutResponse(bo->beresp, "HTTP/1.1", 503, "Backend fetch failed"); http_TimeHeader(bo->beresp, "Date: ", now); http_SetHeader(bo->beresp, "Server: Varnish"); bo->fetch_objcore->t_origin = now; if (!VTAILQ_EMPTY(&bo->fetch_objcore->objhead->waitinglist)) { /* * If there is a waitinglist, it means that there is no * grace-able object, so cache the error return for a * short time, so the waiting list can drain, rather than * each objcore on the waiting list sequentially attempt * to fetch from the backend. */ bo->fetch_objcore->ttl = 1; bo->fetch_objcore->grace = 5; bo->fetch_objcore->keep = 5; } else { bo->fetch_objcore->ttl = 0; bo->fetch_objcore->grace = 0; bo->fetch_objcore->keep = 0; } synth_body = VSB_new_auto(); AN(synth_body); VCL_backend_error_method(bo->vcl, wrk, NULL, bo, synth_body); AZ(VSB_finish(synth_body)); if (wrk->handling == VCL_RET_ABANDON || wrk->handling == VCL_RET_FAIL) { VSB_destroy(&synth_body); return (F_STP_FAIL); } if (wrk->handling == VCL_RET_RETRY) { VSB_destroy(&synth_body); if (bo->retries++ < cache_param->max_retries) return (F_STP_RETRY); VSLb(bo->vsl, SLT_VCL_Error, "Too many retries, failing"); return (F_STP_FAIL); } assert(wrk->handling == VCL_RET_DELIVER); bo->vfc->bo = bo; bo->vfc->wrk = bo->wrk; bo->vfc->oc = bo->fetch_objcore; bo->vfc->http = bo->beresp; bo->vfc->esi_req = bo->bereq; if (vbf_beresp2obj(bo)) { (void)VFP_Error(bo->vfc, "Could not get storage"); VSB_destroy(&synth_body); return (F_STP_FAIL); } ll = VSB_len(synth_body); o = 0; while (ll > 0) { l = ll; if (VFP_GetStorage(bo->vfc, &l, &ptr) != VFP_OK) break; memcpy(ptr, VSB_data(synth_body) + o, l); VFP_Extend(bo->vfc, l); ll -= l; o += l; } AZ(ObjSetU64(wrk, bo->fetch_objcore, OA_LEN, o)); VSB_destroy(&synth_body); HSH_Unbusy(wrk, bo->fetch_objcore); ObjSetState(wrk, bo->fetch_objcore, BOS_FINISHED); return (F_STP_DONE); } Commit Message: Avoid buffer read overflow on vcl_error and -sfile The file stevedore may return a buffer larger than asked for when requesting storage. Due to lack of check for this condition, the code to copy the synthetic error memory buffer from vcl_error would overrun the buffer. Patch by @shamger Fixes: #2429 CWE ID: CWE-119
vbf_stp_error(struct worker *wrk, struct busyobj *bo) { ssize_t l, ll, o; double now; uint8_t *ptr; struct vsb *synth_body; CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC); AN(bo->fetch_objcore->flags & OC_F_BUSY); assert(bo->director_state == DIR_S_NULL); wrk->stats->fetch_failed++; now = W_TIM_real(wrk); VSLb_ts_busyobj(bo, "Error", now); if (bo->fetch_objcore->stobj->stevedore != NULL) ObjFreeObj(bo->wrk, bo->fetch_objcore); HTTP_Setup(bo->beresp, bo->ws, bo->vsl, SLT_BerespMethod); http_PutResponse(bo->beresp, "HTTP/1.1", 503, "Backend fetch failed"); http_TimeHeader(bo->beresp, "Date: ", now); http_SetHeader(bo->beresp, "Server: Varnish"); bo->fetch_objcore->t_origin = now; if (!VTAILQ_EMPTY(&bo->fetch_objcore->objhead->waitinglist)) { /* * If there is a waitinglist, it means that there is no * grace-able object, so cache the error return for a * short time, so the waiting list can drain, rather than * each objcore on the waiting list sequentially attempt * to fetch from the backend. */ bo->fetch_objcore->ttl = 1; bo->fetch_objcore->grace = 5; bo->fetch_objcore->keep = 5; } else { bo->fetch_objcore->ttl = 0; bo->fetch_objcore->grace = 0; bo->fetch_objcore->keep = 0; } synth_body = VSB_new_auto(); AN(synth_body); VCL_backend_error_method(bo->vcl, wrk, NULL, bo, synth_body); AZ(VSB_finish(synth_body)); if (wrk->handling == VCL_RET_ABANDON || wrk->handling == VCL_RET_FAIL) { VSB_destroy(&synth_body); return (F_STP_FAIL); } if (wrk->handling == VCL_RET_RETRY) { VSB_destroy(&synth_body); if (bo->retries++ < cache_param->max_retries) return (F_STP_RETRY); VSLb(bo->vsl, SLT_VCL_Error, "Too many retries, failing"); return (F_STP_FAIL); } assert(wrk->handling == VCL_RET_DELIVER); bo->vfc->bo = bo; bo->vfc->wrk = bo->wrk; bo->vfc->oc = bo->fetch_objcore; bo->vfc->http = bo->beresp; bo->vfc->esi_req = bo->bereq; if (vbf_beresp2obj(bo)) { (void)VFP_Error(bo->vfc, "Could not get storage"); VSB_destroy(&synth_body); return (F_STP_FAIL); } ll = VSB_len(synth_body); o = 0; while (ll > 0) { l = ll; if (VFP_GetStorage(bo->vfc, &l, &ptr) != VFP_OK) break; if (l > ll) l = ll; memcpy(ptr, VSB_data(synth_body) + o, l); VFP_Extend(bo->vfc, l); ll -= l; o += l; } AZ(ObjSetU64(wrk, bo->fetch_objcore, OA_LEN, o)); VSB_destroy(&synth_body); HSH_Unbusy(wrk, bo->fetch_objcore); ObjSetState(wrk, bo->fetch_objcore, BOS_FINISHED); return (F_STP_DONE); }
168,193
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { ut8 op_MSB,op_LSB; int ret; if (!data) return 0; memset (op, '\0', sizeof (RAnalOp)); op->addr = addr; op->type = R_ANAL_OP_TYPE_UNK; op->jump = op->fail = -1; op->ptr = op->val = -1; op->size = 2; op_MSB = anal->big_endian? data[0]: data[1]; op_LSB = anal->big_endian? data[1]: data[0]; ret = first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB)); return ret; } Commit Message: Fix #9903 - oobread in RAnal.sh CWE ID: CWE-125
static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { ut8 op_MSB,op_LSB; int ret; if (!data || len < 2) { return 0; } memset (op, '\0', sizeof (RAnalOp)); op->addr = addr; op->type = R_ANAL_OP_TYPE_UNK; op->jump = op->fail = -1; op->ptr = op->val = -1; op->size = 2; op_MSB = anal->big_endian? data[0]: data[1]; op_LSB = anal->big_endian? data[1]: data[0]; ret = first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB)); return ret; }
169,221
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void esp_do_dma(ESPState *s) { uint32_t len; int to_device; len = s->dma_left; if (s->do_cmd) { trace_esp_do_dma(s->cmdlen, len); s->dma_memory_read(s->dma_opaque, &s->cmdbuf[s->cmdlen], len); return; } return; } Commit Message: CWE ID: CWE-787
static void esp_do_dma(ESPState *s) { uint32_t len; int to_device; len = s->dma_left; if (s->do_cmd) { trace_esp_do_dma(s->cmdlen, len); assert (s->cmdlen <= sizeof(s->cmdbuf) && len <= sizeof(s->cmdbuf) - s->cmdlen); s->dma_memory_read(s->dma_opaque, &s->cmdbuf[s->cmdlen], len); return; } return; }
164,961
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PepperRendererConnection::OnMsgDidDeleteInProcessInstance( PP_Instance instance) { in_process_host_->DeleteInstance(instance); } Commit Message: Validate in-process plugin instance messages. Bug: 733548, 733549 Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation Change-Id: Ie5572c7bcafa05399b09c44425ddd5ce9b9e4cba Reviewed-on: https://chromium-review.googlesource.com/538908 Commit-Queue: Bill Budge <[email protected]> Reviewed-by: Raymes Khoury <[email protected]> Cr-Commit-Position: refs/heads/master@{#480696} CWE ID: CWE-20
void PepperRendererConnection::OnMsgDidDeleteInProcessInstance( PP_Instance instance) { // 'instance' is possibly invalid. The host must be careful not to trust it. in_process_host_->DeleteInstance(instance); }
172,312
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const CuePoint* Cues::GetNext(const CuePoint* pCurr) const { if (pCurr == NULL) return NULL; assert(pCurr->GetTimeCode() >= 0); assert(m_cue_points); assert(m_count >= 1); #if 0 const size_t count = m_count + m_preload_count; size_t index = pCurr->m_index; assert(index < count); CuePoint* const* const pp = m_cue_points; assert(pp); assert(pp[index] == pCurr); ++index; if (index >= count) return NULL; CuePoint* const pNext = pp[index]; assert(pNext); pNext->Load(m_pSegment->m_pReader); #else long index = pCurr->m_index; assert(index < m_count); CuePoint* const* const pp = m_cue_points; assert(pp); assert(pp[index] == pCurr); ++index; if (index >= m_count) return NULL; CuePoint* const pNext = pp[index]; assert(pNext); assert(pNext->GetTimeCode() >= 0); #endif return pNext; } 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
const CuePoint* Cues::GetNext(const CuePoint* pCurr) const assert(pCurr->GetTimeCode() >= 0); assert(m_cue_points); assert(m_count >= 1); #if 0 const size_t count = m_count + m_preload_count; size_t index = pCurr->m_index; assert(index < count); CuePoint* const* const pp = m_cue_points; assert(pp); assert(pp[index] == pCurr); ++index; if (index >= count) return NULL; CuePoint* const pNext = pp[index]; assert(pNext); pNext->Load(m_pSegment->m_pReader); #else long index = pCurr->m_index; assert(index < m_count); CuePoint* const* const pp = m_cue_points; assert(pp); assert(pp[index] == pCurr); ++index; if (index >= m_count) return NULL; CuePoint* const pNext = pp[index]; assert(pNext); assert(pNext->GetTimeCode() >= 0); #endif return pNext; }
174,346
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool 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
bool Track::VetEntry(const BlockEntry* pBlockEntry) const 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; // This function is used during a seek to determine whether the // frame is a valid seek target. This default function simply // returns true, which means all frames are valid seek targets. // It gets overridden by the VideoTrack class, because only video // keyframes can be used as seek target. return true; }
174,451
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void encode_frame(vpx_codec_ctx_t *codec, vpx_image_t *img, int frame_index, VpxVideoWriter *writer) { vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, 0, VPX_DL_GOOD_QUALITY); if (res != VPX_CODEC_OK) die_codec(codec, "Failed to encode frame"); while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) { if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) { die_codec(codec, "Failed to write compressed frame"); } printf(keyframe ? "K" : "."); fflush(stdout); } } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static void encode_frame(vpx_codec_ctx_t *codec, static int encode_frame(vpx_codec_ctx_t *codec, vpx_image_t *img, int frame_index, VpxVideoWriter *writer) { int got_pkts = 0; vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, 0, VPX_DL_GOOD_QUALITY); if (res != VPX_CODEC_OK) die_codec(codec, "Failed to encode frame"); while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) { got_pkts = 1; if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) { die_codec(codec, "Failed to write compressed frame"); } printf(keyframe ? "K" : "."); fflush(stdout); } } return got_pkts; }
174,481
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CastCastView::ButtonPressed(views::Button* sender, const ui::Event& event) { DCHECK(sender == stop_button_); StopCast(); } Commit Message: Allow the cast tray to function as expected when the installed extension is missing API methods. BUG=489445 Review URL: https://codereview.chromium.org/1145833003 Cr-Commit-Position: refs/heads/master@{#330663} CWE ID: CWE-79
void CastCastView::ButtonPressed(views::Button* sender, const ui::Event& event) { DCHECK(sender == stop_button_); cast_config_delegate_->StopCasting(); }
171,623
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CopyToOMX(const OMX_BUFFERHEADERTYPE *header) { if (!mIsBackup) { return; } memcpy(header->pBuffer + header->nOffset, (const OMX_U8 *)mMem->pointer() + header->nOffset, header->nFilledLen); } 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
void CopyToOMX(const OMX_BUFFERHEADERTYPE *header) { if (!mCopyToOmx) { return; } memcpy(header->pBuffer + header->nOffset, (const OMX_U8 *)mMem->pointer() + header->nOffset, header->nFilledLen); }
174,128
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::set<std::string> GetDistinctHosts(const URLPatternSet& host_patterns, bool include_rcd, bool exclude_file_scheme) { typedef base::StringPairs HostVector; HostVector hosts_best_rcd; for (const URLPattern& pattern : host_patterns) { if (exclude_file_scheme && pattern.scheme() == url::kFileScheme) continue; std::string host = pattern.host(); if (pattern.match_subdomains()) host = "*." + host; std::string rcd; size_t reg_len = net::registry_controlled_domains::PermissiveGetHostRegistryLength( host, net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES, net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES); if (reg_len && reg_len != std::string::npos) { if (include_rcd) // else leave rcd empty rcd = host.substr(host.size() - reg_len); host = host.substr(0, host.size() - reg_len); } HostVector::iterator it = hosts_best_rcd.begin(); for (; it != hosts_best_rcd.end(); ++it) { if (it->first == host) break; } if (it != hosts_best_rcd.end()) { if (include_rcd && RcdBetterThan(rcd, it->second)) it->second = rcd; } else { // Previously unseen host, append it. hosts_best_rcd.push_back(std::make_pair(host, rcd)); } } std::set<std::string> distinct_hosts; for (const auto& host_rcd : hosts_best_rcd) distinct_hosts.insert(host_rcd.first + host_rcd.second); return distinct_hosts; } Commit Message: Ensure IDN domains are in punycode format in extension host permissions Today in extension dialogs and bubbles, IDN domains in host permissions are not displayed in punycode format. There is a low security risk that granting such permission would allow extensions to interact with pages using spoofy IDN domains. Note that this does not affect the omnibox, which would represent the origin properly. To address this issue, this CL converts IDN domains in host permissions to punycode format. Bug: 745580 Change-Id: Ifc04030fae645f8a78ac8fde170660f2d514acce Reviewed-on: https://chromium-review.googlesource.com/644140 Commit-Queue: catmullings <[email protected]> Reviewed-by: Istiaque Ahmed <[email protected]> Reviewed-by: Tommy Li <[email protected]> Cr-Commit-Position: refs/heads/master@{#499090} CWE ID: CWE-20
std::set<std::string> GetDistinctHosts(const URLPatternSet& host_patterns, bool include_rcd, bool exclude_file_scheme) { typedef base::StringPairs HostVector; HostVector hosts_best_rcd; for (const URLPattern& pattern : host_patterns) { if (exclude_file_scheme && pattern.scheme() == url::kFileScheme) continue; std::string host = pattern.host(); if (!host.empty()) { // Convert the host into a secure format. For example, an IDN domain is // converted to punycode. host = base::UTF16ToUTF8(url_formatter::FormatUrlForSecurityDisplay( GURL(base::StringPrintf("%s%s%s", url::kHttpScheme, url::kStandardSchemeSeparator, host.c_str())), url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS)); } if (pattern.match_subdomains()) host = "*." + host; std::string rcd; size_t reg_len = net::registry_controlled_domains::PermissiveGetHostRegistryLength( host, net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES, net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES); if (reg_len && reg_len != std::string::npos) { if (include_rcd) // else leave rcd empty rcd = host.substr(host.size() - reg_len); host = host.substr(0, host.size() - reg_len); } HostVector::iterator it = hosts_best_rcd.begin(); for (; it != hosts_best_rcd.end(); ++it) { if (it->first == host) break; } if (it != hosts_best_rcd.end()) { if (include_rcd && RcdBetterThan(rcd, it->second)) it->second = rcd; } else { // Previously unseen host, append it. hosts_best_rcd.push_back(std::make_pair(host, rcd)); } } std::set<std::string> distinct_hosts; for (const auto& host_rcd : hosts_best_rcd) distinct_hosts.insert(host_rcd.first + host_rcd.second); return distinct_hosts; }
172,961
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: delete_policy_2_svc(dpol_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->name; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_DELETE, NULL, NULL)) { log_unauth("kadm5_delete_policy", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_DELETE; } else { ret.code = kadm5_delete_policy((void *)handle, arg->name); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_delete_policy", ((prime_arg == NULL) ? "(null)" : prime_arg), errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
delete_policy_2_svc(dpol_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->name; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_DELETE, NULL, NULL)) { log_unauth("kadm5_delete_policy", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_DELETE; } else { ret.code = kadm5_delete_policy((void *)handle, arg->name); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_delete_policy", ((prime_arg == NULL) ? "(null)" : prime_arg), errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,511
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport void *ResizeQuantumMemory(void *memory,const size_t count, const size_t quantum) { size_t extent; if (CheckMemoryOverflow(count,quantum) != MagickFalse) { memory=RelinquishMagickMemory(memory); return((void *) NULL); } extent=count*quantum; return(ResizeMagickMemory(memory,extent)); } Commit Message: Suspend exception processing if there are too many exceptions CWE ID: CWE-119
MagickExport void *ResizeQuantumMemory(void *memory,const size_t count, const size_t quantum) { size_t extent; if (HeapOverflowSanityCheck(count,quantum) != MagickFalse) { memory=RelinquishMagickMemory(memory); return((void *) NULL); } extent=count*quantum; return(ResizeMagickMemory(memory,extent)); }
168,545
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int Chapters::Atom::GetDisplayCount() const { return m_displays_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
int Chapters::Atom::GetDisplayCount() const
174,305
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadHRZImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; register ssize_t x; register PixelPacket *q; register unsigned char *p; ssize_t count, y; size_t length; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Convert HRZ raster image to pixel packets. */ image->columns=256; image->rows=240; image->depth=8; pixels=(unsigned char *) AcquireQuantumMemory(image->columns,3* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=(size_t) (3*image->columns); for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if ((size_t) count != length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(4**p++)); SetPixelGreen(q,ScaleCharToQuantum(4**p++)); SetPixelBlue(q,ScaleCharToQuantum(4**p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadHRZImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; register ssize_t x; register PixelPacket *q; register unsigned char *p; ssize_t count, y; size_t length; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Convert HRZ raster image to pixel packets. */ image->columns=256; image->rows=240; image->depth=8; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } pixels=(unsigned char *) AcquireQuantumMemory(image->columns,3* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=(size_t) (3*image->columns); for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if ((size_t) count != length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(4**p++)); SetPixelGreen(q,ScaleCharToQuantum(4**p++)); SetPixelBlue(q,ScaleCharToQuantum(4**p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,571
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) { ALOGV("setNextPlayer"); Mutex::Autolock l(mLock); sp<Client> c = static_cast<Client*>(player.get()); mNextClient = c; if (c != NULL) { if (mAudioOutput != NULL) { mAudioOutput->setNextOutput(c->mAudioOutput); } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) { ALOGE("no current audio output"); } if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) { mPlayer->setNextPlayer(mNextClient->getPlayer()); } } return OK; } Commit Message: MediaPlayerService: avoid invalid static cast Bug: 30204103 Change-Id: Ie0dd3568a375f1e9fed8615ad3d85184bcc99028 (cherry picked from commit ee0a0e39acdcf8f97e0d6945c31ff36a06a36e9d) CWE ID: CWE-264
status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) { ALOGV("setNextPlayer"); Mutex::Autolock l(mLock); sp<Client> c = static_cast<Client*>(player.get()); if (!mService->hasClient(c)) { return BAD_VALUE; } mNextClient = c; if (c != NULL) { if (mAudioOutput != NULL) { mAudioOutput->setNextOutput(c->mAudioOutput); } else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) { ALOGE("no current audio output"); } if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) { mPlayer->setNextPlayer(mNextClient->getPlayer()); } } return OK; }
173,398
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_CreateArray( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_Array; return 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
cJSON *cJSON_CreateArray( void )
167,269
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cmsSEQ* CMSEXPORT cmsAllocProfileSequenceDescription(cmsContext ContextID, cmsUInt32Number n) { cmsSEQ* Seq; cmsUInt32Number i; if (n == 0) return NULL; if (n > 255) return NULL; Seq = (cmsSEQ*) _cmsMallocZero(ContextID, sizeof(cmsSEQ)); if (Seq == NULL) return NULL; Seq -> ContextID = ContextID; Seq -> seq = (cmsPSEQDESC*) _cmsCalloc(ContextID, n, sizeof(cmsPSEQDESC)); Seq -> n = n; for (i=0; i < n; i++) { Seq -> seq[i].Manufacturer = NULL; Seq -> seq[i].Model = NULL; Seq -> seq[i].Description = NULL; } return Seq; } Commit Message: Non happy-path fixes CWE ID:
cmsSEQ* CMSEXPORT cmsAllocProfileSequenceDescription(cmsContext ContextID, cmsUInt32Number n) { cmsSEQ* Seq; cmsUInt32Number i; if (n == 0) return NULL; if (n > 255) return NULL; Seq = (cmsSEQ*) _cmsMallocZero(ContextID, sizeof(cmsSEQ)); if (Seq == NULL) return NULL; Seq -> ContextID = ContextID; Seq -> seq = (cmsPSEQDESC*) _cmsCalloc(ContextID, n, sizeof(cmsPSEQDESC)); Seq -> n = n; if (Seq -> seq == NULL) { _cmsFree(ContextID, Seq); return NULL; } for (i=0; i < n; i++) { Seq -> seq[i].Manufacturer = NULL; Seq -> seq[i].Model = NULL; Seq -> seq[i].Description = NULL; } return Seq; }
166,542
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_expand_16_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; /* expand_16 does something unless the bit depth is already 16. */ return bit_depth < 16; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_expand_16_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; /* expand_16 does something unless the bit depth is already 16. */ return bit_depth < 16; }
173,626
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: juniper_ggsn_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_ggsn_header { uint8_t svc_id; uint8_t flags_len; uint8_t proto; uint8_t flags; uint8_t vlan_id[2]; uint8_t res[2]; }; const struct juniper_ggsn_header *gh; l2info.pictype = DLT_JUNIPER_GGSN; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; gh = (struct juniper_ggsn_header *)&l2info.cookie; if (ndo->ndo_eflag) { ND_PRINT((ndo, "proto %s (%u), vlan %u: ", tok2str(juniper_protocol_values,"Unknown",gh->proto), gh->proto, EXTRACT_16BITS(&gh->vlan_id[0]))); } switch (gh->proto) { case JUNIPER_PROTO_IPV4: ip_print(ndo, p, l2info.length); break; case JUNIPER_PROTO_IPV6: ip6_print(ndo, p, l2info.length); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "unknown GGSN proto (%u)", gh->proto)); } return l2info.header_len; } Commit Message: CVE-2017-12993/Juniper: Add more bounds checks. This fixes a buffer over-read discovered by Kamil Frankowicz. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125
juniper_ggsn_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_ggsn_header { uint8_t svc_id; uint8_t flags_len; uint8_t proto; uint8_t flags; uint8_t vlan_id[2]; uint8_t res[2]; }; const struct juniper_ggsn_header *gh; l2info.pictype = DLT_JUNIPER_GGSN; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; gh = (struct juniper_ggsn_header *)&l2info.cookie; ND_TCHECK(*gh); if (ndo->ndo_eflag) { ND_PRINT((ndo, "proto %s (%u), vlan %u: ", tok2str(juniper_protocol_values,"Unknown",gh->proto), gh->proto, EXTRACT_16BITS(&gh->vlan_id[0]))); } switch (gh->proto) { case JUNIPER_PROTO_IPV4: ip_print(ndo, p, l2info.length); break; case JUNIPER_PROTO_IPV6: ip6_print(ndo, p, l2info.length); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "unknown GGSN proto (%u)", gh->proto)); } return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_services]")); return l2info.header_len; }
167,917
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int aac_sync(uint64_t state, AACAC3ParseContext *hdr_info, int *need_next_header, int *new_frame_start) { GetBitContext bits; AACADTSHeaderInfo hdr; int size; union { uint64_t u64; uint8_t u8[8]; } tmp; tmp.u64 = av_be2ne64(state); init_get_bits(&bits, tmp.u8+8-AAC_ADTS_HEADER_SIZE, AAC_ADTS_HEADER_SIZE * 8); if ((size = avpriv_aac_parse_header(&bits, &hdr)) < 0) return 0; *need_next_header = 0; *new_frame_start = 1; hdr_info->sample_rate = hdr.sample_rate; hdr_info->channels = ff_mpeg4audio_channels[hdr.chan_config]; hdr_info->samples = hdr.samples; hdr_info->bit_rate = hdr.bit_rate; return size; } Commit Message: CWE ID: CWE-125
static int aac_sync(uint64_t state, AACAC3ParseContext *hdr_info, int *need_next_header, int *new_frame_start) { GetBitContext bits; AACADTSHeaderInfo hdr; int size; union { uint64_t u64; uint8_t u8[8 + FF_INPUT_BUFFER_PADDING_SIZE]; } tmp; tmp.u64 = av_be2ne64(state); init_get_bits(&bits, tmp.u8+8-AAC_ADTS_HEADER_SIZE, AAC_ADTS_HEADER_SIZE * 8); if ((size = avpriv_aac_parse_header(&bits, &hdr)) < 0) return 0; *need_next_header = 0; *new_frame_start = 1; hdr_info->sample_rate = hdr.sample_rate; hdr_info->channels = ff_mpeg4audio_channels[hdr.chan_config]; hdr_info->samples = hdr.samples; hdr_info->bit_rate = hdr.bit_rate; return size; }
165,278
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: METHODDEF(JDIMENSION) get_word_gray_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading raw-word-format PGM files with any maxval */ { ppm_source_ptr source = (ppm_source_ptr)sinfo; register JSAMPROW ptr; register U_CHAR *bufferptr; register JSAMPLE *rescale = source->rescale; JDIMENSION col; unsigned int maxval = source->maxval; if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width)) ERREXIT(cinfo, JERR_INPUT_EOF); ptr = source->pub.buffer[0]; bufferptr = source->iobuffer; for (col = cinfo->image_width; col > 0; col--) { register unsigned int temp; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_TOOLARGE); *ptr++ = rescale[temp]; } return 1; } Commit Message: cjpeg: Fix OOB read caused by malformed 8-bit BMP ... in which one or more of the color indices is out of range for the number of palette entries. Fix partly borrowed from jpeg-9c. This commit also adopts Guido's JERR_PPM_OUTOFRANGE enum value in lieu of our project-specific JERR_PPM_TOOLARGE enum value. Fixes #258 CWE ID: CWE-125
METHODDEF(JDIMENSION) get_word_gray_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading raw-word-format PGM files with any maxval */ { ppm_source_ptr source = (ppm_source_ptr)sinfo; register JSAMPROW ptr; register U_CHAR *bufferptr; register JSAMPLE *rescale = source->rescale; JDIMENSION col; unsigned int maxval = source->maxval; if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width)) ERREXIT(cinfo, JERR_INPUT_EOF); ptr = source->pub.buffer[0]; bufferptr = source->iobuffer; for (col = cinfo->image_width; col > 0; col--) { register unsigned int temp; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_OUTOFRANGE); *ptr++ = rescale[temp]; } return 1; }
169,838
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: NotificationsNativeHandler::NotificationsNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetNotificationImageSizes", base::Bind(&NotificationsNativeHandler::GetNotificationImageSizes, base::Unretained(this))); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID:
NotificationsNativeHandler::NotificationsNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetNotificationImageSizes", "notifications", base::Bind(&NotificationsNativeHandler::GetNotificationImageSizes, base::Unretained(this))); }
173,276
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep) { struct dwc3_gadget_ep_cmd_params params; struct dwc3_request *req; int starting; int ret; u32 cmd; if (!dwc3_calc_trbs_left(dep)) return 0; starting = !(dep->flags & DWC3_EP_BUSY); dwc3_prepare_trbs(dep); req = next_request(&dep->started_list); if (!req) { dep->flags |= DWC3_EP_PENDING_REQUEST; return 0; } memset(&params, 0, sizeof(params)); if (starting) { params.param0 = upper_32_bits(req->trb_dma); params.param1 = lower_32_bits(req->trb_dma); cmd = DWC3_DEPCMD_STARTTRANSFER; if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) cmd |= DWC3_DEPCMD_PARAM(dep->frame_number); } else { cmd = DWC3_DEPCMD_UPDATETRANSFER | DWC3_DEPCMD_PARAM(dep->resource_index); } ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params); if (ret < 0) { /* * FIXME we need to iterate over the list of requests * here and stop, unmap, free and del each of the linked * requests instead of what we do now. */ if (req->trb) memset(req->trb, 0, sizeof(struct dwc3_trb)); dep->queued_requests--; dwc3_gadget_giveback(dep, req, ret); return ret; } dep->flags |= DWC3_EP_BUSY; if (starting) { dep->resource_index = dwc3_gadget_ep_get_transfer_index(dep); WARN_ON_ONCE(!dep->resource_index); } return 0; } Commit Message: usb: dwc3: gadget: never call ->complete() from ->ep_queue() This is a requirement which has always existed but, somehow, wasn't reflected in the documentation and problems weren't found until now when Tuba Yavuz found a possible deadlock happening between dwc3 and f_hid. She described the situation as follows: spin_lock_irqsave(&hidg->write_spinlock, flags); // first acquire /* we our function has been disabled by host */ if (!hidg->req) { free_ep_req(hidg->in_ep, hidg->req); goto try_again; } [...] status = usb_ep_queue(hidg->in_ep, hidg->req, GFP_ATOMIC); => [...] => usb_gadget_giveback_request => f_hidg_req_complete => spin_lock_irqsave(&hidg->write_spinlock, flags); // second acquire Note that this happens because dwc3 would call ->complete() on a failed usb_ep_queue() due to failed Start Transfer command. This is, anyway, a theoretical situation because dwc3 currently uses "No Response Update Transfer" command for Bulk and Interrupt endpoints. It's still good to make this case impossible to happen even if the "No Reponse Update Transfer" command is changed. Reported-by: Tuba Yavuz <[email protected]> Signed-off-by: Felipe Balbi <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-189
static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep) { struct dwc3_gadget_ep_cmd_params params; struct dwc3_request *req; int starting; int ret; u32 cmd; if (!dwc3_calc_trbs_left(dep)) return 0; starting = !(dep->flags & DWC3_EP_BUSY); dwc3_prepare_trbs(dep); req = next_request(&dep->started_list); if (!req) { dep->flags |= DWC3_EP_PENDING_REQUEST; return 0; } memset(&params, 0, sizeof(params)); if (starting) { params.param0 = upper_32_bits(req->trb_dma); params.param1 = lower_32_bits(req->trb_dma); cmd = DWC3_DEPCMD_STARTTRANSFER; if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) cmd |= DWC3_DEPCMD_PARAM(dep->frame_number); } else { cmd = DWC3_DEPCMD_UPDATETRANSFER | DWC3_DEPCMD_PARAM(dep->resource_index); } ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params); if (ret < 0) { /* * FIXME we need to iterate over the list of requests * here and stop, unmap, free and del each of the linked * requests instead of what we do now. */ if (req->trb) memset(req->trb, 0, sizeof(struct dwc3_trb)); dep->queued_requests--; dwc3_gadget_del_and_unmap_request(dep, req, ret); return ret; } dep->flags |= DWC3_EP_BUSY; if (starting) { dep->resource_index = dwc3_gadget_ep_get_transfer_index(dep); WARN_ON_ONCE(!dep->resource_index); } return 0; }
169,578
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int get_siz(Jpeg2000DecoderContext *s) { int i; int ncomponents; uint32_t log2_chroma_wh = 0; const enum AVPixelFormat *possible_fmts = NULL; int possible_fmts_nb = 0; if (bytestream2_get_bytes_left(&s->g) < 36) return AVERROR_INVALIDDATA; s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz s->width = bytestream2_get_be32u(&s->g); // Width s->height = bytestream2_get_be32u(&s->g); // Height s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz ncomponents = bytestream2_get_be16u(&s->g); // CSiz if (ncomponents <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n", s->ncomponents); return AVERROR_INVALIDDATA; } if (ncomponents > 4) { avpriv_request_sample(s->avctx, "Support for %d components", s->ncomponents); return AVERROR_PATCHWELCOME; } s->ncomponents = ncomponents; if (s->tile_width <= 0 || s->tile_height <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n", s->tile_width, s->tile_height); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) return AVERROR_INVALIDDATA; for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i uint8_t x = bytestream2_get_byteu(&s->g); s->cbps[i] = (x & 0x7f) + 1; s->precision = FFMAX(s->cbps[i], s->precision); s->sgnd[i] = !!(x & 0x80); s->cdx[i] = bytestream2_get_byteu(&s->g); s->cdy[i] = bytestream2_get_byteu(&s->g); if (!s->cdx[i] || !s->cdy[i]) { av_log(s->avctx, AV_LOG_ERROR, "Invalid sample seperation\n"); return AVERROR_INVALIDDATA; } log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2; } s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width); s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height); if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) { s->numXtiles = s->numYtiles = 0; return AVERROR(EINVAL); } s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile)); if (!s->tile) { s->numXtiles = s->numYtiles = 0; return AVERROR(ENOMEM); } for (i = 0; i < s->numXtiles * s->numYtiles; i++) { Jpeg2000Tile *tile = s->tile + i; tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp)); if (!tile->comp) return AVERROR(ENOMEM); } /* compute image size with reduction factor */ s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x, s->reduction_factor); s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y, s->reduction_factor); if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K || s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) { possible_fmts = xyz_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts); } else { switch (s->colour_space) { case 16: possible_fmts = rgb_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts); break; case 17: possible_fmts = gray_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts); break; case 18: possible_fmts = yuv_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts); break; default: possible_fmts = all_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts); break; } } for (i = 0; i < possible_fmts_nb; ++i) { if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) { s->avctx->pix_fmt = possible_fmts[i]; break; } } if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) { av_log(s->avctx, AV_LOG_ERROR, "Unknown pix_fmt, profile: %d, colour_space: %d, " "components: %d, precision: %d, " "cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n", s->avctx->profile, s->colour_space, ncomponents, s->precision, ncomponents > 2 ? s->cdx[1] : 0, ncomponents > 2 ? s->cdy[1] : 0, ncomponents > 2 ? s->cdx[2] : 0, ncomponents > 2 ? s->cdy[2] : 0); } return 0; } Commit Message: avcodec/jpeg2000dec: Check cdx/y values more carefully Some invalid values where not handled correctly in the later pixel format matching code. Fixes out of array accesses Fixes Ticket2848 Found-by: Piotr Bandurski <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int get_siz(Jpeg2000DecoderContext *s) { int i; int ncomponents; uint32_t log2_chroma_wh = 0; const enum AVPixelFormat *possible_fmts = NULL; int possible_fmts_nb = 0; if (bytestream2_get_bytes_left(&s->g) < 36) return AVERROR_INVALIDDATA; s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz s->width = bytestream2_get_be32u(&s->g); // Width s->height = bytestream2_get_be32u(&s->g); // Height s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz ncomponents = bytestream2_get_be16u(&s->g); // CSiz if (ncomponents <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n", s->ncomponents); return AVERROR_INVALIDDATA; } if (ncomponents > 4) { avpriv_request_sample(s->avctx, "Support for %d components", s->ncomponents); return AVERROR_PATCHWELCOME; } s->ncomponents = ncomponents; if (s->tile_width <= 0 || s->tile_height <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n", s->tile_width, s->tile_height); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) return AVERROR_INVALIDDATA; for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i uint8_t x = bytestream2_get_byteu(&s->g); s->cbps[i] = (x & 0x7f) + 1; s->precision = FFMAX(s->cbps[i], s->precision); s->sgnd[i] = !!(x & 0x80); s->cdx[i] = bytestream2_get_byteu(&s->g); s->cdy[i] = bytestream2_get_byteu(&s->g); if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4 || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) { av_log(s->avctx, AV_LOG_ERROR, "Invalid sample seperation\n"); return AVERROR_INVALIDDATA; } log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2; } s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width); s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height); if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) { s->numXtiles = s->numYtiles = 0; return AVERROR(EINVAL); } s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile)); if (!s->tile) { s->numXtiles = s->numYtiles = 0; return AVERROR(ENOMEM); } for (i = 0; i < s->numXtiles * s->numYtiles; i++) { Jpeg2000Tile *tile = s->tile + i; tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp)); if (!tile->comp) return AVERROR(ENOMEM); } /* compute image size with reduction factor */ s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x, s->reduction_factor); s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y, s->reduction_factor); if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K || s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) { possible_fmts = xyz_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts); } else { switch (s->colour_space) { case 16: possible_fmts = rgb_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts); break; case 17: possible_fmts = gray_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts); break; case 18: possible_fmts = yuv_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts); break; default: possible_fmts = all_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts); break; } } for (i = 0; i < possible_fmts_nb; ++i) { if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) { s->avctx->pix_fmt = possible_fmts[i]; break; } } if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) { av_log(s->avctx, AV_LOG_ERROR, "Unknown pix_fmt, profile: %d, colour_space: %d, " "components: %d, precision: %d, " "cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n", s->avctx->profile, s->colour_space, ncomponents, s->precision, ncomponents > 2 ? s->cdx[1] : 0, ncomponents > 2 ? s->cdy[1] : 0, ncomponents > 2 ? s->cdx[2] : 0, ncomponents > 2 ? s->cdy[2] : 0); } return 0; }
165,923
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CopyFromOMX(const OMX_BUFFERHEADERTYPE *header) { if (!mIsBackup) { return; } sp<ABuffer> codec = getBuffer(header, false /* backup */, true /* limit */); memcpy((OMX_U8 *)mMem->pointer() + header->nOffset, codec->data(), codec->size()); } 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
void CopyFromOMX(const OMX_BUFFERHEADERTYPE *header) { if (!mCopyFromOmx) { return; } sp<ABuffer> codec = getBuffer(header, false /* backup */, true /* limit */); memcpy((OMX_U8 *)mMem->pointer() + header->nOffset, codec->data(), codec->size()); }
174,127
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void show_object_with_name(FILE *out, struct object *obj, struct strbuf *path, const char *component) { char *name = path_name(path, component); char *p; fprintf(out, "%s ", oid_to_hex(&obj->oid)); for (p = name; *p && *p != '\n'; p++) fputc(*p, out); fputc('\n', out); free(name); } 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
void show_object_with_name(FILE *out, struct object *obj, const char *p; fprintf(out, "%s ", oid_to_hex(&obj->oid)); for (p = name; *p && *p != '\n'; p++) fputc(*p, out); fputc('\n', out); }
167,427
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_CreateFloat( double num ) { cJSON *item = cJSON_New_Item(); if ( item ) { item->type = cJSON_Number; item->valuefloat = num; item->valueint = num; } return 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
cJSON *cJSON_CreateFloat( double num )
167,272
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void locationWithPerWorldBindingsAttributeSetterForMainWorld(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->locationWithPerWorldBindings()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void locationWithPerWorldBindingsAttributeSetterForMainWorld(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationWithPerWorldBindings()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); }
171,690
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void OMXNodeInstance::invalidateBufferID(OMX::buffer_id buffer __unused) { } Commit Message: IOMX: Enable buffer ptr to buffer id translation for arm32 Bug: 20634516 Change-Id: Iac9eac3cb251eccd9bbad5df7421a07edc21da0c (cherry picked from commit 2d6b6601743c3c6960c6511a2cb774ef902759f4) CWE ID: CWE-119
void OMXNodeInstance::invalidateBufferID(OMX::buffer_id buffer __unused) {
173,359
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MediaInterfaceProxy::CreateCdm( media::mojom::ContentDecryptionModuleRequest request) { DCHECK(thread_checker_.CalledOnValidThread()); GetMediaInterfaceFactory()->CreateCdm(std::move(request)); } Commit Message: media: Support hosting mojo CDM in a standalone service Currently when mojo CDM is enabled it is hosted in the MediaService running in the process specified by "mojo_media_host". However, on some platforms we need to run mojo CDM and other mojo media services in different processes. For example, on desktop platforms, we want to run mojo video decoder in the GPU process, but run the mojo CDM in the utility process. This CL adds a new build flag "enable_standalone_cdm_service". When enabled, the mojo CDM service will be hosted in a standalone "cdm" service running in the utility process. All other mojo media services will sill be hosted in the "media" servie running in the process specified by "mojo_media_host". BUG=664364 TEST=Encrypted media browser tests using mojo CDM is still working. Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487 Reviewed-on: https://chromium-review.googlesource.com/567172 Commit-Queue: Xiaohan Wang <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Dan Sanders <[email protected]> Cr-Commit-Position: refs/heads/master@{#486947} CWE ID: CWE-119
void MediaInterfaceProxy::CreateCdm( media::mojom::ContentDecryptionModuleRequest request) { DCHECK(thread_checker_.CalledOnValidThread()); GetCdmInterfaceFactory()->CreateCdm(std::move(request)); }
171,936
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SendHandwritingStroke(const HandwritingStroke& stroke) { if (stroke.size() < 2) { LOG(WARNING) << "Empty stroke data or a single dot is passed."; return; } IBusInputContext* context = GetInputContext(input_context_path_, ibus_); if (!context) { return; } const size_t raw_stroke_size = stroke.size() * 2; scoped_array<double> raw_stroke(new double[raw_stroke_size]); for (size_t n = 0; n < stroke.size(); ++n) { raw_stroke[n * 2] = stroke[n].first; // x raw_stroke[n * 2 + 1] = stroke[n].second; // y } ibus_input_context_process_hand_writing_event( context, raw_stroke.get(), raw_stroke_size); g_object_unref(context); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void SendHandwritingStroke(const HandwritingStroke& stroke) { // IBusController override. virtual void SendHandwritingStroke(const HandwritingStroke& stroke) { if (stroke.size() < 2) { LOG(WARNING) << "Empty stroke data or a single dot is passed."; return; } IBusInputContext* context = GetInputContext(input_context_path_, ibus_); if (!context) { return; } const size_t raw_stroke_size = stroke.size() * 2; scoped_array<double> raw_stroke(new double[raw_stroke_size]); for (size_t n = 0; n < stroke.size(); ++n) { raw_stroke[n * 2] = stroke[n].first; // x raw_stroke[n * 2 + 1] = stroke[n].second; // y } ibus_input_context_process_hand_writing_event( context, raw_stroke.get(), raw_stroke_size); g_object_unref(context); }
170,546
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: convert_to_decimal (mpn_t a, size_t extra_zeroes) { mp_limb_t *a_ptr = a.limbs; size_t a_len = a.nlimbs; /* 0.03345 is slightly larger than log(2)/(9*log(10)). */ size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1); char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes)); if (c_ptr != NULL) { char *d_ptr = c_ptr; for (; extra_zeroes > 0; extra_zeroes--) *d_ptr++ = '0'; while (a_len > 0) { /* Divide a by 10^9, in-place. */ mp_limb_t remainder = 0; mp_limb_t *ptr = a_ptr + a_len; size_t count; for (count = a_len; count > 0; count--) { mp_twolimb_t num = ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr; *ptr = num / 1000000000; remainder = num % 1000000000; } /* Store the remainder as 9 decimal digits. */ for (count = 9; count > 0; count--) { *d_ptr++ = '0' + (remainder % 10); remainder = remainder / 10; } /* Normalize a. */ if (a_ptr[a_len - 1] == 0) a_len--; } /* Remove leading zeroes. */ while (d_ptr > c_ptr && d_ptr[-1] == '0') d_ptr--; /* But keep at least one zero. */ if (d_ptr == c_ptr) *d_ptr++ = '0'; /* Terminate the string. */ *d_ptr = '\0'; } return c_ptr; } Commit Message: vasnprintf: Fix heap memory overrun bug. Reported by Ben Pfaff <[email protected]> in <https://lists.gnu.org/archive/html/bug-gnulib/2018-09/msg00107.html>. * lib/vasnprintf.c (convert_to_decimal): Allocate one more byte of memory. * tests/test-vasnprintf.c (test_function): Add another test. CWE ID: CWE-119
convert_to_decimal (mpn_t a, size_t extra_zeroes) { mp_limb_t *a_ptr = a.limbs; size_t a_len = a.nlimbs; /* 0.03345 is slightly larger than log(2)/(9*log(10)). */ size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1); /* We need extra_zeroes bytes for zeroes, followed by c_len bytes for the digits of a, followed by 1 byte for the terminating NUL. */ char *c_ptr = (char *) malloc (xsum (xsum (extra_zeroes, c_len), 1)); if (c_ptr != NULL) { char *d_ptr = c_ptr; for (; extra_zeroes > 0; extra_zeroes--) *d_ptr++ = '0'; while (a_len > 0) { /* Divide a by 10^9, in-place. */ mp_limb_t remainder = 0; mp_limb_t *ptr = a_ptr + a_len; size_t count; for (count = a_len; count > 0; count--) { mp_twolimb_t num = ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr; *ptr = num / 1000000000; remainder = num % 1000000000; } /* Store the remainder as 9 decimal digits. */ for (count = 9; count > 0; count--) { *d_ptr++ = '0' + (remainder % 10); remainder = remainder / 10; } /* Normalize a. */ if (a_ptr[a_len - 1] == 0) a_len--; } /* Remove leading zeroes. */ while (d_ptr > c_ptr && d_ptr[-1] == '0') d_ptr--; /* But keep at least one zero. */ if (d_ptr == c_ptr) *d_ptr++ = '0'; /* Terminate the string. */ *d_ptr = '\0'; } return c_ptr; }
169,013
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline bool unconditional(const struct ipt_ip *ip) { static const struct ipt_ip uncond; return memcmp(ip, &uncond, sizeof(uncond)) == 0; #undef FWINV } Commit Message: netfilter: x_tables: fix unconditional helper Ben Hawkes says: In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it is possible for a user-supplied ipt_entry structure to have a large next_offset field. This field is not bounds checked prior to writing a counter value at the supplied offset. Problem is that mark_source_chains should not have been called -- the rule doesn't have a next entry, so its supposed to return an absolute verdict of either ACCEPT or DROP. However, the function conditional() doesn't work as the name implies. It only checks that the rule is using wildcard address matching. However, an unconditional rule must also not be using any matches (no -m args). The underflow validator only checked the addresses, therefore passing the 'unconditional absolute verdict' test, while mark_source_chains also tested for presence of matches, and thus proceeeded to the next (not-existent) rule. Unify this so that all the callers have same idea of 'unconditional rule'. Reported-by: Ben Hawkes <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119
static inline bool unconditional(const struct ipt_ip *ip) static inline bool unconditional(const struct ipt_entry *e) { static const struct ipt_ip uncond; return e->target_offset == sizeof(struct ipt_entry) && memcmp(&e->ip, &uncond, sizeof(uncond)) == 0; #undef FWINV }
167,371
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: UpdateLibrary* CrosLibrary::GetUpdateLibrary() { return update_lib_.GetDefaultImpl(use_stub_impl_); } 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
UpdateLibrary* CrosLibrary::GetUpdateLibrary() {
170,634
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostViewGuest::AcceleratedSurfaceNew(int32 width_in_pixel, int32 height_in_pixel, uint64 surface_handle) { NOTIMPLEMENTED(); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewGuest::AcceleratedSurfaceNew(int32 width_in_pixel, void RenderWidgetHostViewGuest::AcceleratedSurfaceNew( int32 width_in_pixel, int32 height_in_pixel, uint64 surface_handle, const std::string& mailbox_name) { NOTIMPLEMENTED(); }
171,392
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) { #if WRITE_COMPRESSED_STREAM ++out_frames_; if (pkt->data.frame.pts == 0) write_ivf_file_header(&cfg_, 0, outfile_); write_ivf_frame_header(pkt, outfile_); (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile_); #endif } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) { #if WRITE_COMPRESSED_STREAM virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) { ++out_frames_; if (pkt->data.frame.pts == 0) write_ivf_file_header(&cfg_, 0, outfile_); write_ivf_frame_header(pkt, outfile_); (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile_); }
174,568
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void __svc_rdma_free(struct work_struct *work) { struct svcxprt_rdma *rdma = container_of(work, struct svcxprt_rdma, sc_work); struct svc_xprt *xprt = &rdma->sc_xprt; dprintk("svcrdma: %s(%p)\n", __func__, rdma); if (rdma->sc_qp && !IS_ERR(rdma->sc_qp)) ib_drain_qp(rdma->sc_qp); /* We should only be called from kref_put */ if (kref_read(&xprt->xpt_ref) != 0) pr_err("svcrdma: sc_xprt still in use? (%d)\n", kref_read(&xprt->xpt_ref)); /* * Destroy queued, but not processed read completions. Note * that this cleanup has to be done before destroying the * cm_id because the device ptr is needed to unmap the dma in * svc_rdma_put_context. */ while (!list_empty(&rdma->sc_read_complete_q)) { struct svc_rdma_op_ctxt *ctxt; ctxt = list_first_entry(&rdma->sc_read_complete_q, struct svc_rdma_op_ctxt, list); list_del(&ctxt->list); svc_rdma_put_context(ctxt, 1); } /* Destroy queued, but not processed recv completions */ while (!list_empty(&rdma->sc_rq_dto_q)) { struct svc_rdma_op_ctxt *ctxt; ctxt = list_first_entry(&rdma->sc_rq_dto_q, struct svc_rdma_op_ctxt, list); list_del(&ctxt->list); svc_rdma_put_context(ctxt, 1); } /* Warn if we leaked a resource or under-referenced */ if (rdma->sc_ctxt_used != 0) pr_err("svcrdma: ctxt still in use? (%d)\n", rdma->sc_ctxt_used); /* Final put of backchannel client transport */ if (xprt->xpt_bc_xprt) { xprt_put(xprt->xpt_bc_xprt); xprt->xpt_bc_xprt = NULL; } rdma_dealloc_frmr_q(rdma); svc_rdma_destroy_ctxts(rdma); svc_rdma_destroy_maps(rdma); /* Destroy the QP if present (not a listener) */ if (rdma->sc_qp && !IS_ERR(rdma->sc_qp)) ib_destroy_qp(rdma->sc_qp); if (rdma->sc_sq_cq && !IS_ERR(rdma->sc_sq_cq)) ib_free_cq(rdma->sc_sq_cq); if (rdma->sc_rq_cq && !IS_ERR(rdma->sc_rq_cq)) ib_free_cq(rdma->sc_rq_cq); if (rdma->sc_pd && !IS_ERR(rdma->sc_pd)) ib_dealloc_pd(rdma->sc_pd); /* Destroy the CM ID */ rdma_destroy_id(rdma->sc_cm_id); kfree(rdma); } 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
static void __svc_rdma_free(struct work_struct *work) { struct svcxprt_rdma *rdma = container_of(work, struct svcxprt_rdma, sc_work); struct svc_xprt *xprt = &rdma->sc_xprt; dprintk("svcrdma: %s(%p)\n", __func__, rdma); if (rdma->sc_qp && !IS_ERR(rdma->sc_qp)) ib_drain_qp(rdma->sc_qp); /* We should only be called from kref_put */ if (kref_read(&xprt->xpt_ref) != 0) pr_err("svcrdma: sc_xprt still in use? (%d)\n", kref_read(&xprt->xpt_ref)); /* * Destroy queued, but not processed read completions. Note * that this cleanup has to be done before destroying the * cm_id because the device ptr is needed to unmap the dma in * svc_rdma_put_context. */ while (!list_empty(&rdma->sc_read_complete_q)) { struct svc_rdma_op_ctxt *ctxt; ctxt = list_first_entry(&rdma->sc_read_complete_q, struct svc_rdma_op_ctxt, list); list_del(&ctxt->list); svc_rdma_put_context(ctxt, 1); } /* Destroy queued, but not processed recv completions */ while (!list_empty(&rdma->sc_rq_dto_q)) { struct svc_rdma_op_ctxt *ctxt; ctxt = list_first_entry(&rdma->sc_rq_dto_q, struct svc_rdma_op_ctxt, list); list_del(&ctxt->list); svc_rdma_put_context(ctxt, 1); } /* Warn if we leaked a resource or under-referenced */ if (rdma->sc_ctxt_used != 0) pr_err("svcrdma: ctxt still in use? (%d)\n", rdma->sc_ctxt_used); /* Final put of backchannel client transport */ if (xprt->xpt_bc_xprt) { xprt_put(xprt->xpt_bc_xprt); xprt->xpt_bc_xprt = NULL; } rdma_dealloc_frmr_q(rdma); svc_rdma_destroy_rw_ctxts(rdma); svc_rdma_destroy_ctxts(rdma); /* Destroy the QP if present (not a listener) */ if (rdma->sc_qp && !IS_ERR(rdma->sc_qp)) ib_destroy_qp(rdma->sc_qp); if (rdma->sc_sq_cq && !IS_ERR(rdma->sc_sq_cq)) ib_free_cq(rdma->sc_sq_cq); if (rdma->sc_rq_cq && !IS_ERR(rdma->sc_rq_cq)) ib_free_cq(rdma->sc_rq_cq); if (rdma->sc_pd && !IS_ERR(rdma->sc_pd)) ib_dealloc_pd(rdma->sc_pd); /* Destroy the CM ID */ rdma_destroy_id(rdma->sc_cm_id); kfree(rdma); }
168,176
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) { AC3HeaderInfo *hdr = NULL; struct eac3_info *info; int num_blocks, ret; if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info)))) return AVERROR(ENOMEM); info = track->eac3_priv; if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) { /* drop the packets until we see a good one */ if (!track->entry) { av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n"); ret = 0; } else ret = AVERROR_INVALIDDATA; goto end; } info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000); num_blocks = hdr->num_blocks; if (!info->ec3_done) { /* AC-3 substream must be the first one */ if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) { ret = AVERROR(EINVAL); goto end; } /* this should always be the case, given that our AC-3 parser * concatenates dependent frames to their independent parent */ if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) { /* substream ids must be incremental */ if (hdr->substreamid > info->num_ind_sub + 1) { ret = AVERROR(EINVAL); goto end; } if (hdr->substreamid == info->num_ind_sub + 1) { avpriv_request_sample(track->par, "Multiple independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } else if (hdr->substreamid < info->num_ind_sub || hdr->substreamid == 0 && info->substream[0].bsid) { info->ec3_done = 1; goto concatenate; } } else { if (hdr->substreamid != 0) { avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } } /* fill the info needed for the "dec3" atom */ info->substream[hdr->substreamid].fscod = hdr->sr_code; info->substream[hdr->substreamid].bsid = hdr->bitstream_id; info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode; info->substream[hdr->substreamid].acmod = hdr->channel_mode; info->substream[hdr->substreamid].lfeon = hdr->lfe_on; /* Parse dependent substream(s), if any */ if (pkt->size != hdr->frame_size) { int cumul_size = hdr->frame_size; int parent = hdr->substreamid; while (cumul_size != pkt->size) { GetBitContext gbc; int i; ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size); if (ret < 0) goto end; if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) { ret = AVERROR(EINVAL); goto end; } info->substream[parent].num_dep_sub++; ret /= 8; /* header is parsed up to lfeon, but custom channel map may be needed */ init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret); /* skip bsid */ skip_bits(&gbc, 5); /* skip volume control params */ for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) { skip_bits(&gbc, 5); // skip dialog normalization if (get_bits1(&gbc)) { skip_bits(&gbc, 8); // skip compression gain word } } /* get the dependent stream channel map, if exists */ if (get_bits1(&gbc)) info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f; else info->substream[parent].chan_loc |= hdr->channel_mode; cumul_size += hdr->frame_size; } } } concatenate: if (!info->num_blocks && num_blocks == 6) { ret = pkt->size; goto end; } else if (info->num_blocks + num_blocks > 6) { ret = AVERROR_INVALIDDATA; goto end; } if (!info->num_blocks) { ret = av_packet_ref(&info->pkt, pkt); if (!ret) info->num_blocks = num_blocks; goto end; } else { if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0) goto end; memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size); info->num_blocks += num_blocks; info->pkt.duration += pkt->duration; if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0) goto end; if (info->num_blocks != 6) goto end; av_packet_unref(pkt); av_packet_move_ref(pkt, &info->pkt); info->num_blocks = 0; } ret = pkt->size; end: av_free(hdr); return ret; } Commit Message: avformat/movenc: Do not pass AVCodecParameters in avpriv_request_sample Fixes: out of array read Fixes: ffmpeg_crash_8.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-125
static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) { AC3HeaderInfo *hdr = NULL; struct eac3_info *info; int num_blocks, ret; if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info)))) return AVERROR(ENOMEM); info = track->eac3_priv; if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) { /* drop the packets until we see a good one */ if (!track->entry) { av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n"); ret = 0; } else ret = AVERROR_INVALIDDATA; goto end; } info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000); num_blocks = hdr->num_blocks; if (!info->ec3_done) { /* AC-3 substream must be the first one */ if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) { ret = AVERROR(EINVAL); goto end; } /* this should always be the case, given that our AC-3 parser * concatenates dependent frames to their independent parent */ if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) { /* substream ids must be incremental */ if (hdr->substreamid > info->num_ind_sub + 1) { ret = AVERROR(EINVAL); goto end; } if (hdr->substreamid == info->num_ind_sub + 1) { avpriv_request_sample(mov->fc, "Multiple independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } else if (hdr->substreamid < info->num_ind_sub || hdr->substreamid == 0 && info->substream[0].bsid) { info->ec3_done = 1; goto concatenate; } } else { if (hdr->substreamid != 0) { avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } } /* fill the info needed for the "dec3" atom */ info->substream[hdr->substreamid].fscod = hdr->sr_code; info->substream[hdr->substreamid].bsid = hdr->bitstream_id; info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode; info->substream[hdr->substreamid].acmod = hdr->channel_mode; info->substream[hdr->substreamid].lfeon = hdr->lfe_on; /* Parse dependent substream(s), if any */ if (pkt->size != hdr->frame_size) { int cumul_size = hdr->frame_size; int parent = hdr->substreamid; while (cumul_size != pkt->size) { GetBitContext gbc; int i; ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size); if (ret < 0) goto end; if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) { ret = AVERROR(EINVAL); goto end; } info->substream[parent].num_dep_sub++; ret /= 8; /* header is parsed up to lfeon, but custom channel map may be needed */ init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret); /* skip bsid */ skip_bits(&gbc, 5); /* skip volume control params */ for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) { skip_bits(&gbc, 5); // skip dialog normalization if (get_bits1(&gbc)) { skip_bits(&gbc, 8); // skip compression gain word } } /* get the dependent stream channel map, if exists */ if (get_bits1(&gbc)) info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f; else info->substream[parent].chan_loc |= hdr->channel_mode; cumul_size += hdr->frame_size; } } } concatenate: if (!info->num_blocks && num_blocks == 6) { ret = pkt->size; goto end; } else if (info->num_blocks + num_blocks > 6) { ret = AVERROR_INVALIDDATA; goto end; } if (!info->num_blocks) { ret = av_packet_ref(&info->pkt, pkt); if (!ret) info->num_blocks = num_blocks; goto end; } else { if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0) goto end; memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size); info->num_blocks += num_blocks; info->pkt.duration += pkt->duration; if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0) goto end; if (info->num_blocks != 6) goto end; av_packet_unref(pkt); av_packet_move_ref(pkt, &info->pkt); info->num_blocks = 0; } ret = pkt->size; end: av_free(hdr); return ret; }
169,162
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ip_options_build(struct sk_buff * skb, struct ip_options * opt, __be32 daddr, struct rtable *rt, int is_frag) { unsigned char *iph = skb_network_header(skb); memcpy(&(IPCB(skb)->opt), opt, sizeof(struct ip_options)); memcpy(iph+sizeof(struct iphdr), opt->__data, opt->optlen); opt = &(IPCB(skb)->opt); if (opt->srr) memcpy(iph+opt->srr+iph[opt->srr+1]-4, &daddr, 4); if (!is_frag) { if (opt->rr_needaddr) ip_rt_get_source(iph+opt->rr+iph[opt->rr+2]-5, rt); if (opt->ts_needaddr) ip_rt_get_source(iph+opt->ts+iph[opt->ts+2]-9, rt); if (opt->ts_needtime) { struct timespec tv; __be32 midtime; getnstimeofday(&tv); midtime = htonl((tv.tv_sec % 86400) * MSEC_PER_SEC + tv.tv_nsec / NSEC_PER_MSEC); memcpy(iph+opt->ts+iph[opt->ts+2]-5, &midtime, 4); } return; } if (opt->rr) { memset(iph+opt->rr, IPOPT_NOP, iph[opt->rr+1]); opt->rr = 0; opt->rr_needaddr = 0; } if (opt->ts) { memset(iph+opt->ts, IPOPT_NOP, iph[opt->ts+1]); opt->ts = 0; opt->ts_needaddr = opt->ts_needtime = 0; } } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
void ip_options_build(struct sk_buff * skb, struct ip_options * opt, void ip_options_build(struct sk_buff *skb, struct ip_options *opt, __be32 daddr, struct rtable *rt, int is_frag) { unsigned char *iph = skb_network_header(skb); memcpy(&(IPCB(skb)->opt), opt, sizeof(struct ip_options)); memcpy(iph+sizeof(struct iphdr), opt->__data, opt->optlen); opt = &(IPCB(skb)->opt); if (opt->srr) memcpy(iph+opt->srr+iph[opt->srr+1]-4, &daddr, 4); if (!is_frag) { if (opt->rr_needaddr) ip_rt_get_source(iph+opt->rr+iph[opt->rr+2]-5, rt); if (opt->ts_needaddr) ip_rt_get_source(iph+opt->ts+iph[opt->ts+2]-9, rt); if (opt->ts_needtime) { struct timespec tv; __be32 midtime; getnstimeofday(&tv); midtime = htonl((tv.tv_sec % 86400) * MSEC_PER_SEC + tv.tv_nsec / NSEC_PER_MSEC); memcpy(iph+opt->ts+iph[opt->ts+2]-5, &midtime, 4); } return; } if (opt->rr) { memset(iph+opt->rr, IPOPT_NOP, iph[opt->rr+1]); opt->rr = 0; opt->rr_needaddr = 0; } if (opt->ts) { memset(iph+opt->ts, IPOPT_NOP, iph[opt->ts+1]); opt->ts = 0; opt->ts_needaddr = opt->ts_needtime = 0; } }
165,556
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PatternMatch(char *pat, int patdashes, char *string, int stringdashes) { char c, t; if (stringdashes < patdashes) return 0; for (;;) { switch (c = *pat++) { case '*': if (!(c = *pat++)) return 1; if (c == XK_minus) { patdashes--; for (;;) { while ((t = *string++) != XK_minus) if (!t) return 0; stringdashes--; if (PatternMatch(pat, patdashes, string, stringdashes)) return 1; if (stringdashes == patdashes) return 0; } } else { for (;;) { while ((t = *string++) != c) { if (!t) return 0; if (t == XK_minus) { if (stringdashes-- < patdashes) return 0; } } if (PatternMatch(pat, patdashes, string, stringdashes)) return 1; } } case '?': if (*string++ == XK_minus) stringdashes--; break; case '\0': return (*string == '\0'); patdashes--; stringdashes--; break; } return 0; default: if (c == *string++) break; return 0; } } Commit Message: CWE ID: CWE-125
PatternMatch(char *pat, int patdashes, char *string, int stringdashes) { char c, t; if (stringdashes < patdashes) return 0; for (;;) { switch (c = *pat++) { case '*': if (!(c = *pat++)) return 1; if (c == XK_minus) { patdashes--; for (;;) { while ((t = *string++) != XK_minus) if (!t) return 0; stringdashes--; if (PatternMatch(pat, patdashes, string, stringdashes)) return 1; if (stringdashes == patdashes) return 0; } } else { for (;;) { while ((t = *string++) != c) { if (!t) return 0; if (t == XK_minus) { if (stringdashes-- < patdashes) return 0; } } if (PatternMatch(pat, patdashes, string, stringdashes)) return 1; } } case '?': if ((t = *string++) == XK_minus) stringdashes--; if (!t) return 0; break; case '\0': return (*string == '\0'); patdashes--; stringdashes--; break; } return 0; default: if (c == *string++) break; return 0; } }
164,693
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void libxsmm_sparse_csr_reader( libxsmm_generated_code* io_generated_code, const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_INPUT ); return; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csr_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_LEN ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC data-structure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * ((size_t)(*o_row_count) + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csr_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_ALLOC_DATA ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int) * ((size_t)(*o_row_count) + 1)); memset(*o_column_idx, 0, sizeof(unsigned int) * (*o_element_count)); memset(*o_values, 0, sizeof(double) * (*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int) * (*o_row_count)); /* init column idx */ for ( l_i = 0; l_i <= *o_row_count; ++l_i ) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_DESC ); fclose( l_csr_file_handle ); /* close mtx file */ return; } /* now we read the actual content */ } else { unsigned int l_row = 0, l_column = 0; double l_value = 0; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csr_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_ELEMS ); return; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_LEN ); return; } if ( l_row_idx_id != NULL ) { /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ free( l_row_idx_id ); } } Commit Message: Issue #287: made CSR/CSC readers more robust against invalid input (case #1). CWE ID: CWE-119
void libxsmm_sparse_csr_reader( libxsmm_generated_code* io_generated_code, const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_INPUT ); return; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csr_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_LEN ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if (3 == sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) && 0 != *o_row_count && 0 != *o_column_count && 0 != *o_element_count) { /* allocate CSC data-structure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * ((size_t)(*o_row_count) + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csr_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_ALLOC_DATA ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int) * ((size_t)(*o_row_count) + 1)); memset(*o_column_idx, 0, sizeof(unsigned int) * (*o_element_count)); memset(*o_values, 0, sizeof(double) * (*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int) * (*o_row_count)); /* init column idx */ for ( l_i = 0; l_i <= *o_row_count; ++l_i ) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_DESC ); fclose( l_csr_file_handle ); /* close mtx file */ return; } /* now we read the actual content */ } else { unsigned int l_row = 0, l_column = 0; double l_value = 0; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csr_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_ELEMS ); return; } /* adjust numbers to zero termination */ LIBXSMM_ASSERT(0 != l_row && 0 != l_column); l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_LEN ); return; } if ( l_row_idx_id != NULL ) { /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ free( l_row_idx_id ); } }
168,951
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GLES2DecoderImpl::ClearUnclearedAttachments( GLenum target, Framebuffer* framebuffer) { if (target == GL_READ_FRAMEBUFFER_EXT) { glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0); glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, framebuffer->service_id()); } GLbitfield clear_bits = 0; if (framebuffer->HasUnclearedAttachment(GL_COLOR_ATTACHMENT0)) { glClearColor( 0.0f, 0.0f, 0.0f, (GLES2Util::GetChannelsForFormat( framebuffer->GetColorAttachmentFormat()) & 0x0008) != 0 ? 0.0f : 1.0f); state_.SetDeviceColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); clear_bits |= GL_COLOR_BUFFER_BIT; } if (framebuffer->HasUnclearedAttachment(GL_STENCIL_ATTACHMENT) || framebuffer->HasUnclearedAttachment(GL_DEPTH_STENCIL_ATTACHMENT)) { glClearStencil(0); state_.SetDeviceStencilMaskSeparate(GL_FRONT, -1); state_.SetDeviceStencilMaskSeparate(GL_BACK, -1); clear_bits |= GL_STENCIL_BUFFER_BIT; } if (framebuffer->HasUnclearedAttachment(GL_DEPTH_ATTACHMENT) || framebuffer->HasUnclearedAttachment(GL_DEPTH_STENCIL_ATTACHMENT)) { glClearDepth(1.0f); state_.SetDeviceDepthMask(GL_TRUE); clear_bits |= GL_DEPTH_BUFFER_BIT; } state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false); glClear(clear_bits); framebuffer_manager()->MarkAttachmentsAsCleared( framebuffer, renderbuffer_manager(), texture_manager()); RestoreClearState(); if (target == GL_READ_FRAMEBUFFER_EXT) { glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, framebuffer->service_id()); Framebuffer* draw_framebuffer = GetFramebufferInfoForTarget(GL_DRAW_FRAMEBUFFER_EXT); GLuint service_id = draw_framebuffer ? draw_framebuffer->service_id() : GetBackbufferServiceId(); glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, service_id); } } 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
void GLES2DecoderImpl::ClearUnclearedAttachments( GLenum target, Framebuffer* framebuffer) { if (target == GL_READ_FRAMEBUFFER_EXT) { glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0); glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, framebuffer->service_id()); } GLbitfield clear_bits = 0; if (framebuffer->HasUnclearedColorAttachments()) { glClearColor( 0.0f, 0.0f, 0.0f, (GLES2Util::GetChannelsForFormat( framebuffer->GetColorAttachmentFormat()) & 0x0008) != 0 ? 0.0f : 1.0f); state_.SetDeviceColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); clear_bits |= GL_COLOR_BUFFER_BIT; framebuffer->PrepareDrawBuffersForClear(); } if (framebuffer->HasUnclearedAttachment(GL_STENCIL_ATTACHMENT) || framebuffer->HasUnclearedAttachment(GL_DEPTH_STENCIL_ATTACHMENT)) { glClearStencil(0); state_.SetDeviceStencilMaskSeparate(GL_FRONT, -1); state_.SetDeviceStencilMaskSeparate(GL_BACK, -1); clear_bits |= GL_STENCIL_BUFFER_BIT; } if (framebuffer->HasUnclearedAttachment(GL_DEPTH_ATTACHMENT) || framebuffer->HasUnclearedAttachment(GL_DEPTH_STENCIL_ATTACHMENT)) { glClearDepth(1.0f); state_.SetDeviceDepthMask(GL_TRUE); clear_bits |= GL_DEPTH_BUFFER_BIT; } state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false); glClear(clear_bits); if ((clear_bits | GL_COLOR_BUFFER_BIT) != 0) framebuffer->RestoreDrawBuffersAfterClear(); framebuffer_manager()->MarkAttachmentsAsCleared( framebuffer, renderbuffer_manager(), texture_manager()); RestoreClearState(); if (target == GL_READ_FRAMEBUFFER_EXT) { glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, framebuffer->service_id()); Framebuffer* draw_framebuffer = GetFramebufferInfoForTarget(GL_DRAW_FRAMEBUFFER_EXT); GLuint service_id = draw_framebuffer ? draw_framebuffer->service_id() : GetBackbufferServiceId(); glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, service_id); } }
171,658
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static boolean ReadICCProfile(j_decompress_ptr jpeg_info) { char magick[12]; ErrorManager *error_manager; ExceptionInfo *exception; Image *image; MagickBooleanType status; register ssize_t i; register unsigned char *p; size_t length; StringInfo *icc_profile, *profile; /* Read color profile. */ length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8); length+=(size_t) GetCharacter(jpeg_info); length-=2; if (length <= 14) { while (length-- > 0) if (GetCharacter(jpeg_info) == EOF) break; return(TRUE); } for (i=0; i < 12; i++) magick[i]=(char) GetCharacter(jpeg_info); if (LocaleCompare(magick,ICC_PROFILE) != 0) { /* Not a ICC profile, return. */ for (i=0; i < (ssize_t) (length-12); i++) if (GetCharacter(jpeg_info) == EOF) break; return(TRUE); } (void) GetCharacter(jpeg_info); /* id */ (void) GetCharacter(jpeg_info); /* markers */ length-=14; error_manager=(ErrorManager *) jpeg_info->client_data; exception=error_manager->exception; image=error_manager->image; profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } error_manager->profile=profile; p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) length; i++) { int c; c=GetCharacter(jpeg_info); if (c == EOF) break; *p++=(unsigned char) c; } if (i != (ssize_t) length) { profile=DestroyStringInfo(profile); (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"InsufficientImageDataInFile","`%s'", image->filename); return(FALSE); } error_manager->profile=NULL; icc_profile=(StringInfo *) GetImageProfile(image,"icc"); if (icc_profile != (StringInfo *) NULL) { ConcatenateStringInfo(icc_profile,profile); profile=DestroyStringInfo(profile); } else { status=SetImageProfile(image,"icc",profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Profile: ICC, %.20g bytes",(double) length); return(TRUE); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1641 CWE ID:
static boolean ReadICCProfile(j_decompress_ptr jpeg_info) { char magick[12]; ErrorManager *error_manager; ExceptionInfo *exception; Image *image; MagickBooleanType status; register ssize_t i; register unsigned char *p; size_t length; StringInfo *icc_profile, *profile; /* Read color profile. */ length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8); length+=(size_t) GetCharacter(jpeg_info); length-=2; if (length <= 14) { while (length-- > 0) if (GetCharacter(jpeg_info) == EOF) break; return(TRUE); } for (i=0; i < 12; i++) magick[i]=(char) GetCharacter(jpeg_info); if (LocaleCompare(magick,ICC_PROFILE) != 0) { /* Not a ICC profile, return. */ for (i=0; i < (ssize_t) (length-12); i++) if (GetCharacter(jpeg_info) == EOF) break; return(TRUE); } (void) GetCharacter(jpeg_info); /* id */ (void) GetCharacter(jpeg_info); /* markers */ length-=14; error_manager=(ErrorManager *) jpeg_info->client_data; exception=error_manager->exception; image=error_manager->image; profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } error_manager->profile=profile; p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) length; i++) { int c; c=GetCharacter(jpeg_info); if (c == EOF) break; *p++=(unsigned char) c; } error_manager->profile=NULL; if (i != (ssize_t) length) { profile=DestroyStringInfo(profile); (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"InsufficientImageDataInFile","`%s'", image->filename); return(FALSE); } icc_profile=(StringInfo *) GetImageProfile(image,"icc"); if (icc_profile != (StringInfo *) NULL) { ConcatenateStringInfo(icc_profile,profile); profile=DestroyStringInfo(profile); } else { status=SetImageProfile(image,"icc",profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Profile: ICC, %.20g bytes",(double) length); return(TRUE); }
169,487
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AcceleratedStaticBitmapImage::CopyToTexture( gpu::gles2::GLES2Interface* dest_gl, GLenum dest_target, GLuint dest_texture_id, bool unpack_premultiply_alpha, bool unpack_flip_y, const IntPoint& dest_point, const IntRect& source_sub_rectangle) { CheckThread(); if (!IsValid()) return false; DCHECK(texture_holder_->IsCrossThread() || dest_gl != ContextProviderWrapper()->ContextProvider()->ContextGL()); EnsureMailbox(kUnverifiedSyncToken, GL_NEAREST); dest_gl->WaitSyncTokenCHROMIUM( texture_holder_->GetSyncToken().GetConstData()); GLuint source_texture_id = dest_gl->CreateAndConsumeTextureCHROMIUM( texture_holder_->GetMailbox().name); dest_gl->CopySubTextureCHROMIUM( source_texture_id, 0, dest_target, dest_texture_id, 0, dest_point.X(), dest_point.Y(), source_sub_rectangle.X(), source_sub_rectangle.Y(), source_sub_rectangle.Width(), source_sub_rectangle.Height(), unpack_flip_y ? GL_FALSE : GL_TRUE, GL_FALSE, unpack_premultiply_alpha ? GL_FALSE : GL_TRUE); dest_gl->DeleteTextures(1, &source_texture_id); gpu::SyncToken sync_token; dest_gl->GenUnverifiedSyncTokenCHROMIUM(sync_token.GetData()); texture_holder_->UpdateSyncToken(sync_token); return true; } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <[email protected]> Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
bool AcceleratedStaticBitmapImage::CopyToTexture( gpu::gles2::GLES2Interface* dest_gl, GLenum dest_target, GLuint dest_texture_id, bool unpack_premultiply_alpha, bool unpack_flip_y, const IntPoint& dest_point, const IntRect& source_sub_rectangle) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (!IsValid()) return false; DCHECK(texture_holder_->IsCrossThread() || dest_gl != ContextProviderWrapper()->ContextProvider()->ContextGL()); EnsureMailbox(kUnverifiedSyncToken, GL_NEAREST); dest_gl->WaitSyncTokenCHROMIUM( texture_holder_->GetSyncToken().GetConstData()); GLuint source_texture_id = dest_gl->CreateAndConsumeTextureCHROMIUM( texture_holder_->GetMailbox().name); dest_gl->CopySubTextureCHROMIUM( source_texture_id, 0, dest_target, dest_texture_id, 0, dest_point.X(), dest_point.Y(), source_sub_rectangle.X(), source_sub_rectangle.Y(), source_sub_rectangle.Width(), source_sub_rectangle.Height(), unpack_flip_y ? GL_FALSE : GL_TRUE, GL_FALSE, unpack_premultiply_alpha ? GL_FALSE : GL_TRUE); dest_gl->DeleteTextures(1, &source_texture_id); gpu::SyncToken sync_token; dest_gl->GenUnverifiedSyncTokenCHROMIUM(sync_token.GetData()); texture_holder_->UpdateSyncToken(sync_token); return true; }
172,591
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Cluster::GetIndex() const { return m_index; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Cluster::GetIndex() const Cluster::Cluster(Segment* pSegment, long idx, long long element_start /* long long element_size */) : m_pSegment(pSegment), m_element_start(element_start), m_index(idx), m_pos(element_start), m_element_size(-1 /* element_size */), m_timecode(-1), m_entries(NULL), m_entries_size(0), m_entries_count(-1) // means "has not been parsed yet" {} Cluster::~Cluster() { if (m_entries_count <= 0) return; BlockEntry** i = m_entries; BlockEntry** const j = m_entries + m_entries_count; while (i != j) { BlockEntry* p = *i++; assert(p); delete p; } delete[] m_entries; }
174,328
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int raw_cmd_copyout(int cmd, void __user *param, struct floppy_raw_cmd *ptr) { int ret; while (ptr) { ret = copy_to_user(param, ptr, sizeof(*ptr)); if (ret) return -EFAULT; param += sizeof(struct floppy_raw_cmd); if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) { if (ptr->length >= 0 && ptr->length <= ptr->buffer_length) { long length = ptr->buffer_length - ptr->length; ret = fd_copyout(ptr->data, ptr->kernel_data, length); if (ret) return ret; } } ptr = ptr->next; } return 0; } Commit Message: floppy: don't write kernel-only members to FDRAWCMD ioctl output Do not leak kernel-only floppy_raw_cmd structure members to userspace. This includes the linked-list pointer and the pointer to the allocated DMA space. Signed-off-by: Matthew Daley <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
static int raw_cmd_copyout(int cmd, void __user *param, struct floppy_raw_cmd *ptr) { int ret; while (ptr) { struct floppy_raw_cmd cmd = *ptr; cmd.next = NULL; cmd.kernel_data = NULL; ret = copy_to_user(param, &cmd, sizeof(cmd)); if (ret) return -EFAULT; param += sizeof(struct floppy_raw_cmd); if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) { if (ptr->length >= 0 && ptr->length <= ptr->buffer_length) { long length = ptr->buffer_length - ptr->length; ret = fd_copyout(ptr->data, ptr->kernel_data, length); if (ret) return ret; } } ptr = ptr->next; } return 0; }
166,434
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SoftHEVC::onQueueFilled(OMX_U32 portIndex) { UNUSED(portIndex); if (mSignalledError) { return; } if (mOutputPortSettingsChange != NONE) { return; } if (NULL == mCodecCtx) { if (OK != initDecoder()) { return; } } if (outputBufferWidth() != mStride) { /* Set the run-time (dynamic) parameters */ mStride = outputBufferWidth(); setParams(mStride); } List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex); List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); /* If input EOS is seen and decoder is not in flush mode, * set the decoder in flush mode. * There can be a case where EOS is sent along with last picture data * In that case, only after decoding that input data, decoder has to be * put in flush. This case is handled here */ if (mReceivedEOS && !mIsInFlush) { setFlushMode(); } while (!outQueue.empty()) { BufferInfo *inInfo; OMX_BUFFERHEADERTYPE *inHeader; BufferInfo *outInfo; OMX_BUFFERHEADERTYPE *outHeader; size_t timeStampIx; inInfo = NULL; inHeader = NULL; if (!mIsInFlush) { if (!inQueue.empty()) { inInfo = *inQueue.begin(); inHeader = inInfo->mHeader; } else { break; } } outInfo = *outQueue.begin(); outHeader = outInfo->mHeader; outHeader->nFlags = 0; outHeader->nTimeStamp = 0; outHeader->nOffset = 0; if (inHeader != NULL && (inHeader->nFlags & OMX_BUFFERFLAG_EOS)) { mReceivedEOS = true; if (inHeader->nFilledLen == 0) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); inHeader = NULL; setFlushMode(); } } /* Get a free slot in timestamp array to hold input timestamp */ { size_t i; timeStampIx = 0; for (i = 0; i < MAX_TIME_STAMPS; i++) { if (!mTimeStampsValid[i]) { timeStampIx = i; break; } } if (inHeader != NULL) { mTimeStampsValid[timeStampIx] = true; mTimeStamps[timeStampIx] = inHeader->nTimeStamp; } } { ivd_video_decode_ip_t s_dec_ip; ivd_video_decode_op_t s_dec_op; WORD32 timeDelay, timeTaken; size_t sizeY, sizeUV; setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx); GETTIME(&mTimeStart, NULL); /* Compute time elapsed between end of previous decode() * to start of current decode() */ TIME_DIFF(mTimeEnd, mTimeStart, timeDelay); IV_API_CALL_STATUS_T status; status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op); bool resChanged = (IVD_RES_CHANGED == (s_dec_op.u4_error_code & 0xFF)); GETTIME(&mTimeEnd, NULL); /* Compute time taken for decode() */ TIME_DIFF(mTimeStart, mTimeEnd, timeTaken); ALOGV("timeTaken=%6d delay=%6d numBytes=%6d", timeTaken, timeDelay, s_dec_op.u4_num_bytes_consumed); if (s_dec_op.u4_frame_decoded_flag && !mFlushNeeded) { mFlushNeeded = true; } if ((inHeader != NULL) && (1 != s_dec_op.u4_frame_decoded_flag)) { /* If the input did not contain picture data, then ignore * the associated timestamp */ mTimeStampsValid[timeStampIx] = false; } if (mChangingResolution && !s_dec_op.u4_output_present) { mChangingResolution = false; resetDecoder(); resetPlugin(); continue; } if (resChanged) { mChangingResolution = true; if (mFlushNeeded) { setFlushMode(); } continue; } if ((0 < s_dec_op.u4_pic_wd) && (0 < s_dec_op.u4_pic_ht)) { uint32_t width = s_dec_op.u4_pic_wd; uint32_t height = s_dec_op.u4_pic_ht; bool portWillReset = false; handlePortSettingsChange(&portWillReset, width, height); if (portWillReset) { resetDecoder(); return; } } if (s_dec_op.u4_output_present) { outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2; outHeader->nTimeStamp = mTimeStamps[s_dec_op.u4_ts]; mTimeStampsValid[s_dec_op.u4_ts] = false; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } else { /* If in flush mode and no output is returned by the codec, * then come out of flush mode */ mIsInFlush = false; /* If EOS was recieved on input port and there is no output * from the codec, then signal EOS on output port */ if (mReceivedEOS) { outHeader->nFilledLen = 0; outHeader->nFlags |= OMX_BUFFERFLAG_EOS; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; resetPlugin(); } } } if (inHeader != NULL) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } } } Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec Bug: 27833616 Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738 (cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d) CWE ID: CWE-20
void SoftHEVC::onQueueFilled(OMX_U32 portIndex) { UNUSED(portIndex); if (mSignalledError) { return; } if (mOutputPortSettingsChange != NONE) { return; } if (NULL == mCodecCtx) { if (OK != initDecoder()) { return; } } if (outputBufferWidth() != mStride) { /* Set the run-time (dynamic) parameters */ mStride = outputBufferWidth(); setParams(mStride); } List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex); List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); /* If input EOS is seen and decoder is not in flush mode, * set the decoder in flush mode. * There can be a case where EOS is sent along with last picture data * In that case, only after decoding that input data, decoder has to be * put in flush. This case is handled here */ if (mReceivedEOS && !mIsInFlush) { setFlushMode(); } while (!outQueue.empty()) { BufferInfo *inInfo; OMX_BUFFERHEADERTYPE *inHeader; BufferInfo *outInfo; OMX_BUFFERHEADERTYPE *outHeader; size_t timeStampIx; inInfo = NULL; inHeader = NULL; if (!mIsInFlush) { if (!inQueue.empty()) { inInfo = *inQueue.begin(); inHeader = inInfo->mHeader; } else { break; } } outInfo = *outQueue.begin(); outHeader = outInfo->mHeader; outHeader->nFlags = 0; outHeader->nTimeStamp = 0; outHeader->nOffset = 0; if (inHeader != NULL && (inHeader->nFlags & OMX_BUFFERFLAG_EOS)) { mReceivedEOS = true; if (inHeader->nFilledLen == 0) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); inHeader = NULL; setFlushMode(); } } /* Get a free slot in timestamp array to hold input timestamp */ { size_t i; timeStampIx = 0; for (i = 0; i < MAX_TIME_STAMPS; i++) { if (!mTimeStampsValid[i]) { timeStampIx = i; break; } } if (inHeader != NULL) { mTimeStampsValid[timeStampIx] = true; mTimeStamps[timeStampIx] = inHeader->nTimeStamp; } } { ivd_video_decode_ip_t s_dec_ip; ivd_video_decode_op_t s_dec_op; WORD32 timeDelay, timeTaken; size_t sizeY, sizeUV; if (!setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx)) { ALOGE("Decoder arg setup failed"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } GETTIME(&mTimeStart, NULL); /* Compute time elapsed between end of previous decode() * to start of current decode() */ TIME_DIFF(mTimeEnd, mTimeStart, timeDelay); IV_API_CALL_STATUS_T status; status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op); bool resChanged = (IVD_RES_CHANGED == (s_dec_op.u4_error_code & 0xFF)); GETTIME(&mTimeEnd, NULL); /* Compute time taken for decode() */ TIME_DIFF(mTimeStart, mTimeEnd, timeTaken); ALOGV("timeTaken=%6d delay=%6d numBytes=%6d", timeTaken, timeDelay, s_dec_op.u4_num_bytes_consumed); if (s_dec_op.u4_frame_decoded_flag && !mFlushNeeded) { mFlushNeeded = true; } if ((inHeader != NULL) && (1 != s_dec_op.u4_frame_decoded_flag)) { /* If the input did not contain picture data, then ignore * the associated timestamp */ mTimeStampsValid[timeStampIx] = false; } if (mChangingResolution && !s_dec_op.u4_output_present) { mChangingResolution = false; resetDecoder(); resetPlugin(); continue; } if (resChanged) { mChangingResolution = true; if (mFlushNeeded) { setFlushMode(); } continue; } if ((0 < s_dec_op.u4_pic_wd) && (0 < s_dec_op.u4_pic_ht)) { uint32_t width = s_dec_op.u4_pic_wd; uint32_t height = s_dec_op.u4_pic_ht; bool portWillReset = false; handlePortSettingsChange(&portWillReset, width, height); if (portWillReset) { resetDecoder(); return; } } if (s_dec_op.u4_output_present) { outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2; outHeader->nTimeStamp = mTimeStamps[s_dec_op.u4_ts]; mTimeStampsValid[s_dec_op.u4_ts] = false; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } else { /* If in flush mode and no output is returned by the codec, * then come out of flush mode */ mIsInFlush = false; /* If EOS was recieved on input port and there is no output * from the codec, then signal EOS on output port */ if (mReceivedEOS) { outHeader->nFilledLen = 0; outHeader->nFlags |= OMX_BUFFERFLAG_EOS; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; resetPlugin(); } } } if (inHeader != NULL) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } } }
174,181
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: base::WaitableEvent* ProxyChannelDelegate::GetShutdownEvent() { return &shutdown_event_; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
base::WaitableEvent* ProxyChannelDelegate::GetShutdownEvent() {
170,734
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: crypto_retrieve_X509_sans(krb5_context context, pkinit_plg_crypto_context plgctx, pkinit_req_crypto_context reqctx, X509 *cert, krb5_principal **princs_ret, krb5_principal **upn_ret, unsigned char ***dns_ret) { krb5_error_code retval = EINVAL; char buf[DN_BUF_LEN]; int p = 0, u = 0, d = 0, ret = 0, l; krb5_principal *princs = NULL; krb5_principal *upns = NULL; unsigned char **dnss = NULL; unsigned int i, num_found = 0, num_sans = 0; X509_EXTENSION *ext = NULL; GENERAL_NAMES *ialt = NULL; GENERAL_NAME *gen = NULL; if (princs_ret != NULL) *princs_ret = NULL; if (upn_ret != NULL) *upn_ret = NULL; if (dns_ret != NULL) *dns_ret = NULL; if (princs_ret == NULL && upn_ret == NULL && dns_ret == NULL) { pkiDebug("%s: nowhere to return any values!\n", __FUNCTION__); return retval; } if (cert == NULL) { pkiDebug("%s: no certificate!\n", __FUNCTION__); return retval; } X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf)); pkiDebug("%s: looking for SANs in cert = %s\n", __FUNCTION__, buf); l = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1); if (l < 0) return 0; if (!(ext = X509_get_ext(cert, l)) || !(ialt = X509V3_EXT_d2i(ext))) { pkiDebug("%s: found no subject alt name extensions\n", __FUNCTION__); retval = ENOENT; goto cleanup; } num_sans = sk_GENERAL_NAME_num(ialt); pkiDebug("%s: found %d subject alt name extension(s)\n", __FUNCTION__, num_sans); /* OK, we're likely returning something. Allocate return values */ if (princs_ret != NULL) { princs = calloc(num_sans + 1, sizeof(krb5_principal)); if (princs == NULL) { retval = ENOMEM; goto cleanup; } } if (upn_ret != NULL) { upns = calloc(num_sans + 1, sizeof(krb5_principal)); if (upns == NULL) { retval = ENOMEM; goto cleanup; } } if (dns_ret != NULL) { dnss = calloc(num_sans + 1, sizeof(*dnss)); if (dnss == NULL) { retval = ENOMEM; goto cleanup; } } for (i = 0; i < num_sans; i++) { krb5_data name = { 0, 0, NULL }; gen = sk_GENERAL_NAME_value(ialt, i); switch (gen->type) { case GEN_OTHERNAME: name.length = gen->d.otherName->value->value.sequence->length; name.data = (char *)gen->d.otherName->value->value.sequence->data; if (princs != NULL && OBJ_cmp(plgctx->id_pkinit_san, gen->d.otherName->type_id) == 0) { #ifdef DEBUG_ASN1 print_buffer_bin((unsigned char *)name.data, name.length, "/tmp/pkinit_san"); #endif ret = k5int_decode_krb5_principal_name(&name, &princs[p]); if (ret) { pkiDebug("%s: failed decoding pkinit san value\n", __FUNCTION__); } else { p++; num_found++; } } else if (upns != NULL && OBJ_cmp(plgctx->id_ms_san_upn, gen->d.otherName->type_id) == 0) { /* Prevent abuse of embedded null characters. */ if (memchr(name.data, '\0', name.length)) break; ret = krb5_parse_name_flags(context, name.data, KRB5_PRINCIPAL_PARSE_ENTERPRISE, &upns[u]); if (ret) { pkiDebug("%s: failed parsing ms-upn san value\n", __FUNCTION__); } else { u++; num_found++; } } else { pkiDebug("%s: unrecognized othername oid in SAN\n", __FUNCTION__); continue; } break; case GEN_DNS: if (dnss != NULL) { /* Prevent abuse of embedded null characters. */ if (memchr(gen->d.dNSName->data, '\0', gen->d.dNSName->length)) break; pkiDebug("%s: found dns name = %s\n", __FUNCTION__, gen->d.dNSName->data); dnss[d] = (unsigned char *) strdup((char *)gen->d.dNSName->data); if (dnss[d] == NULL) { pkiDebug("%s: failed to duplicate dns name\n", __FUNCTION__); } else { d++; num_found++; } } break; default: pkiDebug("%s: SAN type = %d expecting %d\n", __FUNCTION__, gen->type, GEN_OTHERNAME); } } sk_GENERAL_NAME_pop_free(ialt, GENERAL_NAME_free); retval = 0; if (princs) *princs_ret = princs; if (upns) *upn_ret = upns; if (dnss) *dns_ret = dnss; cleanup: if (retval) { if (princs != NULL) { for (i = 0; princs[i] != NULL; i++) krb5_free_principal(context, princs[i]); free(princs); } if (upns != NULL) { for (i = 0; upns[i] != NULL; i++) krb5_free_principal(context, upns[i]); free(upns); } if (dnss != NULL) { for (i = 0; dnss[i] != NULL; i++) free(dnss[i]); free(dnss); } } return retval; } Commit Message: Fix certauth built-in module returns The PKINIT certauth eku module should never authoritatively authorize a certificate, because an extended key usage does not establish a relationship between the certificate and any specific user; it only establishes that the certificate was created for PKINIT client authentication. Therefore, pkinit_eku_authorize() should return KRB5_PLUGIN_NO_HANDLE on success, not 0. The certauth san module should pass if it does not find any SANs of the types it can match against; the presence of other types of SANs should not cause it to explicitly deny a certificate. Check for an empty result from crypto_retrieve_cert_sans() in verify_client_san(), instead of returning ENOENT from crypto_retrieve_cert_sans() when there are no SANs at all. ticket: 8561 CWE ID: CWE-287
crypto_retrieve_X509_sans(krb5_context context, pkinit_plg_crypto_context plgctx, pkinit_req_crypto_context reqctx, X509 *cert, krb5_principal **princs_ret, krb5_principal **upn_ret, unsigned char ***dns_ret) { krb5_error_code retval = EINVAL; char buf[DN_BUF_LEN]; int p = 0, u = 0, d = 0, ret = 0, l; krb5_principal *princs = NULL; krb5_principal *upns = NULL; unsigned char **dnss = NULL; unsigned int i, num_found = 0, num_sans = 0; X509_EXTENSION *ext = NULL; GENERAL_NAMES *ialt = NULL; GENERAL_NAME *gen = NULL; if (princs_ret != NULL) *princs_ret = NULL; if (upn_ret != NULL) *upn_ret = NULL; if (dns_ret != NULL) *dns_ret = NULL; if (princs_ret == NULL && upn_ret == NULL && dns_ret == NULL) { pkiDebug("%s: nowhere to return any values!\n", __FUNCTION__); return retval; } if (cert == NULL) { pkiDebug("%s: no certificate!\n", __FUNCTION__); return retval; } X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf)); pkiDebug("%s: looking for SANs in cert = %s\n", __FUNCTION__, buf); l = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1); if (l < 0) return 0; if (!(ext = X509_get_ext(cert, l)) || !(ialt = X509V3_EXT_d2i(ext))) { pkiDebug("%s: found no subject alt name extensions\n", __FUNCTION__); goto cleanup; } num_sans = sk_GENERAL_NAME_num(ialt); pkiDebug("%s: found %d subject alt name extension(s)\n", __FUNCTION__, num_sans); /* OK, we're likely returning something. Allocate return values */ if (princs_ret != NULL) { princs = calloc(num_sans + 1, sizeof(krb5_principal)); if (princs == NULL) { retval = ENOMEM; goto cleanup; } } if (upn_ret != NULL) { upns = calloc(num_sans + 1, sizeof(krb5_principal)); if (upns == NULL) { retval = ENOMEM; goto cleanup; } } if (dns_ret != NULL) { dnss = calloc(num_sans + 1, sizeof(*dnss)); if (dnss == NULL) { retval = ENOMEM; goto cleanup; } } for (i = 0; i < num_sans; i++) { krb5_data name = { 0, 0, NULL }; gen = sk_GENERAL_NAME_value(ialt, i); switch (gen->type) { case GEN_OTHERNAME: name.length = gen->d.otherName->value->value.sequence->length; name.data = (char *)gen->d.otherName->value->value.sequence->data; if (princs != NULL && OBJ_cmp(plgctx->id_pkinit_san, gen->d.otherName->type_id) == 0) { #ifdef DEBUG_ASN1 print_buffer_bin((unsigned char *)name.data, name.length, "/tmp/pkinit_san"); #endif ret = k5int_decode_krb5_principal_name(&name, &princs[p]); if (ret) { pkiDebug("%s: failed decoding pkinit san value\n", __FUNCTION__); } else { p++; num_found++; } } else if (upns != NULL && OBJ_cmp(plgctx->id_ms_san_upn, gen->d.otherName->type_id) == 0) { /* Prevent abuse of embedded null characters. */ if (memchr(name.data, '\0', name.length)) break; ret = krb5_parse_name_flags(context, name.data, KRB5_PRINCIPAL_PARSE_ENTERPRISE, &upns[u]); if (ret) { pkiDebug("%s: failed parsing ms-upn san value\n", __FUNCTION__); } else { u++; num_found++; } } else { pkiDebug("%s: unrecognized othername oid in SAN\n", __FUNCTION__); continue; } break; case GEN_DNS: if (dnss != NULL) { /* Prevent abuse of embedded null characters. */ if (memchr(gen->d.dNSName->data, '\0', gen->d.dNSName->length)) break; pkiDebug("%s: found dns name = %s\n", __FUNCTION__, gen->d.dNSName->data); dnss[d] = (unsigned char *) strdup((char *)gen->d.dNSName->data); if (dnss[d] == NULL) { pkiDebug("%s: failed to duplicate dns name\n", __FUNCTION__); } else { d++; num_found++; } } break; default: pkiDebug("%s: SAN type = %d expecting %d\n", __FUNCTION__, gen->type, GEN_OTHERNAME); } } sk_GENERAL_NAME_pop_free(ialt, GENERAL_NAME_free); retval = 0; if (princs != NULL && *princs != NULL) { *princs_ret = princs; princs = NULL; } if (upns != NULL && *upns != NULL) { *upn_ret = upns; upns = NULL; } if (dnss != NULL && *dnss != NULL) { *dns_ret = dnss; dnss = NULL; } cleanup: for (i = 0; princs != NULL && princs[i] != NULL; i++) krb5_free_principal(context, princs[i]); free(princs); for (i = 0; upns != NULL && upns[i] != NULL; i++) krb5_free_principal(context, upns[i]); free(upns); for (i = 0; dnss != NULL && dnss[i] != NULL; i++) free(dnss[i]); free(dnss); return retval; }
170,173
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int perf_event_task_disable(void) { struct perf_event *event; mutex_lock(&current->perf_event_mutex); list_for_each_entry(event, &current->perf_event_list, owner_entry) perf_event_for_each_child(event, perf_event_disable); mutex_unlock(&current->perf_event_mutex); return 0; } Commit Message: perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264
int perf_event_task_disable(void) { struct perf_event_context *ctx; struct perf_event *event; mutex_lock(&current->perf_event_mutex); list_for_each_entry(event, &current->perf_event_list, owner_entry) { ctx = perf_event_ctx_lock(event); perf_event_for_each_child(event, _perf_event_disable); perf_event_ctx_unlock(event, ctx); } mutex_unlock(&current->perf_event_mutex); return 0; }
166,989
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CapturerMac::CaptureInvalidRects(CaptureCompletedCallback* callback) { scoped_refptr<CaptureData> data; if (capturing_) { InvalidRects rects; helper_.SwapInvalidRects(rects); VideoFrameBuffer& current_buffer = buffers_[current_buffer_]; current_buffer.Update(); bool flip = true; // GL capturers need flipping. if (cgl_context_) { if (pixel_buffer_object_.get() != 0) { GlBlitFast(current_buffer); } else { GlBlitSlow(current_buffer); } } else { CgBlit(current_buffer, rects); flip = false; } DataPlanes planes; planes.data[0] = current_buffer.ptr(); planes.strides[0] = current_buffer.bytes_per_row(); if (flip) { planes.strides[0] = -planes.strides[0]; planes.data[0] += (current_buffer.size().height() - 1) * current_buffer.bytes_per_row(); } data = new CaptureData(planes, gfx::Size(current_buffer.size()), pixel_format()); data->mutable_dirty_rects() = rects; current_buffer_ = (current_buffer_ + 1) % kNumBuffers; helper_.set_size_most_recent(data->size()); } callback->Run(data); delete callback; } Commit Message: Workaround for bad driver issue with NVIDIA GeForce 7300 GT on Mac 10.5. BUG=87283 TEST=Run on a machine with NVIDIA GeForce 7300 GT on Mac 10.5 immediately after booting. Review URL: http://codereview.chromium.org/7373018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@92651 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void CapturerMac::CaptureInvalidRects(CaptureCompletedCallback* callback) { scoped_refptr<CaptureData> data; if (capturing_) { InvalidRects rects; helper_.SwapInvalidRects(rects); VideoFrameBuffer& current_buffer = buffers_[current_buffer_]; current_buffer.Update(); bool flip = true; // GL capturers need flipping. if (cgl_context_) { if (pixel_buffer_object_.get() != 0) { GlBlitFast(current_buffer); } else { // See comment in scoped_pixel_buffer_object::Init about why the slow // path is always used on 10.5. GlBlitSlow(current_buffer); } } else { CgBlit(current_buffer, rects); flip = false; } DataPlanes planes; planes.data[0] = current_buffer.ptr(); planes.strides[0] = current_buffer.bytes_per_row(); if (flip) { planes.strides[0] = -planes.strides[0]; planes.data[0] += (current_buffer.size().height() - 1) * current_buffer.bytes_per_row(); } data = new CaptureData(planes, gfx::Size(current_buffer.size()), pixel_format()); data->mutable_dirty_rects() = rects; current_buffer_ = (current_buffer_ + 1) % kNumBuffers; helper_.set_size_most_recent(data->size()); } callback->Run(data); delete callback; }
170,316
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message) #if defined(ENABLE_BASIC_PRINTING) IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages) IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog) #endif // ENABLE_BASIC_PRINTING IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone) IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked, SetScriptedPrintBlocked) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID:
bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) { // The class is not designed to handle recursive messages. This is not // expected during regular flow. However, during rendering of content for // printing, lower level code may run nested message loop. E.g. PDF may has // script to show message box http://crbug.com/502562. In that moment browser // may receive updated printer capabilities and decide to restart print // preview generation. When this happened message handling function may // choose to ignore message or safely crash process. ++ipc_nesting_level_; bool handled = true; IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message) #if defined(ENABLE_BASIC_PRINTING) IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages) IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog) #endif // ENABLE_BASIC_PRINTING IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone) IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked, SetScriptedPrintBlocked) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() --ipc_nesting_level_; return handled; }
171,872
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { struct page *page = vmf->page; loff_t size; unsigned long len; int ret; struct file *file = vma->vm_file; struct inode *inode = file_inode(file); struct address_space *mapping = inode->i_mapping; handle_t *handle; get_block_t *get_block; int retries = 0; sb_start_pagefault(inode->i_sb); file_update_time(vma->vm_file); /* Delalloc case is easy... */ if (test_opt(inode->i_sb, DELALLOC) && !ext4_should_journal_data(inode) && !ext4_nonda_switch(inode->i_sb)) { do { ret = block_page_mkwrite(vma, vmf, ext4_da_get_block_prep); } while (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)); goto out_ret; } lock_page(page); size = i_size_read(inode); /* Page got truncated from under us? */ if (page->mapping != mapping || page_offset(page) > size) { unlock_page(page); ret = VM_FAULT_NOPAGE; goto out; } if (page->index == size >> PAGE_CACHE_SHIFT) len = size & ~PAGE_CACHE_MASK; else len = PAGE_CACHE_SIZE; /* * Return if we have all the buffers mapped. This avoids the need to do * journal_start/journal_stop which can block and take a long time */ if (page_has_buffers(page)) { if (!ext4_walk_page_buffers(NULL, page_buffers(page), 0, len, NULL, ext4_bh_unmapped)) { /* Wait so that we don't change page under IO */ wait_for_stable_page(page); ret = VM_FAULT_LOCKED; goto out; } } unlock_page(page); /* OK, we need to fill the hole... */ if (ext4_should_dioread_nolock(inode)) get_block = ext4_get_block_write; else get_block = ext4_get_block; retry_alloc: handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, ext4_writepage_trans_blocks(inode)); if (IS_ERR(handle)) { ret = VM_FAULT_SIGBUS; goto out; } ret = block_page_mkwrite(vma, vmf, get_block); if (!ret && ext4_should_journal_data(inode)) { if (ext4_walk_page_buffers(handle, page_buffers(page), 0, PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) { unlock_page(page); ret = VM_FAULT_SIGBUS; ext4_journal_stop(handle); goto out; } ext4_set_inode_state(inode, EXT4_STATE_JDATA); } ext4_journal_stop(handle); if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) goto retry_alloc; out_ret: ret = block_page_mkwrite_return(ret); out: sb_end_pagefault(inode->i_sb); 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
int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { struct page *page = vmf->page; loff_t size; unsigned long len; int ret; struct file *file = vma->vm_file; struct inode *inode = file_inode(file); struct address_space *mapping = inode->i_mapping; handle_t *handle; get_block_t *get_block; int retries = 0; sb_start_pagefault(inode->i_sb); file_update_time(vma->vm_file); down_read(&EXT4_I(inode)->i_mmap_sem); /* Delalloc case is easy... */ if (test_opt(inode->i_sb, DELALLOC) && !ext4_should_journal_data(inode) && !ext4_nonda_switch(inode->i_sb)) { do { ret = block_page_mkwrite(vma, vmf, ext4_da_get_block_prep); } while (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)); goto out_ret; } lock_page(page); size = i_size_read(inode); /* Page got truncated from under us? */ if (page->mapping != mapping || page_offset(page) > size) { unlock_page(page); ret = VM_FAULT_NOPAGE; goto out; } if (page->index == size >> PAGE_CACHE_SHIFT) len = size & ~PAGE_CACHE_MASK; else len = PAGE_CACHE_SIZE; /* * Return if we have all the buffers mapped. This avoids the need to do * journal_start/journal_stop which can block and take a long time */ if (page_has_buffers(page)) { if (!ext4_walk_page_buffers(NULL, page_buffers(page), 0, len, NULL, ext4_bh_unmapped)) { /* Wait so that we don't change page under IO */ wait_for_stable_page(page); ret = VM_FAULT_LOCKED; goto out; } } unlock_page(page); /* OK, we need to fill the hole... */ if (ext4_should_dioread_nolock(inode)) get_block = ext4_get_block_write; else get_block = ext4_get_block; retry_alloc: handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, ext4_writepage_trans_blocks(inode)); if (IS_ERR(handle)) { ret = VM_FAULT_SIGBUS; goto out; } ret = block_page_mkwrite(vma, vmf, get_block); if (!ret && ext4_should_journal_data(inode)) { if (ext4_walk_page_buffers(handle, page_buffers(page), 0, PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) { unlock_page(page); ret = VM_FAULT_SIGBUS; ext4_journal_stop(handle); goto out; } ext4_set_inode_state(inode, EXT4_STATE_JDATA); } ext4_journal_stop(handle); if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) goto retry_alloc; out_ret: ret = block_page_mkwrite_return(ret); out: up_read(&EXT4_I(inode)->i_mmap_sem); sb_end_pagefault(inode->i_sb); return ret; }
167,489
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GLES2Implementation::BeginQueryEXT(GLenum target, GLuint id) { GPU_CLIENT_SINGLE_THREAD_CHECK(); GPU_CLIENT_LOG("[" << GetLogPrefix() << "] BeginQueryEXT(" << GLES2Util::GetStringQueryTarget(target) << ", " << id << ")"); switch (target) { case GL_COMMANDS_ISSUED_CHROMIUM: case GL_LATENCY_QUERY_CHROMIUM: case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM: case GL_GET_ERROR_QUERY_CHROMIUM: break; case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM: case GL_COMMANDS_COMPLETED_CHROMIUM: if (!capabilities_.sync_query) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for commands completed queries"); return; } break; case GL_SAMPLES_PASSED_ARB: if (!capabilities_.occlusion_query) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for occlusion queries"); return; } break; case GL_ANY_SAMPLES_PASSED: case GL_ANY_SAMPLES_PASSED_CONSERVATIVE: if (!capabilities_.occlusion_query_boolean) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for boolean occlusion queries"); return; } break; case GL_TIME_ELAPSED_EXT: if (!capabilities_.timer_queries) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for timing queries"); return; } break; case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: if (capabilities_.major_version >= 3) break; FALLTHROUGH; default: SetGLError(GL_INVALID_ENUM, "glBeginQueryEXT", "unknown query target"); return; } if (query_tracker_->GetCurrentQuery(target)) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "query already in progress"); return; } if (id == 0) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "id is 0"); return; } if (!GetIdAllocator(IdNamespaces::kQueries)->InUse(id)) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "invalid id"); return; } switch (target) { case GL_TIME_ELAPSED_EXT: if (!query_tracker_->SetDisjointSync(this)) { SetGLError(GL_OUT_OF_MEMORY, "glBeginQueryEXT", "buffer allocation failed"); return; } break; default: break; } if (query_tracker_->BeginQuery(id, target, this)) CheckGLError(); if (target == GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM) { AllocateShadowCopiesForReadback(); } } 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
void GLES2Implementation::BeginQueryEXT(GLenum target, GLuint id) { GPU_CLIENT_SINGLE_THREAD_CHECK(); GPU_CLIENT_LOG("[" << GetLogPrefix() << "] BeginQueryEXT(" << GLES2Util::GetStringQueryTarget(target) << ", " << id << ")"); switch (target) { case GL_COMMANDS_ISSUED_CHROMIUM: case GL_LATENCY_QUERY_CHROMIUM: case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM: case GL_GET_ERROR_QUERY_CHROMIUM: case GL_PROGRAM_COMPLETION_QUERY_CHROMIUM: break; case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM: case GL_COMMANDS_COMPLETED_CHROMIUM: if (!capabilities_.sync_query) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for commands completed queries"); return; } break; case GL_SAMPLES_PASSED_ARB: if (!capabilities_.occlusion_query) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for occlusion queries"); return; } break; case GL_ANY_SAMPLES_PASSED: case GL_ANY_SAMPLES_PASSED_CONSERVATIVE: if (!capabilities_.occlusion_query_boolean) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for boolean occlusion queries"); return; } break; case GL_TIME_ELAPSED_EXT: if (!capabilities_.timer_queries) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for timing queries"); return; } break; case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: if (capabilities_.major_version >= 3) break; FALLTHROUGH; default: SetGLError(GL_INVALID_ENUM, "glBeginQueryEXT", "unknown query target"); return; } if (query_tracker_->GetCurrentQuery(target)) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "query already in progress"); return; } if (id == 0) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "id is 0"); return; } if (!GetIdAllocator(IdNamespaces::kQueries)->InUse(id)) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "invalid id"); return; } switch (target) { case GL_TIME_ELAPSED_EXT: if (!query_tracker_->SetDisjointSync(this)) { SetGLError(GL_OUT_OF_MEMORY, "glBeginQueryEXT", "buffer allocation failed"); return; } break; default: break; } if (query_tracker_->BeginQuery(id, target, this)) CheckGLError(); if (target == GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM) { AllocateShadowCopiesForReadback(); } }
172,527
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __init sit_init(void) { int err; printk(KERN_INFO "IPv6 over IPv4 tunneling driver\n"); if (xfrm4_tunnel_register(&sit_handler, AF_INET6) < 0) { printk(KERN_INFO "sit init: Can't add protocol\n"); return -EAGAIN; } err = register_pernet_device(&sit_net_ops); if (err < 0) xfrm4_tunnel_deregister(&sit_handler, AF_INET6); return err; } Commit Message: tunnels: fix netns vs proto registration ordering Same stuff as in ip_gre patch: receive hook can be called before netns setup is done, oopsing in net_generic(). Signed-off-by: Alexey Dobriyan <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
static int __init sit_init(void) { int err; printk(KERN_INFO "IPv6 over IPv4 tunneling driver\n"); err = register_pernet_device(&sit_net_ops); if (err < 0) return err; err = xfrm4_tunnel_register(&sit_handler, AF_INET6); if (err < 0) { unregister_pernet_device(&sit_net_ops); printk(KERN_INFO "sit init: Can't add protocol\n"); } return err; }
165,878
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CNB::SetupLSO(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength) const { PopulateIPLength(reinterpret_cast<IPv4Header*>(IpHeader), static_cast<USHORT>(EthPayloadLength)); tTcpIpPacketParsingResult packetReview; packetReview = ParaNdis_CheckSumVerifyFlat(reinterpret_cast<IPv4Header*>(IpHeader), EthPayloadLength, pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum, __FUNCTION__); if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS) { auto IpHeaderOffset = m_Context->Offload.ipHeaderOffset; auto VHeader = static_cast<virtio_net_hdr_basic*>(VirtioHeader); auto PriorityHdrLen = (m_ParentNBL->TCI() != 0) ? ETH_PRIORITY_HEADER_SIZE : 0; VHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; VHeader->gso_type = packetReview.ipStatus == ppresIPV4 ? VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6; VHeader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + IpHeaderOffset + PriorityHdrLen); VHeader->gso_size = (USHORT)m_ParentNBL->MSS(); VHeader->csum_start = (USHORT)(m_ParentNBL->TCPHeaderOffset() + PriorityHdrLen); VHeader->csum_offset = TCP_CHECKSUM_OFFSET; } } Commit Message: NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <[email protected]> CWE ID: CWE-20
void CNB::SetupLSO(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength) const { PopulateIPLength(reinterpret_cast<IPv4Header*>(IpHeader), static_cast<USHORT>(EthPayloadLength)); tTcpIpPacketParsingResult packetReview; packetReview = ParaNdis_CheckSumVerifyFlat(reinterpret_cast<IPv4Header*>(IpHeader), EthPayloadLength, pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum, FALSE, __FUNCTION__); if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS) { auto IpHeaderOffset = m_Context->Offload.ipHeaderOffset; auto VHeader = static_cast<virtio_net_hdr_basic*>(VirtioHeader); auto PriorityHdrLen = (m_ParentNBL->TCI() != 0) ? ETH_PRIORITY_HEADER_SIZE : 0; VHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; VHeader->gso_type = packetReview.ipStatus == ppresIPV4 ? VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6; VHeader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + IpHeaderOffset + PriorityHdrLen); VHeader->gso_size = (USHORT)m_ParentNBL->MSS(); VHeader->csum_start = (USHORT)(m_ParentNBL->TCPHeaderOffset() + PriorityHdrLen); VHeader->csum_offset = TCP_CHECKSUM_OFFSET; } }
170,142
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->type == ST_FIELD && ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } } Commit Message: CWE ID: CWE-119
static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; } else { stack->done = 1; } efree(ent1); return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->type == ST_FIELD && ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } }
165,165
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int init_nss_hash(struct crypto_instance *instance) { PK11SlotInfo* hash_slot = NULL; SECItem hash_param; if (!hash_to_nss[instance->crypto_hash_type]) { return 0; } hash_param.type = siBuffer; hash_param.data = 0; hash_param.len = 0; hash_slot = PK11_GetBestSlot(hash_to_nss[instance->crypto_hash_type], NULL); if (hash_slot == NULL) { log_printf(instance->log_level_security, "Unable to find security slot (err %d)", PR_GetError()); return -1; } instance->nss_sym_key_sign = PK11_ImportSymKey(hash_slot, hash_to_nss[instance->crypto_hash_type], PK11_OriginUnwrap, CKA_SIGN, &hash_param, NULL); if (instance->nss_sym_key_sign == NULL) { log_printf(instance->log_level_security, "Failure to import key into NSS (err %d)", PR_GetError()); return -1; } PK11_FreeSlot(hash_slot); return 0; } Commit Message: totemcrypto: fix hmac key initialization Signed-off-by: Fabio M. Di Nitto <[email protected]> Reviewed-by: Jan Friesse <[email protected]> CWE ID:
static int init_nss_hash(struct crypto_instance *instance) { PK11SlotInfo* hash_slot = NULL; SECItem hash_param; if (!hash_to_nss[instance->crypto_hash_type]) { return 0; } hash_param.type = siBuffer; hash_param.data = instance->private_key; hash_param.len = instance->private_key_len; hash_slot = PK11_GetBestSlot(hash_to_nss[instance->crypto_hash_type], NULL); if (hash_slot == NULL) { log_printf(instance->log_level_security, "Unable to find security slot (err %d)", PR_GetError()); return -1; } instance->nss_sym_key_sign = PK11_ImportSymKey(hash_slot, hash_to_nss[instance->crypto_hash_type], PK11_OriginUnwrap, CKA_SIGN, &hash_param, NULL); if (instance->nss_sym_key_sign == NULL) { log_printf(instance->log_level_security, "Failure to import key into NSS (err %d)", PR_GetError()); return -1; } PK11_FreeSlot(hash_slot); return 0; }
166,546
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void color_sycc_to_rgb(opj_image_t *img) { if(img->numcomps < 3) { img->color_space = OPJ_CLRSPC_GRAY; return; } if((img->comps[0].dx == 1) && (img->comps[1].dx == 2) && (img->comps[2].dx == 2) && (img->comps[0].dy == 1) && (img->comps[1].dy == 2) && (img->comps[2].dy == 2))/* horizontal and vertical sub-sample */ { sycc420_to_rgb(img); } else if((img->comps[0].dx == 1) && (img->comps[1].dx == 2) && (img->comps[2].dx == 2) && (img->comps[0].dy == 1) && (img->comps[1].dy == 1) && (img->comps[2].dy == 1))/* horizontal sub-sample only */ { sycc422_to_rgb(img); } else if((img->comps[0].dx == 1) && (img->comps[1].dx == 1) && (img->comps[2].dx == 1) && (img->comps[0].dy == 1) && (img->comps[1].dy == 1) && (img->comps[2].dy == 1))/* no sub-sample */ { sycc444_to_rgb(img); } else { fprintf(stderr,"%s:%d:color_sycc_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,__LINE__); return; } img->color_space = OPJ_CLRSPC_SRGB; }/* color_sycc_to_rgb() */ Commit Message: Fix Out-Of-Bounds Read in sycc42x_to_rgb function (#745) 42x Images with an odd x0/y0 lead to subsampled component starting at the 2nd column/line. That is offset = comp->dx * comp->x0 - image->x0 = 1 Fix #726 CWE ID: CWE-125
void color_sycc_to_rgb(opj_image_t *img) { if(img->numcomps < 3) { img->color_space = OPJ_CLRSPC_GRAY; return; } if((img->comps[0].dx == 1) && (img->comps[1].dx == 2) && (img->comps[2].dx == 2) && (img->comps[0].dy == 1) && (img->comps[1].dy == 2) && (img->comps[2].dy == 2))/* horizontal and vertical sub-sample */ { sycc420_to_rgb(img); } else if((img->comps[0].dx == 1) && (img->comps[1].dx == 2) && (img->comps[2].dx == 2) && (img->comps[0].dy == 1) && (img->comps[1].dy == 1) && (img->comps[2].dy == 1))/* horizontal sub-sample only */ { sycc422_to_rgb(img); } else if((img->comps[0].dx == 1) && (img->comps[1].dx == 1) && (img->comps[2].dx == 1) && (img->comps[0].dy == 1) && (img->comps[1].dy == 1) && (img->comps[2].dy == 1))/* no sub-sample */ { sycc444_to_rgb(img); } else { fprintf(stderr,"%s:%d:color_sycc_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,__LINE__); return; } }/* color_sycc_to_rgb() */
168,838
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FindBarController::MaybeSetPrepopulateText() { #if !defined(OS_MACOSX) FindManager* find_manager = tab_contents_->GetFindManager(); string16 find_string = find_manager->find_text(); if (find_string.empty()) find_string = find_manager->previous_find_text(); if (find_string.empty()) { find_string = FindBarState::GetLastPrepopulateText(tab_contents_->profile()); } find_bar_->SetFindText(find_string); #else #endif } 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
void FindBarController::MaybeSetPrepopulateText() { #if !defined(OS_MACOSX) FindTabHelper* find_tab_helper = tab_contents_->find_tab_helper(); string16 find_string = find_tab_helper->find_text(); if (find_string.empty()) find_string = find_tab_helper->previous_find_text(); if (find_string.empty()) { find_string = FindBarState::GetLastPrepopulateText(tab_contents_->profile()); } find_bar_->SetFindText(find_string); #else #endif }
170,659
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void Sp_match(js_State *J) { js_Regexp *re; const char *text; int len; const char *a, *b, *c, *e; Resub m; text = checkstring(J, 0); if (js_isregexp(J, 1)) js_copy(J, 1); else if (js_isundefined(J, 1)) js_newregexp(J, "", 0); else js_newregexp(J, js_tostring(J, 1), 0); re = js_toregexp(J, -1); if (!(re->flags & JS_REGEXP_G)) { js_RegExp_prototype_exec(J, re, text); return; } re->last = 0; js_newarray(J); len = 0; a = text; e = text + strlen(text); while (a <= e) { if (js_regexec(re->prog, a, &m, a > text ? REG_NOTBOL : 0)) break; b = m.sub[0].sp; c = m.sub[0].ep; js_pushlstring(J, b, c - b); js_setindex(J, -2, len++); a = c; if (c - b == 0) ++a; } if (len == 0) { js_pop(J, 1); js_pushnull(J); } } Commit Message: Bug 700937: Limit recursion in regexp matcher. Also handle negative return code as an error in the JS bindings. CWE ID: CWE-400
static void Sp_match(js_State *J) { js_Regexp *re; const char *text; int len; const char *a, *b, *c, *e; Resub m; text = checkstring(J, 0); if (js_isregexp(J, 1)) js_copy(J, 1); else if (js_isundefined(J, 1)) js_newregexp(J, "", 0); else js_newregexp(J, js_tostring(J, 1), 0); re = js_toregexp(J, -1); if (!(re->flags & JS_REGEXP_G)) { js_RegExp_prototype_exec(J, re, text); return; } re->last = 0; js_newarray(J); len = 0; a = text; e = text + strlen(text); while (a <= e) { if (js_doregexec(J, re->prog, a, &m, a > text ? REG_NOTBOL : 0)) break; b = m.sub[0].sp; c = m.sub[0].ep; js_pushlstring(J, b, c - b); js_setindex(J, -2, len++); a = c; if (c - b == 0) ++a; } if (len == 0) { js_pop(J, 1); js_pushnull(J); } }
169,698