instruction
stringclasses 1
value | input
stringlengths 90
9.3k
| 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: static void print_bpf_insn(struct bpf_insn *insn)
{
u8 class = BPF_CLASS(insn->code);
if (class == BPF_ALU || class == BPF_ALU64) {
if (BPF_SRC(insn->code) == BPF_X)
verbose("(%02x) %sr%d %s %sr%d\n",
insn->code, class == BPF_ALU ? "(u32) " : "",
insn->dst_reg,
bpf_alu_string[BPF_OP(insn->code) >> 4],
class == BPF_ALU ? "(u32) " : "",
insn->src_reg);
else
verbose("(%02x) %sr%d %s %s%d\n",
insn->code, class == BPF_ALU ? "(u32) " : "",
insn->dst_reg,
bpf_alu_string[BPF_OP(insn->code) >> 4],
class == BPF_ALU ? "(u32) " : "",
insn->imm);
} else if (class == BPF_STX) {
if (BPF_MODE(insn->code) == BPF_MEM)
verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
insn->code,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->dst_reg,
insn->off, insn->src_reg);
else if (BPF_MODE(insn->code) == BPF_XADD)
verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
insn->code,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->dst_reg, insn->off,
insn->src_reg);
else
verbose("BUG_%02x\n", insn->code);
} else if (class == BPF_ST) {
if (BPF_MODE(insn->code) != BPF_MEM) {
verbose("BUG_st_%02x\n", insn->code);
return;
}
verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
insn->code,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->dst_reg,
insn->off, insn->imm);
} else if (class == BPF_LDX) {
if (BPF_MODE(insn->code) != BPF_MEM) {
verbose("BUG_ldx_%02x\n", insn->code);
return;
}
verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
insn->code, insn->dst_reg,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->src_reg, insn->off);
} else if (class == BPF_LD) {
if (BPF_MODE(insn->code) == BPF_ABS) {
verbose("(%02x) r0 = *(%s *)skb[%d]\n",
insn->code,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->imm);
} else if (BPF_MODE(insn->code) == BPF_IND) {
verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
insn->code,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->src_reg, insn->imm);
} else if (BPF_MODE(insn->code) == BPF_IMM) {
verbose("(%02x) r%d = 0x%x\n",
insn->code, insn->dst_reg, insn->imm);
} else {
verbose("BUG_ld_%02x\n", insn->code);
return;
}
} else if (class == BPF_JMP) {
u8 opcode = BPF_OP(insn->code);
if (opcode == BPF_CALL) {
verbose("(%02x) call %s#%d\n", insn->code,
func_id_name(insn->imm), insn->imm);
} else if (insn->code == (BPF_JMP | BPF_JA)) {
verbose("(%02x) goto pc%+d\n",
insn->code, insn->off);
} else if (insn->code == (BPF_JMP | BPF_EXIT)) {
verbose("(%02x) exit\n", insn->code);
} else if (BPF_SRC(insn->code) == BPF_X) {
verbose("(%02x) if r%d %s r%d goto pc%+d\n",
insn->code, insn->dst_reg,
bpf_jmp_string[BPF_OP(insn->code) >> 4],
insn->src_reg, insn->off);
} else {
verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
insn->code, insn->dst_reg,
bpf_jmp_string[BPF_OP(insn->code) >> 4],
insn->imm, insn->off);
}
} else {
verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
}
}
Commit Message: bpf: don't let ldimm64 leak map addresses on unprivileged
The patch fixes two things at once:
1) It checks the env->allow_ptr_leaks and only prints the map address to
the log if we have the privileges to do so, otherwise it just dumps 0
as we would when kptr_restrict is enabled on %pK. Given the latter is
off by default and not every distro sets it, I don't want to rely on
this, hence the 0 by default for unprivileged.
2) Printing of ldimm64 in the verifier log is currently broken in that
we don't print the full immediate, but only the 32 bit part of the
first insn part for ldimm64. Thus, fix this up as well; it's okay to
access, since we verified all ldimm64 earlier already (including just
constants) through replace_map_fd_with_map_ptr().
Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs")
Fixes: cbd357008604 ("bpf: verifier (add ability to receive verification log)")
Reported-by: Jann Horn <jannh@google.com>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
Acked-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200
|
static void print_bpf_insn(struct bpf_insn *insn)
static void print_bpf_insn(const struct bpf_verifier_env *env,
const struct bpf_insn *insn)
{
u8 class = BPF_CLASS(insn->code);
if (class == BPF_ALU || class == BPF_ALU64) {
if (BPF_SRC(insn->code) == BPF_X)
verbose("(%02x) %sr%d %s %sr%d\n",
insn->code, class == BPF_ALU ? "(u32) " : "",
insn->dst_reg,
bpf_alu_string[BPF_OP(insn->code) >> 4],
class == BPF_ALU ? "(u32) " : "",
insn->src_reg);
else
verbose("(%02x) %sr%d %s %s%d\n",
insn->code, class == BPF_ALU ? "(u32) " : "",
insn->dst_reg,
bpf_alu_string[BPF_OP(insn->code) >> 4],
class == BPF_ALU ? "(u32) " : "",
insn->imm);
} else if (class == BPF_STX) {
if (BPF_MODE(insn->code) == BPF_MEM)
verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
insn->code,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->dst_reg,
insn->off, insn->src_reg);
else if (BPF_MODE(insn->code) == BPF_XADD)
verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
insn->code,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->dst_reg, insn->off,
insn->src_reg);
else
verbose("BUG_%02x\n", insn->code);
} else if (class == BPF_ST) {
if (BPF_MODE(insn->code) != BPF_MEM) {
verbose("BUG_st_%02x\n", insn->code);
return;
}
verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
insn->code,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->dst_reg,
insn->off, insn->imm);
} else if (class == BPF_LDX) {
if (BPF_MODE(insn->code) != BPF_MEM) {
verbose("BUG_ldx_%02x\n", insn->code);
return;
}
verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
insn->code, insn->dst_reg,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->src_reg, insn->off);
} else if (class == BPF_LD) {
if (BPF_MODE(insn->code) == BPF_ABS) {
verbose("(%02x) r0 = *(%s *)skb[%d]\n",
insn->code,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->imm);
} else if (BPF_MODE(insn->code) == BPF_IND) {
verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
insn->code,
bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
insn->src_reg, insn->imm);
} else if (BPF_MODE(insn->code) == BPF_IMM &&
BPF_SIZE(insn->code) == BPF_DW) {
/* At this point, we already made sure that the second
* part of the ldimm64 insn is accessible.
*/
u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD;
if (map_ptr && !env->allow_ptr_leaks)
imm = 0;
verbose("(%02x) r%d = 0x%llx\n", insn->code,
insn->dst_reg, (unsigned long long)imm);
} else {
verbose("BUG_ld_%02x\n", insn->code);
return;
}
} else if (class == BPF_JMP) {
u8 opcode = BPF_OP(insn->code);
if (opcode == BPF_CALL) {
verbose("(%02x) call %s#%d\n", insn->code,
func_id_name(insn->imm), insn->imm);
} else if (insn->code == (BPF_JMP | BPF_JA)) {
verbose("(%02x) goto pc%+d\n",
insn->code, insn->off);
} else if (insn->code == (BPF_JMP | BPF_EXIT)) {
verbose("(%02x) exit\n", insn->code);
} else if (BPF_SRC(insn->code) == BPF_X) {
verbose("(%02x) if r%d %s r%d goto pc%+d\n",
insn->code, insn->dst_reg,
bpf_jmp_string[BPF_OP(insn->code) >> 4],
insn->src_reg, insn->off);
} else {
verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
insn->code, insn->dst_reg,
bpf_jmp_string[BPF_OP(insn->code) >> 4],
insn->imm, insn->off);
}
} else {
verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
}
}
| 168,121
|
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 nfs_set_open_stateid_locked(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags)
{
if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
memcpy(state->stateid.data, stateid->data, sizeof(state->stateid.data));
memcpy(state->open_stateid.data, stateid->data, sizeof(state->open_stateid.data));
switch (open_flags) {
case FMODE_READ:
set_bit(NFS_O_RDONLY_STATE, &state->flags);
break;
case FMODE_WRITE:
set_bit(NFS_O_WRONLY_STATE, &state->flags);
break;
case FMODE_READ|FMODE_WRITE:
set_bit(NFS_O_RDWR_STATE, &state->flags);
}
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
CWE ID:
|
static void nfs_set_open_stateid_locked(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags)
static void nfs_set_open_stateid_locked(struct nfs4_state *state, nfs4_stateid *stateid, fmode_t fmode)
{
if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
memcpy(state->stateid.data, stateid->data, sizeof(state->stateid.data));
memcpy(state->open_stateid.data, stateid->data, sizeof(state->open_stateid.data));
switch (fmode) {
case FMODE_READ:
set_bit(NFS_O_RDONLY_STATE, &state->flags);
break;
case FMODE_WRITE:
set_bit(NFS_O_WRONLY_STATE, &state->flags);
break;
case FMODE_READ|FMODE_WRITE:
set_bit(NFS_O_RDWR_STATE, &state->flags);
}
}
| 165,706
|
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: do_async_increment (IncrementData *data)
{
gint32 newx = data->x + 1;
dbus_g_method_return (data->context, newx);
g_free (data);
return FALSE;
}
Commit Message:
CWE ID: CWE-264
|
do_async_increment (IncrementData *data)
| 165,083
|
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 link_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, i = 0, nbuf;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
/*
* If we have iterated all input buffers or ran out of
* output room, break.
*/
if (i >= ipipe->nrbufs || opipe->nrbufs >= opipe->buffers)
break;
ibuf = ipipe->bufs + ((ipipe->curbuf + i) & (ipipe->buffers-1));
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
pipe_buf_get(ipipe, ibuf);
obuf = opipe->bufs + nbuf;
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
if (obuf->len > len)
obuf->len = len;
opipe->nrbufs++;
ret += obuf->len;
len -= obuf->len;
i++;
} while (len);
/*
* return EAGAIN if we have the potential of some data in the
* future, otherwise just return 0
*/
if (!ret && ipipe->waiting_writers && (flags & SPLICE_F_NONBLOCK))
ret = -EAGAIN;
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
return ret;
}
Commit Message: fs: prevent page refcount overflow in pipe_buf_get
Change pipe_buf_get() to return a bool indicating whether it succeeded
in raising the refcount of the page (if the thing in the pipe is a page).
This removes another mechanism for overflowing the page refcount. All
callers converted to handle a failure.
Reported-by: Jann Horn <jannh@google.com>
Signed-off-by: Matthew Wilcox <willy@infradead.org>
Cc: stable@kernel.org
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-416
|
static int link_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, i = 0, nbuf;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
/*
* If we have iterated all input buffers or ran out of
* output room, break.
*/
if (i >= ipipe->nrbufs || opipe->nrbufs >= opipe->buffers)
break;
ibuf = ipipe->bufs + ((ipipe->curbuf + i) & (ipipe->buffers-1));
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
if (!pipe_buf_get(ipipe, ibuf)) {
if (ret == 0)
ret = -EFAULT;
break;
}
obuf = opipe->bufs + nbuf;
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
if (obuf->len > len)
obuf->len = len;
opipe->nrbufs++;
ret += obuf->len;
len -= obuf->len;
i++;
} while (len);
/*
* return EAGAIN if we have the potential of some data in the
* future, otherwise just return 0
*/
if (!ret && ipipe->waiting_writers && (flags & SPLICE_F_NONBLOCK))
ret = -EAGAIN;
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
return ret;
}
| 170,230
|
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 NaClIPCAdapter::TakeClientFileDescriptor() {
return io_thread_data_.channel_->TakeClientFileDescriptor();
}
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
TBR=bbudge@chromium.org
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
|
int NaClIPCAdapter::TakeClientFileDescriptor() {
| 170,731
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int prctl_set_vma_anon_name(unsigned long start, unsigned long end,
unsigned long arg)
{
unsigned long tmp;
struct vm_area_struct * vma, *prev;
int unmapped_error = 0;
int error = -EINVAL;
/*
* If the interval [start,end) covers some unmapped address
* ranges, just ignore them, but return -ENOMEM at the end.
* - this matches the handling in madvise.
*/
vma = find_vma_prev(current->mm, start, &prev);
if (vma && start > vma->vm_start)
prev = vma;
for (;;) {
/* Still start < end. */
error = -ENOMEM;
if (!vma)
return error;
/* Here start < (end|vma->vm_end). */
if (start < vma->vm_start) {
unmapped_error = -ENOMEM;
start = vma->vm_start;
if (start >= end)
return error;
}
/* Here vma->vm_start <= start < (end|vma->vm_end) */
tmp = vma->vm_end;
if (end < tmp)
tmp = end;
/* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */
error = prctl_update_vma_anon_name(vma, &prev, start, end,
(const char __user *)arg);
if (error)
return error;
start = tmp;
if (prev && start < prev->vm_end)
start = prev->vm_end;
error = unmapped_error;
if (start >= end)
return error;
if (prev)
vma = prev->vm_next;
else /* madvise_remove dropped mmap_sem */
vma = find_vma(current->mm, start);
}
}
Commit Message: mm: fix prctl_set_vma_anon_name
prctl_set_vma_anon_name could attempt to set the name across
two vmas at the same time due to a typo, which might corrupt
the vma list. Fix it to use tmp instead of end to limit
the name setting to a single vma at a time.
Change-Id: Ie32d8ddb0fd547efbeedd6528acdab5ca5b308b4
Reported-by: Jed Davis <jld@mozilla.com>
Signed-off-by: Colin Cross <ccross@android.com>
CWE ID: CWE-264
|
static int prctl_set_vma_anon_name(unsigned long start, unsigned long end,
unsigned long arg)
{
unsigned long tmp;
struct vm_area_struct * vma, *prev;
int unmapped_error = 0;
int error = -EINVAL;
/*
* If the interval [start,end) covers some unmapped address
* ranges, just ignore them, but return -ENOMEM at the end.
* - this matches the handling in madvise.
*/
vma = find_vma_prev(current->mm, start, &prev);
if (vma && start > vma->vm_start)
prev = vma;
for (;;) {
/* Still start < end. */
error = -ENOMEM;
if (!vma)
return error;
/* Here start < (end|vma->vm_end). */
if (start < vma->vm_start) {
unmapped_error = -ENOMEM;
start = vma->vm_start;
if (start >= end)
return error;
}
/* Here vma->vm_start <= start < (end|vma->vm_end) */
tmp = vma->vm_end;
if (end < tmp)
tmp = end;
/* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */
error = prctl_update_vma_anon_name(vma, &prev, start, tmp,
(const char __user *)arg);
if (error)
return error;
start = tmp;
if (prev && start < prev->vm_end)
start = prev->vm_end;
error = unmapped_error;
if (start >= end)
return error;
if (prev)
vma = prev->vm_next;
else /* madvise_remove dropped mmap_sem */
vma = find_vma(current->mm, start);
}
}
| 173,972
|
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: ikev2_vid_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
const u_char *vid;
int i, len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4));
vid = (const u_char *)(ext+1);
len = ntohs(e.len) - 4;
ND_TCHECK2(*vid, len);
for(i=0; i<len; i++) {
if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i]));
else ND_PRINT((ndo, "."));
}
if (2 < ndo->ndo_vflag && 4 < len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
ikev2_vid_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
const u_char *vid;
int i, len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4));
vid = (const u_char *)(ext+1);
len = ntohs(e.len) - 4;
ND_TCHECK2(*vid, len);
for(i=0; i<len; i++) {
if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i]));
else ND_PRINT((ndo, "."));
}
if (2 < ndo->ndo_vflag && 4 < len) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
| 167,803
|
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 timer_start(Unit *u) {
Timer *t = TIMER(u);
TimerValue *v;
assert(t);
assert(t->state == TIMER_DEAD || t->state == TIMER_FAILED);
if (UNIT_TRIGGER(u)->load_state != UNIT_LOADED)
return -ENOENT;
t->last_trigger = DUAL_TIMESTAMP_NULL;
/* Reenable all timers that depend on unit activation time */
LIST_FOREACH(value, v, t->values)
if (v->base == TIMER_ACTIVE)
v->disabled = false;
if (t->stamp_path) {
struct stat st;
if (stat(t->stamp_path, &st) >= 0)
t->last_trigger.realtime = timespec_load(&st.st_atim);
else if (errno == ENOENT)
/* The timer has never run before,
* make sure a stamp file exists.
*/
touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
}
t->result = TIMER_SUCCESS;
timer_enter_waiting(t, true);
return 1;
}
Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere
CWE ID: CWE-264
|
static int timer_start(Unit *u) {
Timer *t = TIMER(u);
TimerValue *v;
assert(t);
assert(t->state == TIMER_DEAD || t->state == TIMER_FAILED);
if (UNIT_TRIGGER(u)->load_state != UNIT_LOADED)
return -ENOENT;
t->last_trigger = DUAL_TIMESTAMP_NULL;
/* Reenable all timers that depend on unit activation time */
LIST_FOREACH(value, v, t->values)
if (v->base == TIMER_ACTIVE)
v->disabled = false;
if (t->stamp_path) {
struct stat st;
if (stat(t->stamp_path, &st) >= 0)
t->last_trigger.realtime = timespec_load(&st.st_atim);
else if (errno == ENOENT)
/* The timer has never run before,
* make sure a stamp file exists.
*/
touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
}
t->result = TIMER_SUCCESS;
timer_enter_waiting(t, true);
return 1;
}
| 170,107
|
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: QualifyIpPacket(IPHeader *pIpHeader, ULONG len)
{
tTcpIpPacketParsingResult res;
UCHAR ver_len = pIpHeader->v4.ip_verlen;
UCHAR ip_version = (ver_len & 0xF0) >> 4;
USHORT ipHeaderSize = 0;
USHORT fullLength = 0;
res.value = 0;
if (ip_version == 4)
{
ipHeaderSize = (ver_len & 0xF) << 2;
fullLength = swap_short(pIpHeader->v4.ip_length);
DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\n",
ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength));
res.ipStatus = (ipHeaderSize >= sizeof(IPv4Header)) ? ppresIPV4 : ppresNotIP;
if (len < ipHeaderSize) res.ipCheckSum = ppresIPTooShort;
if (fullLength) {}
else
{
DPrintf(2, ("ip v.%d, iplen %d\n", ip_version, fullLength));
}
}
else if (ip_version == 6)
{
UCHAR nextHeader = pIpHeader->v6.ip6_next_header;
BOOLEAN bParsingDone = FALSE;
ipHeaderSize = sizeof(pIpHeader->v6);
res.ipStatus = ppresIPV6;
res.ipCheckSum = ppresCSOK;
fullLength = swap_short(pIpHeader->v6.ip6_payload_len);
fullLength += ipHeaderSize;
while (nextHeader != 59)
{
IPv6ExtHeader *pExt;
switch (nextHeader)
{
case PROTOCOL_TCP:
bParsingDone = TRUE;
res.xxpStatus = ppresXxpKnown;
res.TcpUdp = ppresIsTCP;
res.xxpFull = len >= fullLength ? 1 : 0;
res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);
break;
case PROTOCOL_UDP:
bParsingDone = TRUE;
res.xxpStatus = ppresXxpKnown;
res.TcpUdp = ppresIsUDP;
res.xxpFull = len >= fullLength ? 1 : 0;
res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);
break;
case 0:
case 60:
case 43:
case 44:
case 51:
case 50:
case 135:
if (len >= ((ULONG)ipHeaderSize + 8))
{
pExt = (IPv6ExtHeader *)((PUCHAR)pIpHeader + ipHeaderSize);
nextHeader = pExt->ip6ext_next_header;
ipHeaderSize += 8;
ipHeaderSize += pExt->ip6ext_hdr_len * 8;
}
else
{
DPrintf(0, ("[%s] ERROR: Break in the middle of ext. headers(len %d, hdr > %d)\n", __FUNCTION__, len, ipHeaderSize));
res.ipStatus = ppresNotIP;
bParsingDone = TRUE;
}
break;
default:
res.xxpStatus = ppresXxpOther;
bParsingDone = TRUE;
break;
}
if (bParsingDone)
break;
}
if (ipHeaderSize <= MAX_SUPPORTED_IPV6_HEADERS)
{
DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\n",
ip_version, ipHeaderSize, nextHeader, fullLength));
res.ipHeaderSize = ipHeaderSize;
}
else
{
DPrintf(0, ("[%s] ERROR: IP chain is too large (%d)\n", __FUNCTION__, ipHeaderSize));
res.ipStatus = ppresNotIP;
}
}
if (res.ipStatus == ppresIPV4)
{
res.ipHeaderSize = ipHeaderSize;
res.xxpFull = len >= fullLength ? 1 : 0;
res.IsFragment = (pIpHeader->v4.ip_offset & ~0xC0) != 0;
switch (pIpHeader->v4.ip_protocol)
{
case PROTOCOL_TCP:
{
res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);
}
break;
case PROTOCOL_UDP:
{
res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);
}
break;
default:
res.xxpStatus = ppresXxpOther;
break;
}
}
return res;
}
Commit Message: NetKVM: BZ#1169718: More rigoruous testing of incoming packet
Signed-off-by: Joseph Hindin <yhindin@rehat.com>
CWE ID: CWE-20
|
QualifyIpPacket(IPHeader *pIpHeader, ULONG len)
{
tTcpIpPacketParsingResult res;
res.value = 0;
if (len < 4)
{
res.ipStatus = ppresNotIP;
return res;
}
UCHAR ver_len = pIpHeader->v4.ip_verlen;
UCHAR ip_version = (ver_len & 0xF0) >> 4;
USHORT ipHeaderSize = 0;
USHORT fullLength = 0;
res.value = 0;
if (ip_version == 4)
{
if (len < sizeof(IPv4Header))
{
res.ipStatus = ppresNotIP;
return res;
}
ipHeaderSize = (ver_len & 0xF) << 2;
fullLength = swap_short(pIpHeader->v4.ip_length);
DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d, L2 payload length %d\n",
ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength, len));
res.ipStatus = (ipHeaderSize >= sizeof(IPv4Header)) ? ppresIPV4 : ppresNotIP;
if (res.ipStatus == ppresNotIP)
{
return res;
}
if (ipHeaderSize >= fullLength || len < fullLength)
{
DPrintf(2, ("[%s] - truncated packet - ip_version %d, ipHeaderSize %d, protocol %d, iplen %d, L2 payload length %d\n",
ip_version, ipHeaderSize, pIpHeader->v4.ip_protocol, fullLength, len));
res.ipCheckSum = ppresIPTooShort;
return res;
}
}
else if (ip_version == 6)
{
UCHAR nextHeader = pIpHeader->v6.ip6_next_header;
BOOLEAN bParsingDone = FALSE;
ipHeaderSize = sizeof(pIpHeader->v6);
res.ipStatus = ppresIPV6;
res.ipCheckSum = ppresCSOK;
fullLength = swap_short(pIpHeader->v6.ip6_payload_len);
fullLength += ipHeaderSize;
while (nextHeader != 59)
{
IPv6ExtHeader *pExt;
switch (nextHeader)
{
case PROTOCOL_TCP:
bParsingDone = TRUE;
res.xxpStatus = ppresXxpKnown;
res.TcpUdp = ppresIsTCP;
res.xxpFull = len >= fullLength ? 1 : 0;
res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);
break;
case PROTOCOL_UDP:
bParsingDone = TRUE;
res.xxpStatus = ppresXxpKnown;
res.TcpUdp = ppresIsUDP;
res.xxpFull = len >= fullLength ? 1 : 0;
res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);
break;
case 0:
case 60:
case 43:
case 44:
case 51:
case 50:
case 135:
if (len >= ((ULONG)ipHeaderSize + 8))
{
pExt = (IPv6ExtHeader *)((PUCHAR)pIpHeader + ipHeaderSize);
nextHeader = pExt->ip6ext_next_header;
ipHeaderSize += 8;
ipHeaderSize += pExt->ip6ext_hdr_len * 8;
}
else
{
DPrintf(0, ("[%s] ERROR: Break in the middle of ext. headers(len %d, hdr > %d)\n", __FUNCTION__, len, ipHeaderSize));
res.ipStatus = ppresNotIP;
bParsingDone = TRUE;
}
break;
default:
res.xxpStatus = ppresXxpOther;
bParsingDone = TRUE;
break;
}
if (bParsingDone)
break;
}
if (ipHeaderSize <= MAX_SUPPORTED_IPV6_HEADERS)
{
DPrintf(3, ("ip_version %d, ipHeaderSize %d, protocol %d, iplen %d\n",
ip_version, ipHeaderSize, nextHeader, fullLength));
res.ipHeaderSize = ipHeaderSize;
}
else
{
DPrintf(0, ("[%s] ERROR: IP chain is too large (%d)\n", __FUNCTION__, ipHeaderSize));
res.ipStatus = ppresNotIP;
}
}
if (res.ipStatus == ppresIPV4)
{
res.ipHeaderSize = ipHeaderSize;
res.IsFragment = (pIpHeader->v4.ip_offset & ~0xC0) != 0;
switch (pIpHeader->v4.ip_protocol)
{
case PROTOCOL_TCP:
{
res = ProcessTCPHeader(res, pIpHeader, len, ipHeaderSize);
}
break;
case PROTOCOL_UDP:
{
res = ProcessUDPHeader(res, pIpHeader, len, ipHeaderSize);
}
break;
default:
res.xxpStatus = ppresXxpOther;
break;
}
}
return res;
}
| 168,891
|
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: exsltStrXpathCtxtRegister (xmlXPathContextPtr ctxt, const xmlChar *prefix)
{
if (ctxt
&& prefix
&& !xmlXPathRegisterNs(ctxt,
prefix,
(const xmlChar *) EXSLT_STRINGS_NAMESPACE)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "encode-uri",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrEncodeUriFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "decode-uri",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrDecodeUriFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "padding",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrPaddingFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "align",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrAlignFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "concat",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrConcatFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "replace",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrReplaceFunction)) {
return 0;
}
return -1;
}
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
|
exsltStrXpathCtxtRegister (xmlXPathContextPtr ctxt, const xmlChar *prefix)
{
if (ctxt
&& prefix
&& !xmlXPathRegisterNs(ctxt,
prefix,
(const xmlChar *) EXSLT_STRINGS_NAMESPACE)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "encode-uri",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrEncodeUriFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "decode-uri",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrDecodeUriFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "padding",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrPaddingFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "align",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrAlignFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "concat",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrConcatFunction)) {
return 0;
}
return -1;
}
| 173,297
|
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_palette_to_rgb_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_palette_to_rgb(pp);
this->next->set(this->next, that, pp, pi);
}
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_palette_to_rgb_set(PNG_CONST image_transform *this,
image_transform_png_set_palette_to_rgb_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_palette_to_rgb(pp);
this->next->set(this->next, that, pp, pi);
}
| 173,640
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ServiceWorkerDevToolsAgentHost::WorkerReadyForInspection(
blink::mojom::DevToolsAgentAssociatedPtrInfo devtools_agent_ptr_info) {
DCHECK_EQ(WORKER_NOT_READY, state_);
state_ = WORKER_READY;
agent_ptr_.Bind(std::move(devtools_agent_ptr_info));
if (!sessions().empty()) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::BindOnce(&SetDevToolsAttachedOnIO,
context_weak_, version_id_, true));
}
RenderProcessHost* host = RenderProcessHost::FromID(worker_process_id_);
for (DevToolsSession* session : sessions()) {
session->SetRenderer(host, nullptr);
session->AttachToAgent(agent_ptr_);
}
}
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 <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
void ServiceWorkerDevToolsAgentHost::WorkerReadyForInspection(
blink::mojom::DevToolsAgentAssociatedPtrInfo devtools_agent_ptr_info) {
DCHECK_EQ(WORKER_NOT_READY, state_);
state_ = WORKER_READY;
agent_ptr_.Bind(std::move(devtools_agent_ptr_info));
if (!sessions().empty()) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::BindOnce(&SetDevToolsAttachedOnIO,
context_weak_, version_id_, true));
}
for (DevToolsSession* session : sessions()) {
session->SetRenderer(worker_process_id_, nullptr);
session->AttachToAgent(agent_ptr_);
}
}
| 172,785
|
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 cJSON *cJSON_New_Item( void )
{
cJSON* node = (cJSON*) cJSON_malloc( sizeof(cJSON) );
if ( node )
memset( node, 0, sizeof(cJSON) );
return node;
}
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 <bmah@es.net>
CWE ID: CWE-119
|
static cJSON *cJSON_New_Item( void )
static cJSON *cJSON_New_Item(void)
{
cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON));
if (node) memset(node,0,sizeof(cJSON));
return node;
}
| 167,291
|
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 FrameLoader::startLoad(FrameLoadRequest& frameLoadRequest, FrameLoadType type, NavigationPolicy navigationPolicy)
{
ASSERT(client()->hasWebView());
if (m_frame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
return;
NavigationType navigationType = determineNavigationType(type, frameLoadRequest.resourceRequest().httpBody() || frameLoadRequest.form(), frameLoadRequest.triggeringEvent());
frameLoadRequest.resourceRequest().setRequestContext(determineRequestContextFromNavigationType(navigationType));
frameLoadRequest.resourceRequest().setFrameType(m_frame->isMainFrame() ? WebURLRequest::FrameTypeTopLevel : WebURLRequest::FrameTypeNested);
ResourceRequest& request = frameLoadRequest.resourceRequest();
if (!shouldContinueForNavigationPolicy(request, frameLoadRequest.substituteData(), nullptr, frameLoadRequest.shouldCheckMainWorldContentSecurityPolicy(), navigationType, navigationPolicy, type == FrameLoadTypeReplaceCurrentItem, frameLoadRequest.clientRedirect() == ClientRedirectPolicy::ClientRedirect))
return;
if (!shouldClose(navigationType == NavigationTypeReload))
return;
m_frame->document()->cancelParsing();
detachDocumentLoader(m_provisionalDocumentLoader);
if (!m_frame->host())
return;
m_provisionalDocumentLoader = client()->createDocumentLoader(m_frame, request, frameLoadRequest.substituteData().isValid() ? frameLoadRequest.substituteData() : defaultSubstituteDataForURL(request.url()));
m_provisionalDocumentLoader->setNavigationType(navigationType);
m_provisionalDocumentLoader->setReplacesCurrentHistoryItem(type == FrameLoadTypeReplaceCurrentItem);
m_provisionalDocumentLoader->setIsClientRedirect(frameLoadRequest.clientRedirect() == ClientRedirectPolicy::ClientRedirect);
InspectorInstrumentation::didStartProvisionalLoad(m_frame);
m_frame->navigationScheduler().cancel();
m_checkTimer.stop();
m_loadType = type;
if (frameLoadRequest.form())
client()->dispatchWillSubmitForm(frameLoadRequest.form());
m_progressTracker->progressStarted();
if (m_provisionalDocumentLoader->isClientRedirect())
m_provisionalDocumentLoader->appendRedirect(m_frame->document()->url());
m_provisionalDocumentLoader->appendRedirect(m_provisionalDocumentLoader->request().url());
double triggeringEventTime = frameLoadRequest.triggeringEvent() ? frameLoadRequest.triggeringEvent()->platformTimeStamp() : 0;
client()->dispatchDidStartProvisionalLoad(triggeringEventTime);
ASSERT(m_provisionalDocumentLoader);
m_provisionalDocumentLoader->startLoadingMainResource();
takeObjectSnapshot();
}
Commit Message: Disable frame navigations during DocumentLoader detach in FrameLoader::startLoad
BUG=613266
Review-Url: https://codereview.chromium.org/2006033002
Cr-Commit-Position: refs/heads/master@{#396241}
CWE ID: CWE-284
|
void FrameLoader::startLoad(FrameLoadRequest& frameLoadRequest, FrameLoadType type, NavigationPolicy navigationPolicy)
{
ASSERT(client()->hasWebView());
if (m_frame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
return;
NavigationType navigationType = determineNavigationType(type, frameLoadRequest.resourceRequest().httpBody() || frameLoadRequest.form(), frameLoadRequest.triggeringEvent());
frameLoadRequest.resourceRequest().setRequestContext(determineRequestContextFromNavigationType(navigationType));
frameLoadRequest.resourceRequest().setFrameType(m_frame->isMainFrame() ? WebURLRequest::FrameTypeTopLevel : WebURLRequest::FrameTypeNested);
ResourceRequest& request = frameLoadRequest.resourceRequest();
if (!shouldContinueForNavigationPolicy(request, frameLoadRequest.substituteData(), nullptr, frameLoadRequest.shouldCheckMainWorldContentSecurityPolicy(), navigationType, navigationPolicy, type == FrameLoadTypeReplaceCurrentItem, frameLoadRequest.clientRedirect() == ClientRedirectPolicy::ClientRedirect))
return;
if (!shouldClose(navigationType == NavigationTypeReload))
return;
m_frame->document()->cancelParsing();
if (m_provisionalDocumentLoader) {
FrameNavigationDisabler navigationDisabler(*m_frame);
detachDocumentLoader(m_provisionalDocumentLoader);
}
if (!m_frame->host())
return;
m_provisionalDocumentLoader = client()->createDocumentLoader(m_frame, request, frameLoadRequest.substituteData().isValid() ? frameLoadRequest.substituteData() : defaultSubstituteDataForURL(request.url()));
m_provisionalDocumentLoader->setNavigationType(navigationType);
m_provisionalDocumentLoader->setReplacesCurrentHistoryItem(type == FrameLoadTypeReplaceCurrentItem);
m_provisionalDocumentLoader->setIsClientRedirect(frameLoadRequest.clientRedirect() == ClientRedirectPolicy::ClientRedirect);
InspectorInstrumentation::didStartProvisionalLoad(m_frame);
m_frame->navigationScheduler().cancel();
m_checkTimer.stop();
m_loadType = type;
if (frameLoadRequest.form())
client()->dispatchWillSubmitForm(frameLoadRequest.form());
m_progressTracker->progressStarted();
if (m_provisionalDocumentLoader->isClientRedirect())
m_provisionalDocumentLoader->appendRedirect(m_frame->document()->url());
m_provisionalDocumentLoader->appendRedirect(m_provisionalDocumentLoader->request().url());
double triggeringEventTime = frameLoadRequest.triggeringEvent() ? frameLoadRequest.triggeringEvent()->platformTimeStamp() : 0;
client()->dispatchDidStartProvisionalLoad(triggeringEventTime);
ASSERT(m_provisionalDocumentLoader);
m_provisionalDocumentLoader->startLoadingMainResource();
takeObjectSnapshot();
}
| 172,258
|
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 PrintPreviewDataService::RemoveEntry(
const std::string& preview_ui_addr_str) {
PreviewDataStoreMap::iterator it = data_store_map_.find(preview_ui_addr_str);
if (it != data_store_map_.end())
data_store_map_.erase(it);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
void PrintPreviewDataService::RemoveEntry(
void PrintPreviewDataService::RemoveEntry(int32 preview_ui_id) {
data_store_map_.erase(preview_ui_id);
}
| 170,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: SRP_user_pwd *SRP_VBASE_get_by_user(SRP_VBASE *vb, char *username)
{
int i;
SRP_user_pwd *user;
unsigned char digv[SHA_DIGEST_LENGTH];
unsigned char digs[SHA_DIGEST_LENGTH];
EVP_MD_CTX ctxt;
if (vb == NULL)
return NULL;
for (i = 0; i < sk_SRP_user_pwd_num(vb->users_pwd); i++) {
user = sk_SRP_user_pwd_value(vb->users_pwd, i);
if (strcmp(user->id, username) == 0)
return user;
}
if ((vb->seed_key == NULL) ||
(vb->default_g == NULL) || (vb->default_N == NULL))
return NULL;
if (!(len = t_fromb64(tmp, N)))
goto err;
N_bn = BN_bin2bn(tmp, len, NULL);
if (!(len = t_fromb64(tmp, g)))
goto err;
g_bn = BN_bin2bn(tmp, len, NULL);
defgNid = "*";
} else {
SRP_gN *gN = SRP_get_gN_by_id(g, NULL);
if (gN == NULL)
goto err;
N_bn = gN->N;
g_bn = gN->g;
defgNid = gN->id;
}
Commit Message:
CWE ID: CWE-399
|
SRP_user_pwd *SRP_VBASE_get_by_user(SRP_VBASE *vb, char *username)
static SRP_user_pwd *find_user(SRP_VBASE *vb, char *username)
{
int i;
SRP_user_pwd *user;
if (vb == NULL)
return NULL;
for (i = 0; i < sk_SRP_user_pwd_num(vb->users_pwd); i++) {
user = sk_SRP_user_pwd_value(vb->users_pwd, i);
if (strcmp(user->id, username) == 0)
return user;
}
return NULL;
}
/*
* This method ignores the configured seed and fails for an unknown user.
* Ownership of the returned pointer is not released to the caller.
* In other words, caller must not free the result.
*/
SRP_user_pwd *SRP_VBASE_get_by_user(SRP_VBASE *vb, char *username)
{
return find_user(vb, username);
}
/*
* Ownership of the returned pointer is released to the caller.
* In other words, caller must free the result once done.
*/
SRP_user_pwd *SRP_VBASE_get1_by_user(SRP_VBASE *vb, char *username)
{
SRP_user_pwd *user;
unsigned char digv[SHA_DIGEST_LENGTH];
unsigned char digs[SHA_DIGEST_LENGTH];
EVP_MD_CTX ctxt;
if (vb == NULL)
return NULL;
if ((user = find_user(vb, username)) != NULL)
return srp_user_pwd_dup(user);
if ((vb->seed_key == NULL) ||
(vb->default_g == NULL) || (vb->default_N == NULL))
return NULL;
if (!(len = t_fromb64(tmp, N)))
goto err;
N_bn = BN_bin2bn(tmp, len, NULL);
if (!(len = t_fromb64(tmp, g)))
goto err;
g_bn = BN_bin2bn(tmp, len, NULL);
defgNid = "*";
} else {
SRP_gN *gN = SRP_get_gN_by_id(g, NULL);
if (gN == NULL)
goto err;
N_bn = gN->N;
g_bn = gN->g;
defgNid = gN->id;
}
| 165,248
|
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 base::Callback<void(const gfx::Image&)> Wrap(
const base::Callback<void(const SkBitmap&)>& image_decoded_callback) {
auto* handler = new ImageDecodedHandlerWithTimeout(image_decoded_callback);
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&ImageDecodedHandlerWithTimeout::OnImageDecoded,
handler->weak_ptr_factory_.GetWeakPtr(), gfx::Image()),
base::TimeDelta::FromSeconds(kDecodeLogoTimeoutSeconds));
return base::Bind(&ImageDecodedHandlerWithTimeout::OnImageDecoded,
handler->weak_ptr_factory_.GetWeakPtr());
}
Commit Message: Local NTP: add smoke tests for doodles
Split LogoService into LogoService interface and LogoServiceImpl to make
it easier to provide fake data to the test.
Bug: 768419
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I84639189d2db1b24a2e139936c99369352bab587
Reviewed-on: https://chromium-review.googlesource.com/690198
Reviewed-by: Sylvain Defresne <sdefresne@chromium.org>
Reviewed-by: Marc Treib <treib@chromium.org>
Commit-Queue: Chris Pickel <sfiera@chromium.org>
Cr-Commit-Position: refs/heads/master@{#505374}
CWE ID: CWE-119
|
static base::Callback<void(const gfx::Image&)> Wrap(
| 171,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: my_object_increment (MyObject *obj, gint32 x, gint32 *ret, GError **error)
{
*ret = x +1;
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_increment (MyObject *obj, gint32 x, gint32 *ret, GError **error)
| 165,105
|
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: IW_IMPL(unsigned int) iw_get_ui16le(const iw_byte *b)
{
return b[0] | (b[1]<<8);
}
Commit Message: Trying to fix some invalid left shift operations
Fixes issue #16
CWE ID: CWE-682
|
IW_IMPL(unsigned int) iw_get_ui16le(const iw_byte *b)
{
return (unsigned int)b[0] | ((unsigned int)b[1]<<8);
}
| 168,198
|
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 GetNetworkList(NetworkInterfaceList* networks, int policy) {
if (networks == NULL)
return false;
base::ThreadRestrictions::AssertIOAllowed();
ifaddrs* interfaces;
if (getifaddrs(&interfaces) < 0) {
PLOG(ERROR) << "getifaddrs";
return false;
}
std::unique_ptr<internal::IPAttributesGetter> ip_attributes_getter;
#if defined(OS_MACOSX) && !defined(OS_IOS)
ip_attributes_getter = base::MakeUnique<internal::IPAttributesGetterMac>();
#endif
bool result = internal::IfaddrsToNetworkInterfaceList(
policy, interfaces, ip_attributes_getter.get(), networks);
freeifaddrs(interfaces);
return result;
}
Commit Message: Replace base::MakeUnique with std::make_unique in net/.
base/memory/ptr_util.h includes will be cleaned up later.
Bug: 755727
Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434
Reviewed-on: https://chromium-review.googlesource.com/627300
Commit-Queue: Jeremy Roman <jbroman@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Reviewed-by: Bence Béky <bnc@chromium.org>
Cr-Commit-Position: refs/heads/master@{#498123}
CWE ID: CWE-311
|
bool GetNetworkList(NetworkInterfaceList* networks, int policy) {
if (networks == NULL)
return false;
base::ThreadRestrictions::AssertIOAllowed();
ifaddrs* interfaces;
if (getifaddrs(&interfaces) < 0) {
PLOG(ERROR) << "getifaddrs";
return false;
}
std::unique_ptr<internal::IPAttributesGetter> ip_attributes_getter;
#if defined(OS_MACOSX) && !defined(OS_IOS)
ip_attributes_getter = std::make_unique<internal::IPAttributesGetterMac>();
#endif
bool result = internal::IfaddrsToNetworkInterfaceList(
policy, interfaces, ip_attributes_getter.get(), networks);
freeifaddrs(interfaces);
return result;
}
| 173,265
|
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::UpdatePrintSettings(
const DictionaryValue& job_settings, bool is_preview) {
PrintMsg_PrintPages_Params settings;
Send(new PrintHostMsg_UpdatePrintSettings(routing_id(),
print_pages_params_->params.document_cookie, job_settings, &settings));
if (settings.params.dpi < kMinDpi || !settings.params.document_cookie) {
print_preview_context_.set_error(PREVIEW_ERROR_UPDATING_PRINT_SETTINGS);
return false;
}
if (is_preview) {
if (!job_settings.GetString(printing::kPreviewUIAddr,
&(settings.params.preview_ui_addr)) ||
!job_settings.GetInteger(printing::kPreviewRequestID,
&(settings.params.preview_request_id)) ||
!job_settings.GetBoolean(printing::kIsFirstRequest,
&(settings.params.is_first_request))) {
NOTREACHED();
print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
return false;
}
if (settings.params.is_first_request &&
!print_preview_context_.IsModifiable()) {
settings.params.display_header_footer = false;
}
PageSizeMargins default_page_layout;
GetPageSizeAndMarginsInPoints(NULL, -1, settings.params,
&default_page_layout);
if (!old_print_pages_params_.get() ||
!PageLayoutIsEqual(*old_print_pages_params_, settings)) {
Send(new PrintHostMsg_DidGetDefaultPageLayout(routing_id(),
default_page_layout));
}
SetCustomMarginsIfSelected(job_settings, &settings);
if (settings.params.display_header_footer) {
header_footer_info_.reset(new DictionaryValue());
header_footer_info_->SetString(printing::kSettingHeaderFooterDate,
settings.params.date);
header_footer_info_->SetString(printing::kSettingHeaderFooterURL,
settings.params.url);
header_footer_info_->SetString(printing::kSettingHeaderFooterTitle,
settings.params.title);
}
}
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
settings.params.document_cookie));
return true;
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool PrintWebViewHelper::UpdatePrintSettings(
const DictionaryValue& job_settings, bool is_preview) {
if (job_settings.empty()) {
if (is_preview)
print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
return false;
}
// Send the cookie so that UpdatePrintSettings can reuse PrinterQuery when
// possible.
int cookie = print_pages_params_.get() ?
print_pages_params_->params.document_cookie : 0;
PrintMsg_PrintPages_Params settings;
Send(new PrintHostMsg_UpdatePrintSettings(routing_id(),
cookie, job_settings, &settings));
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
if (PrintMsg_Print_Params_IsEmpty(settings.params)) {
if (is_preview) {
print_preview_context_.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS);
} else {
WebKit::WebFrame* frame = print_preview_context_.frame();
if (!frame) {
GetPrintFrame(&frame);
}
if (frame) {
render_view()->runModalAlertDialog(
frame,
l10n_util::GetStringUTF16(
IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS));
}
}
return false;
}
if (settings.params.dpi < kMinDpi || !settings.params.document_cookie) {
print_preview_context_.set_error(PREVIEW_ERROR_UPDATING_PRINT_SETTINGS);
return false;
}
if (is_preview) {
if (!job_settings.GetString(printing::kPreviewUIAddr,
&(settings.params.preview_ui_addr)) ||
!job_settings.GetInteger(printing::kPreviewRequestID,
&(settings.params.preview_request_id)) ||
!job_settings.GetBoolean(printing::kIsFirstRequest,
&(settings.params.is_first_request))) {
NOTREACHED();
print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
return false;
}
if (settings.params.is_first_request &&
!print_preview_context_.IsModifiable()) {
settings.params.display_header_footer = false;
}
PageSizeMargins default_page_layout;
GetPageSizeAndMarginsInPoints(NULL, -1, settings.params,
&default_page_layout);
if (!old_print_pages_params_.get() ||
!PageLayoutIsEqual(*old_print_pages_params_, settings)) {
Send(new PrintHostMsg_DidGetDefaultPageLayout(routing_id(),
default_page_layout));
}
SetCustomMarginsIfSelected(job_settings, &settings);
if (settings.params.display_header_footer) {
header_footer_info_.reset(new DictionaryValue());
header_footer_info_->SetString(printing::kSettingHeaderFooterDate,
settings.params.date);
header_footer_info_->SetString(printing::kSettingHeaderFooterURL,
settings.params.url);
header_footer_info_->SetString(printing::kSettingHeaderFooterTitle,
settings.params.title);
}
}
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
settings.params.document_cookie));
return true;
}
| 170,264
|
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: formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form)
{
Buffer save;
char *p;
int spos, epos, rows, c_rows, pos, col = 0;
Line *l;
copyBuffer(&save, buf);
gotoLine(buf, a->start.line);
switch (form->type) {
case FORM_TEXTAREA:
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
#ifdef MENU_SELECT
case FORM_SELECT:
#endif /* MENU_SELECT */
spos = a->start.pos;
epos = a->end.pos;
break;
default:
spos = a->start.pos + 1;
epos = a->end.pos - 1;
}
switch (form->type) {
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
if (buf->currentLine == NULL ||
spos >= buf->currentLine->len || spos < 0)
break;
if (form->checked)
buf->currentLine->lineBuf[spos] = '*';
else
buf->currentLine->lineBuf[spos] = ' ';
break;
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_TEXTAREA:
#ifdef MENU_SELECT
case FORM_SELECT:
if (form->type == FORM_SELECT) {
p = form->label->ptr;
updateSelectOption(form, form->select_option);
}
else
#endif /* MENU_SELECT */
{
if (!form->value)
break;
p = form->value->ptr;
}
l = buf->currentLine;
if (!l)
break;
if (form->type == FORM_TEXTAREA) {
int n = a->y - buf->currentLine->linenumber;
if (n > 0)
for (; l && n; l = l->prev, n--) ;
else if (n < 0)
for (; l && n; l = l->prev, n++) ;
if (!l)
break;
}
rows = form->rows ? form->rows : 1;
col = COLPOS(l, a->start.pos);
for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) {
if (rows > 1) {
pos = columnPos(l, col);
a = retrieveAnchor(buf->formitem, l->linenumber, pos);
if (a == NULL)
break;
spos = a->start.pos;
epos = a->end.pos;
}
if (a->start.line != a->end.line || spos > epos || epos >= l->len ||
spos < 0 || epos < 0 || COLPOS(l, epos) < col)
break;
pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col,
rows > 1,
form->type == FORM_INPUT_PASSWORD);
if (pos != epos) {
shiftAnchorPosition(buf->href, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->name, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->img, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->formitem, buf->hmarklist,
a->start.line, spos, pos - epos);
}
}
break;
}
copyBuffer(buf, &save);
arrangeLine(buf);
}
Commit Message: Prevent invalid columnPos() call in formUpdateBuffer()
Bug-Debian: https://github.com/tats/w3m/issues/89
CWE ID: CWE-476
|
formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form)
{
Buffer save;
char *p;
int spos, epos, rows, c_rows, pos, col = 0;
Line *l;
copyBuffer(&save, buf);
gotoLine(buf, a->start.line);
switch (form->type) {
case FORM_TEXTAREA:
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
#ifdef MENU_SELECT
case FORM_SELECT:
#endif /* MENU_SELECT */
spos = a->start.pos;
epos = a->end.pos;
break;
default:
spos = a->start.pos + 1;
epos = a->end.pos - 1;
}
switch (form->type) {
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
if (buf->currentLine == NULL ||
spos >= buf->currentLine->len || spos < 0)
break;
if (form->checked)
buf->currentLine->lineBuf[spos] = '*';
else
buf->currentLine->lineBuf[spos] = ' ';
break;
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_TEXTAREA:
#ifdef MENU_SELECT
case FORM_SELECT:
if (form->type == FORM_SELECT) {
p = form->label->ptr;
updateSelectOption(form, form->select_option);
}
else
#endif /* MENU_SELECT */
{
if (!form->value)
break;
p = form->value->ptr;
}
l = buf->currentLine;
if (!l)
break;
if (form->type == FORM_TEXTAREA) {
int n = a->y - buf->currentLine->linenumber;
if (n > 0)
for (; l && n; l = l->prev, n--) ;
else if (n < 0)
for (; l && n; l = l->prev, n++) ;
if (!l)
break;
}
rows = form->rows ? form->rows : 1;
col = COLPOS(l, a->start.pos);
for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) {
if (l == NULL)
break;
if (rows > 1) {
pos = columnPos(l, col);
a = retrieveAnchor(buf->formitem, l->linenumber, pos);
if (a == NULL)
break;
spos = a->start.pos;
epos = a->end.pos;
}
if (a->start.line != a->end.line || spos > epos || epos >= l->len ||
spos < 0 || epos < 0 || COLPOS(l, epos) < col)
break;
pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col,
rows > 1,
form->type == FORM_INPUT_PASSWORD);
if (pos != epos) {
shiftAnchorPosition(buf->href, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->name, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->img, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->formitem, buf->hmarklist,
a->start.line, spos, pos - epos);
}
}
break;
}
copyBuffer(buf, &save);
arrangeLine(buf);
}
| 169,347
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int msPostGISLayerSetTimeFilter(layerObj *lp, const char *timestring, const char *timefield)
{
char **atimes, **aranges = NULL;
int numtimes=0,i=0,numranges=0;
size_t buffer_size = 512;
char buffer[512], bufferTmp[512];
buffer[0] = '\0';
bufferTmp[0] = '\0';
if (!lp || !timestring || !timefield)
return MS_FALSE;
/* discrete time */
if (strstr(timestring, ",") == NULL &&
strstr(timestring, "/") == NULL) { /* discrete time */
createPostgresTimeCompareSimple(timefield, timestring, buffer, buffer_size);
} else {
/* multiple times, or ranges */
atimes = msStringSplit (timestring, ',', &numtimes);
if (atimes == NULL || numtimes < 1)
return MS_FALSE;
strlcat(buffer, "(", buffer_size);
for(i=0; i<numtimes; i++) {
if(i!=0) {
strlcat(buffer, " OR ", buffer_size);
}
strlcat(buffer, "(", buffer_size);
aranges = msStringSplit(atimes[i], '/', &numranges);
if(!aranges) return MS_FALSE;
if(numranges == 1) {
/* we don't have range, just a simple time */
createPostgresTimeCompareSimple(timefield, atimes[i], bufferTmp, buffer_size);
strlcat(buffer, bufferTmp, buffer_size);
} else if(numranges == 2) {
/* we have a range */
createPostgresTimeCompareRange(timefield, aranges[0], aranges[1], bufferTmp, buffer_size);
strlcat(buffer, bufferTmp, buffer_size);
} else {
return MS_FALSE;
}
msFreeCharArray(aranges, numranges);
strlcat(buffer, ")", buffer_size);
}
strlcat(buffer, ")", buffer_size);
msFreeCharArray(atimes, numtimes);
}
if(!*buffer) {
return MS_FALSE;
}
if(lp->filteritem) free(lp->filteritem);
lp->filteritem = msStrdup(timefield);
if (&lp->filter) {
/* if the filter is set and it's a string type, concatenate it with
the time. If not just free it */
if (lp->filter.type == MS_EXPRESSION) {
snprintf(bufferTmp, buffer_size, "(%s) and %s", lp->filter.string, buffer);
loadExpressionString(&lp->filter, bufferTmp);
} else {
freeExpression(&lp->filter);
loadExpressionString(&lp->filter, buffer);
}
}
return MS_TRUE;
}
Commit Message: Fix potential SQL Injection with postgis TIME filters (#4834)
CWE ID: CWE-89
|
int msPostGISLayerSetTimeFilter(layerObj *lp, const char *timestring, const char *timefield)
{
char **atimes, **aranges = NULL;
int numtimes=0,i=0,numranges=0;
size_t buffer_size = 512;
char buffer[512], bufferTmp[512];
buffer[0] = '\0';
bufferTmp[0] = '\0';
if (!lp || !timestring || !timefield)
return MS_FALSE;
if( strchr(timestring,'\'') || strchr(timestring, '\\') ) {
msSetError(MS_MISCERR, "Invalid time filter.", "msPostGISLayerSetTimeFilter()");
return MS_FALSE;
}
/* discrete time */
if (strstr(timestring, ",") == NULL &&
strstr(timestring, "/") == NULL) { /* discrete time */
createPostgresTimeCompareSimple(timefield, timestring, buffer, buffer_size);
} else {
/* multiple times, or ranges */
atimes = msStringSplit (timestring, ',', &numtimes);
if (atimes == NULL || numtimes < 1)
return MS_FALSE;
strlcat(buffer, "(", buffer_size);
for(i=0; i<numtimes; i++) {
if(i!=0) {
strlcat(buffer, " OR ", buffer_size);
}
strlcat(buffer, "(", buffer_size);
aranges = msStringSplit(atimes[i], '/', &numranges);
if(!aranges) return MS_FALSE;
if(numranges == 1) {
/* we don't have range, just a simple time */
createPostgresTimeCompareSimple(timefield, atimes[i], bufferTmp, buffer_size);
strlcat(buffer, bufferTmp, buffer_size);
} else if(numranges == 2) {
/* we have a range */
createPostgresTimeCompareRange(timefield, aranges[0], aranges[1], bufferTmp, buffer_size);
strlcat(buffer, bufferTmp, buffer_size);
} else {
return MS_FALSE;
}
msFreeCharArray(aranges, numranges);
strlcat(buffer, ")", buffer_size);
}
strlcat(buffer, ")", buffer_size);
msFreeCharArray(atimes, numtimes);
}
if(!*buffer) {
return MS_FALSE;
}
if(lp->filteritem) free(lp->filteritem);
lp->filteritem = msStrdup(timefield);
if (&lp->filter) {
/* if the filter is set and it's a string type, concatenate it with
the time. If not just free it */
if (lp->filter.type == MS_EXPRESSION) {
snprintf(bufferTmp, buffer_size, "(%s) and %s", lp->filter.string, buffer);
loadExpressionString(&lp->filter, bufferTmp);
} else {
freeExpression(&lp->filter);
loadExpressionString(&lp->filter, buffer);
}
}
return MS_TRUE;
}
| 166,525
|
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 RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) {
if (!ShouldAllowSession(session))
return false;
protocol::EmulationHandler* emulation_handler =
new protocol::EmulationHandler();
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(new protocol::DOMHandler()));
session->AddHandler(base::WrapUnique(emulation_handler));
session->AddHandler(base::WrapUnique(new protocol::InputHandler()));
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::MemoryHandler()));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(
GetId(),
frame_tree_node_ ? frame_tree_node_->devtools_frame_token()
: base::UnguessableToken(),
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler()));
session->AddHandler(base::WrapUnique(new protocol::StorageHandler()));
session->AddHandler(base::WrapUnique(new protocol::TargetHandler(
session->client()->MayAttachToBrowser()
? protocol::TargetHandler::AccessMode::kRegular
: protocol::TargetHandler::AccessMode::kAutoAttachOnly,
GetId(), GetRendererChannel(), session->GetRootSession())));
session->AddHandler(base::WrapUnique(new protocol::PageHandler(
emulation_handler, session->client()->MayAffectLocalFiles())));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
if (!frame_tree_node_ || !frame_tree_node_->parent()) {
session->AddHandler(base::WrapUnique(
new protocol::TracingHandler(frame_tree_node_, GetIOContext())));
}
if (sessions().empty()) {
bool use_video_capture_api = true;
#ifdef OS_ANDROID
if (!CompositorImpl::IsInitialized())
use_video_capture_api = false;
#endif
if (!use_video_capture_api)
frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder());
GrantPolicy();
#if defined(OS_ANDROID)
GetWakeLock()->RequestWakeLock();
#endif
}
return true;
}
Commit Message: [DevTools] Guard DOM.setFileInputFiles under MayAffectLocalFiles
Bug: 805557
Change-Id: Ib6f37ec6e1d091ee54621cc0c5c44f1a6beab10f
Reviewed-on: https://chromium-review.googlesource.com/c/1334847
Reviewed-by: Pavel Feldman <pfeldman@chromium.org>
Commit-Queue: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#607902}
CWE ID: CWE-254
|
bool RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) {
if (!ShouldAllowSession(session))
return false;
protocol::EmulationHandler* emulation_handler =
new protocol::EmulationHandler();
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(
new protocol::DOMHandler(session->client()->MayAffectLocalFiles())));
session->AddHandler(base::WrapUnique(emulation_handler));
session->AddHandler(base::WrapUnique(new protocol::InputHandler()));
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::MemoryHandler()));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(
GetId(),
frame_tree_node_ ? frame_tree_node_->devtools_frame_token()
: base::UnguessableToken(),
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler()));
session->AddHandler(base::WrapUnique(new protocol::StorageHandler()));
session->AddHandler(base::WrapUnique(new protocol::TargetHandler(
session->client()->MayAttachToBrowser()
? protocol::TargetHandler::AccessMode::kRegular
: protocol::TargetHandler::AccessMode::kAutoAttachOnly,
GetId(), GetRendererChannel(), session->GetRootSession())));
session->AddHandler(base::WrapUnique(new protocol::PageHandler(
emulation_handler, session->client()->MayAffectLocalFiles())));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
if (!frame_tree_node_ || !frame_tree_node_->parent()) {
session->AddHandler(base::WrapUnique(
new protocol::TracingHandler(frame_tree_node_, GetIOContext())));
}
if (sessions().empty()) {
bool use_video_capture_api = true;
#ifdef OS_ANDROID
if (!CompositorImpl::IsInitialized())
use_video_capture_api = false;
#endif
if (!use_video_capture_api)
frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder());
GrantPolicy();
#if defined(OS_ANDROID)
GetWakeLock()->RequestWakeLock();
#endif
}
return true;
}
| 173,114
|
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* sspi_SecureHandleGetUpperPointer(SecHandle* handle)
{
void* pointer;
if (!handle)
return NULL;
pointer = (void*) ~((size_t) handle->dwUpper);
return pointer;
}
Commit Message: nla: invalidate sec handle after creation
If sec pointer isn't invalidated after creation it is not possible
to check if the upper and lower pointers are valid.
This fixes a segfault in the server part if the client disconnects before
the authentication was finished.
CWE ID: CWE-476
|
void* sspi_SecureHandleGetUpperPointer(SecHandle* handle)
{
void* pointer;
if (!handle || !SecIsValidHandle(handle))
return NULL;
pointer = (void*) ~((size_t) handle->dwUpper);
return pointer;
}
| 167,605
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: pop_decoder_state (DECODER_STATE ds)
{
if (!ds->idx)
{
fprintf (stderr, "ERROR: decoder stack underflow!\n");
abort ();
}
ds->cur = ds->stack[--ds->idx];
}
Commit Message:
CWE ID: CWE-20
|
pop_decoder_state (DECODER_STATE ds)
{
if (!ds->idx)
{
fprintf (stderr, "ksba: ber-decoder: stack underflow!\n");
return gpg_error (GPG_ERR_INTERNAL);
}
ds->cur = ds->stack[--ds->idx];
return 0;
}
| 165,051
|
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 ParamTraits<AudioParameters>::Read(const Message* m,
PickleIterator* iter,
AudioParameters* r) {
int format, channel_layout, sample_rate, bits_per_sample,
frames_per_buffer, channels;
if (!m->ReadInt(iter, &format) ||
!m->ReadInt(iter, &channel_layout) ||
!m->ReadInt(iter, &sample_rate) ||
!m->ReadInt(iter, &bits_per_sample) ||
!m->ReadInt(iter, &frames_per_buffer) ||
!m->ReadInt(iter, &channels))
return false;
r->Reset(static_cast<AudioParameters::Format>(format),
static_cast<ChannelLayout>(channel_layout),
sample_rate, bits_per_sample, frames_per_buffer);
return true;
}
Commit Message: Improve validation when creating audio streams.
BUG=166795
Review URL: https://codereview.chromium.org/11647012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173981 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
|
bool ParamTraits<AudioParameters>::Read(const Message* m,
PickleIterator* iter,
AudioParameters* r) {
int format, channel_layout, sample_rate, bits_per_sample,
frames_per_buffer, channels;
if (!m->ReadInt(iter, &format) ||
!m->ReadInt(iter, &channel_layout) ||
!m->ReadInt(iter, &sample_rate) ||
!m->ReadInt(iter, &bits_per_sample) ||
!m->ReadInt(iter, &frames_per_buffer) ||
!m->ReadInt(iter, &channels))
return false;
r->Reset(static_cast<AudioParameters::Format>(format),
static_cast<ChannelLayout>(channel_layout),
sample_rate, bits_per_sample, frames_per_buffer);
if (!r->IsValid())
return false;
return true;
}
| 171,526
|
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: sf_open_virtual (SF_VIRTUAL_IO *sfvirtual, int mode, SF_INFO *sfinfo, void *user_data)
{ SF_PRIVATE *psf ;
/* Make sure we have a valid set ot virtual pointers. */
if (sfvirtual->get_filelen == NULL || sfvirtual->seek == NULL || sfvirtual->tell == NULL)
{ sf_errno = SFE_BAD_VIRTUAL_IO ;
snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_get_filelen / vio_seek / vio_tell in SF_VIRTUAL_IO struct.\n") ;
return NULL ;
} ;
if ((mode == SFM_READ || mode == SFM_RDWR) && sfvirtual->read == NULL)
{ sf_errno = SFE_BAD_VIRTUAL_IO ;
snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_read in SF_VIRTUAL_IO struct.\n") ;
return NULL ;
} ;
if ((mode == SFM_WRITE || mode == SFM_RDWR) && sfvirtual->write == NULL)
{ sf_errno = SFE_BAD_VIRTUAL_IO ;
snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_write in SF_VIRTUAL_IO struct.\n") ;
return NULL ;
} ;
if ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL)
{ sf_errno = SFE_MALLOC_FAILED ;
return NULL ;
} ;
psf_init_files (psf) ;
psf->virtual_io = SF_TRUE ;
psf->vio = *sfvirtual ;
psf->vio_user_data = user_data ;
psf->file.mode = mode ;
return psf_open_file (psf, sfinfo) ;
} /* sf_open_virtual */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119
|
sf_open_virtual (SF_VIRTUAL_IO *sfvirtual, int mode, SF_INFO *sfinfo, void *user_data)
{ SF_PRIVATE *psf ;
/* Make sure we have a valid set ot virtual pointers. */
if (sfvirtual->get_filelen == NULL || sfvirtual->seek == NULL || sfvirtual->tell == NULL)
{ sf_errno = SFE_BAD_VIRTUAL_IO ;
snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_get_filelen / vio_seek / vio_tell in SF_VIRTUAL_IO struct.\n") ;
return NULL ;
} ;
if ((mode == SFM_READ || mode == SFM_RDWR) && sfvirtual->read == NULL)
{ sf_errno = SFE_BAD_VIRTUAL_IO ;
snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_read in SF_VIRTUAL_IO struct.\n") ;
return NULL ;
} ;
if ((mode == SFM_WRITE || mode == SFM_RDWR) && sfvirtual->write == NULL)
{ sf_errno = SFE_BAD_VIRTUAL_IO ;
snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_write in SF_VIRTUAL_IO struct.\n") ;
return NULL ;
} ;
if ((psf = psf_allocate ()) == NULL)
{ sf_errno = SFE_MALLOC_FAILED ;
return NULL ;
} ;
psf_init_files (psf) ;
psf->virtual_io = SF_TRUE ;
psf->vio = *sfvirtual ;
psf->vio_user_data = user_data ;
psf->file.mode = mode ;
return psf_open_file (psf, sfinfo) ;
} /* sf_open_virtual */
| 170,069
|
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: standard_info_part2(standard_display *dp, png_const_structp pp,
png_const_infop pi, int nImages)
{
/* Record cbRow now that it can be found. */
dp->pixel_size = bit_size(pp, png_get_color_type(pp, pi),
png_get_bit_depth(pp, pi));
dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size;
dp->cbRow = png_get_rowbytes(pp, pi);
/* Validate the rowbytes here again. */
if (dp->cbRow != (dp->bit_width+7)/8)
png_error(pp, "bad png_get_rowbytes calculation");
/* Then ensure there is enough space for the output image(s). */
store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
standard_info_part2(standard_display *dp, png_const_structp pp,
png_const_infop pi, int nImages)
{
/* Record cbRow now that it can be found. */
{
png_byte ct = png_get_color_type(pp, pi);
png_byte bd = png_get_bit_depth(pp, pi);
if (bd >= 8 && (ct == PNG_COLOR_TYPE_RGB || ct == PNG_COLOR_TYPE_GRAY) &&
dp->filler)
ct |= 4; /* handle filler as faked alpha channel */
dp->pixel_size = bit_size(pp, ct, bd);
}
dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size;
dp->cbRow = png_get_rowbytes(pp, pi);
/* Validate the rowbytes here again. */
if (dp->cbRow != (dp->bit_width+7)/8)
png_error(pp, "bad png_get_rowbytes calculation");
/* Then ensure there is enough space for the output image(s). */
store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h);
}
| 173,699
|
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: cib_remote_signon(cib_t * cib, const char *name, enum cib_conn_type type)
{
int rc = pcmk_ok;
cib_remote_opaque_t *private = cib->variant_opaque;
if (private->passwd == NULL) {
struct termios settings;
int rc;
rc = tcgetattr(0, &settings);
settings.c_lflag &= ~ECHO;
rc = tcsetattr(0, TCSANOW, &settings);
fprintf(stderr, "Password: ");
private->passwd = calloc(1, 1024);
rc = scanf("%s", private->passwd);
fprintf(stdout, "\n");
/* fprintf(stderr, "entered: '%s'\n", buffer); */
if (rc < 1) {
private->passwd = NULL;
}
settings.c_lflag |= ECHO;
rc = tcsetattr(0, TCSANOW, &settings);
}
if (private->server == NULL || private->user == NULL) {
rc = -EINVAL;
}
if (rc == pcmk_ok) {
rc = cib_tls_signon(cib, &(private->command));
}
if (rc == pcmk_ok) {
rc = cib_tls_signon(cib, &(private->callback));
}
if (rc == pcmk_ok) {
xmlNode *hello =
cib_create_op(0, private->callback.token, CRM_OP_REGISTER, NULL, NULL, NULL, 0, NULL);
crm_xml_add(hello, F_CIB_CLIENTNAME, name);
crm_send_remote_msg(private->command.session, hello, private->command.encrypted);
free_xml(hello);
}
if (rc == pcmk_ok) {
fprintf(stderr, "%s: Opened connection to %s:%d\n", name, private->server, private->port);
cib->state = cib_connected_command;
cib->type = cib_command;
} else {
fprintf(stderr, "%s: Connection to %s:%d failed: %s\n",
name, private->server, private->port, pcmk_strerror(rc));
}
return rc;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
|
cib_remote_signon(cib_t * cib, const char *name, enum cib_conn_type type)
{
int rc = pcmk_ok;
cib_remote_opaque_t *private = cib->variant_opaque;
if (private->passwd == NULL) {
struct termios settings;
int rc;
rc = tcgetattr(0, &settings);
settings.c_lflag &= ~ECHO;
rc = tcsetattr(0, TCSANOW, &settings);
fprintf(stderr, "Password: ");
private->passwd = calloc(1, 1024);
rc = scanf("%s", private->passwd);
fprintf(stdout, "\n");
/* fprintf(stderr, "entered: '%s'\n", buffer); */
if (rc < 1) {
private->passwd = NULL;
}
settings.c_lflag |= ECHO;
rc = tcsetattr(0, TCSANOW, &settings);
}
if (private->server == NULL || private->user == NULL) {
rc = -EINVAL;
}
if (rc == pcmk_ok) {
rc = cib_tls_signon(cib, &(private->command), FALSE);
}
if (rc == pcmk_ok) {
rc = cib_tls_signon(cib, &(private->callback), TRUE);
}
if (rc == pcmk_ok) {
xmlNode *hello =
cib_create_op(0, private->callback.token, CRM_OP_REGISTER, NULL, NULL, NULL, 0, NULL);
crm_xml_add(hello, F_CIB_CLIENTNAME, name);
crm_send_remote_msg(private->command.session, hello, private->command.encrypted);
free_xml(hello);
}
if (rc == pcmk_ok) {
fprintf(stderr, "%s: Opened connection to %s:%d\n", name, private->server, private->port);
cib->state = cib_connected_command;
cib->type = cib_command;
} else {
fprintf(stderr, "%s: Connection to %s:%d failed: %s\n",
name, private->server, private->port, pcmk_strerror(rc));
}
return rc;
}
| 166,153
|
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 linear_ioctl(struct dm_target *ti, unsigned int cmd,
unsigned long arg)
{
struct linear_c *lc = (struct linear_c *) ti->private;
return __blkdev_driver_ioctl(lc->dev->bdev, lc->dev->mode, cmd, arg);
}
Commit Message: dm: do not forward ioctls from logical volumes to the underlying device
A logical volume can map to just part of underlying physical volume.
In this case, it must be treated like a partition.
Based on a patch from Alasdair G Kergon.
Cc: Alasdair G Kergon <agk@redhat.com>
Cc: dm-devel@redhat.com
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
CWE ID: CWE-264
|
static int linear_ioctl(struct dm_target *ti, unsigned int cmd,
unsigned long arg)
{
struct linear_c *lc = (struct linear_c *) ti->private;
struct dm_dev *dev = lc->dev;
int r = 0;
/*
* Only pass ioctls through if the device sizes match exactly.
*/
if (lc->start ||
ti->len != i_size_read(dev->bdev->bd_inode) >> SECTOR_SHIFT)
r = scsi_verify_blk_ioctl(NULL, cmd);
return r ? : __blkdev_driver_ioctl(dev->bdev, dev->mode, cmd, arg);
}
| 165,723
|
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 Editor::insertTextWithoutSendingTextEvent(const String& text,
bool selectInsertedText,
TextEvent* triggeringEvent) {
if (text.isEmpty())
return false;
const VisibleSelection& selection = selectionForCommand(triggeringEvent);
if (!selection.isContentEditable())
return false;
spellChecker().updateMarkersForWordsAffectedByEditing(
isSpaceOrNewline(text[0]));
TypingCommand::insertText(
*selection.start().document(), text, selection,
selectInsertedText ? TypingCommand::SelectInsertedText : 0,
triggeringEvent && triggeringEvent->isComposition()
? TypingCommand::TextCompositionConfirm
: TypingCommand::TextCompositionNone);
if (LocalFrame* editedFrame = selection.start().document()->frame()) {
if (Page* page = editedFrame->page()) {
LocalFrame* focusedOrMainFrame =
toLocalFrame(page->focusController().focusedOrMainFrame());
focusedOrMainFrame->selection().revealSelection(
ScrollAlignment::alignCenterIfNeeded);
}
}
return true;
}
Commit Message: Make TypingCommand::insertText() to take SelectionInDOMTree instead of VisibleSelection
This patch makes |TypingCommand::insertText()| to take |SelectionInDOMTree|
instead of |VisibleSelection| to reduce usage of |VisibleSelection| for
improving code health.
BUG=657237
TEST=n/a
Review-Url: https://codereview.chromium.org/2733183002
Cr-Commit-Position: refs/heads/master@{#455368}
CWE ID:
|
bool Editor::insertTextWithoutSendingTextEvent(const String& text,
bool selectInsertedText,
TextEvent* triggeringEvent) {
if (text.isEmpty())
return false;
const VisibleSelection& selection = selectionForCommand(triggeringEvent);
if (!selection.isContentEditable())
return false;
spellChecker().updateMarkersForWordsAffectedByEditing(
isSpaceOrNewline(text[0]));
TypingCommand::insertText(
*selection.start().document(), text, selection.asSelection(),
selectInsertedText ? TypingCommand::SelectInsertedText : 0,
triggeringEvent && triggeringEvent->isComposition()
? TypingCommand::TextCompositionConfirm
: TypingCommand::TextCompositionNone);
if (LocalFrame* editedFrame = selection.start().document()->frame()) {
if (Page* page = editedFrame->page()) {
LocalFrame* focusedOrMainFrame =
toLocalFrame(page->focusController().focusedOrMainFrame());
focusedOrMainFrame->selection().revealSelection(
ScrollAlignment::alignCenterIfNeeded);
}
}
return true;
}
| 172,030
|
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 jlong Region_createFromParcel(JNIEnv* env, jobject clazz, jobject parcel)
{
if (parcel == NULL) {
return NULL;
}
android::Parcel* p = android::parcelForJavaObject(env, parcel);
SkRegion* region = new SkRegion;
size_t size = p->readInt32();
region->readFromMemory(p->readInplace(size), size);
return reinterpret_cast<jlong>(region);
}
Commit Message: Check that the parcel contained the expected amount of region data. DO NOT MERGE
bug:20883006
Change-Id: Ib47a8ec8696dbc37e958b8dbceb43fcbabf6605b
CWE ID: CWE-264
|
static jlong Region_createFromParcel(JNIEnv* env, jobject clazz, jobject parcel)
{
if (parcel == NULL) {
return NULL;
}
android::Parcel* p = android::parcelForJavaObject(env, parcel);
const size_t size = p->readInt32();
const void* regionData = p->readInplace(size);
if (regionData == NULL) {
return NULL;
}
SkRegion* region = new SkRegion;
region->readFromMemory(regionData, size);
return reinterpret_cast<jlong>(region);
}
| 173,341
|
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 set_sda(int state)
{
qrio_set_opendrain_gpio(DEBLOCK_PORT1, DEBLOCK_SDA1, state);
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787
|
void set_sda(int state)
| 169,633
|
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 ParamTraits<SkBitmap>::Log(const SkBitmap& p, std::string* l) {
l->append("<SkBitmap>");
}
Commit Message: Update IPC ParamTraits for SkBitmap to follow best practices.
Using memcpy() to serialize a POD struct is highly discouraged. Just use
the standard IPC param traits macros for doing it.
Bug: 779428
Change-Id: I48f52c1f5c245ba274d595829ed92e8b3cb41334
Reviewed-on: https://chromium-review.googlesource.com/899649
Reviewed-by: Tom Sepez <tsepez@chromium.org>
Commit-Queue: Daniel Cheng <dcheng@chromium.org>
Cr-Commit-Position: refs/heads/master@{#534562}
CWE ID: CWE-125
|
void ParamTraits<SkBitmap>::Log(const SkBitmap& p, std::string* l) {
l->append("<SkBitmap>");
LogParam(p.info(), l);
}
| 172,893
|
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: xmlParseNmtoken(xmlParserCtxtPtr ctxt) {
xmlChar buf[XML_MAX_NAMELEN + 5];
int len = 0, l;
int c;
int count = 0;
#ifdef DEBUG
nbParseNmToken++;
#endif
GROW;
c = CUR_CHAR(l);
while (xmlIsNameChar(ctxt, c)) {
if (count++ > 100) {
count = 0;
GROW;
}
COPY_BUF(l,buf,len,c);
NEXTL(l);
c = CUR_CHAR(l);
if (len >= XML_MAX_NAMELEN) {
/*
* Okay someone managed to make a huge token, so he's ready to pay
* for the processing speed.
*/
xmlChar *buffer;
int max = len * 2;
buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar));
if (buffer == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
memcpy(buffer, buf, len);
while (xmlIsNameChar(ctxt, c)) {
if (count++ > 100) {
count = 0;
GROW;
}
if (len + 10 > max) {
xmlChar *tmp;
max *= 2;
tmp = (xmlChar *) xmlRealloc(buffer,
max * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buffer);
return(NULL);
}
buffer = tmp;
}
COPY_BUF(l,buffer,len,c);
NEXTL(l);
c = CUR_CHAR(l);
}
buffer[len] = 0;
return(buffer);
}
}
if (len == 0)
return(NULL);
return(xmlStrndup(buf, len));
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
xmlParseNmtoken(xmlParserCtxtPtr ctxt) {
xmlChar buf[XML_MAX_NAMELEN + 5];
int len = 0, l;
int c;
int count = 0;
#ifdef DEBUG
nbParseNmToken++;
#endif
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
c = CUR_CHAR(l);
while (xmlIsNameChar(ctxt, c)) {
if (count++ > 100) {
count = 0;
GROW;
}
COPY_BUF(l,buf,len,c);
NEXTL(l);
c = CUR_CHAR(l);
if (len >= XML_MAX_NAMELEN) {
/*
* Okay someone managed to make a huge token, so he's ready to pay
* for the processing speed.
*/
xmlChar *buffer;
int max = len * 2;
buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar));
if (buffer == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
memcpy(buffer, buf, len);
while (xmlIsNameChar(ctxt, c)) {
if (count++ > 100) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF) {
xmlFree(buffer);
return(NULL);
}
}
if (len + 10 > max) {
xmlChar *tmp;
max *= 2;
tmp = (xmlChar *) xmlRealloc(buffer,
max * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buffer);
return(NULL);
}
buffer = tmp;
}
COPY_BUF(l,buffer,len,c);
NEXTL(l);
c = CUR_CHAR(l);
}
buffer[len] = 0;
return(buffer);
}
}
if (len == 0)
return(NULL);
return(xmlStrndup(buf, len));
}
| 171,298
|
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 MediaStreamDevicesController::IsRequestAllowedByDefault() const {
if (ShouldAlwaysAllowOrigin())
return true;
struct {
bool has_capability;
const char* policy_name;
const char* list_policy_name;
ContentSettingsType settings_type;
} device_checks[] = {
{ microphone_requested_, prefs::kAudioCaptureAllowed,
prefs::kAudioCaptureAllowedUrls, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC },
{ webcam_requested_, prefs::kVideoCaptureAllowed,
prefs::kVideoCaptureAllowedUrls,
CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(device_checks); ++i) {
if (!device_checks[i].has_capability)
continue;
DevicePolicy policy = GetDevicePolicy(device_checks[i].policy_name,
device_checks[i].list_policy_name);
if (policy == ALWAYS_DENY ||
(policy == POLICY_NOT_SET &&
profile_->GetHostContentSettingsMap()->GetContentSetting(
request_.security_origin, request_.security_origin,
device_checks[i].settings_type, NO_RESOURCE_IDENTIFIER) !=
CONTENT_SETTING_ALLOW)) {
return false;
}
}
return true;
}
Commit Message: Make the content setting for webcam/mic sticky for Pepper requests.
This makes the content setting sticky for webcam/mic requests from Pepper from non-https origins.
BUG=249335
R=xians@chromium.org, yzshen@chromium.org
Review URL: https://codereview.chromium.org/17060006
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@206479 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
bool MediaStreamDevicesController::IsRequestAllowedByDefault() const {
if (ShouldAlwaysAllowOrigin())
return true;
struct {
bool has_capability;
const char* policy_name;
const char* list_policy_name;
ContentSettingsType settings_type;
} device_checks[] = {
{ microphone_requested_, prefs::kAudioCaptureAllowed,
prefs::kAudioCaptureAllowedUrls, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC },
{ webcam_requested_, prefs::kVideoCaptureAllowed,
prefs::kVideoCaptureAllowedUrls,
CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(device_checks); ++i) {
if (!device_checks[i].has_capability)
continue;
DevicePolicy policy = GetDevicePolicy(device_checks[i].policy_name,
device_checks[i].list_policy_name);
if (policy == ALWAYS_DENY)
return false;
if (policy == POLICY_NOT_SET) {
// Only load content settings from secure origins unless it is a
// content::MEDIA_OPEN_DEVICE (Pepper) request.
if (!IsSchemeSecure() &&
request_.request_type != content::MEDIA_OPEN_DEVICE) {
return false;
}
if (profile_->GetHostContentSettingsMap()->GetContentSetting(
request_.security_origin, request_.security_origin,
device_checks[i].settings_type, NO_RESOURCE_IDENTIFIER) !=
CONTENT_SETTING_ALLOW) {
return false;
}
}
}
return true;
}
| 171,313
|
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: CmdBufferImageTransportFactory::CreateSharedSurfaceHandle() {
if (!context_->makeContextCurrent()) {
NOTREACHED() << "Failed to make shared graphics context current";
return gfx::GLSurfaceHandle();
}
gfx::GLSurfaceHandle handle = gfx::GLSurfaceHandle(
gfx::kNullPluginWindow, true);
handle.parent_gpu_process_id = context_->GetGPUProcessID();
handle.parent_client_id = context_->GetChannelID();
handle.parent_context_id = context_->GetContextID();
handle.parent_texture_id[0] = context_->createTexture();
handle.parent_texture_id[1] = context_->createTexture();
handle.sync_point = context_->insertSyncPoint();
context_->flush();
return handle;
}
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
TBR=sky@chromium.org
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:
|
CmdBufferImageTransportFactory::CreateSharedSurfaceHandle() {
if (!context_->makeContextCurrent()) {
NOTREACHED() << "Failed to make shared graphics context current";
return gfx::GLSurfaceHandle();
}
gfx::GLSurfaceHandle handle = gfx::GLSurfaceHandle(
gfx::kNullPluginWindow, true);
handle.parent_gpu_process_id = context_->GetGPUProcessID();
context_->flush();
return handle;
}
| 171,363
|
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 get_nb10(ut8* dbg_data, SCV_NB10_HEADER* res) {
const int nb10sz = 16;
memcpy (res, dbg_data, nb10sz);
res->file_name = (ut8*) strdup ((const char*) dbg_data + nb10sz);
}
Commit Message: Fix crash in pe
CWE ID: CWE-125
|
static void get_nb10(ut8* dbg_data, SCV_NB10_HEADER* res) {
const int nb10sz = 16;
// memcpy (res, dbg_data, nb10sz);
// res->file_name = (ut8*) strdup ((const char*) dbg_data + nb10sz);
}
| 169,229
|
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: cib_remote_connection_destroy(gpointer user_data)
{
cib_client_t *client = user_data;
if (client == NULL) {
return;
}
crm_trace("Cleaning up after client disconnect: %s/%s",
crm_str(client->name), client->id);
if (client->id != NULL) {
if (!g_hash_table_remove(client_list, client->id)) {
crm_err("Client %s not found in the hashtable", client->name);
}
}
crm_trace("Destroying %s (%p)", client->name, user_data);
num_clients--;
crm_trace("Num unfree'd clients: %d", num_clients);
free(client->name);
free(client->callback_id);
free(client->id);
free(client->user);
free(client);
crm_trace("Freed the cib client");
if (cib_shutdown_flag) {
cib_shutdown(0);
}
return;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
|
cib_remote_connection_destroy(gpointer user_data)
{
cib_client_t *client = user_data;
int csock = 0;
if (client == NULL) {
return;
}
crm_trace("Cleaning up after client disconnect: %s/%s",
crm_str(client->name), client->id);
if (client->id != NULL) {
if (!g_hash_table_remove(client_list, client->id)) {
crm_err("Client %s not found in the hashtable", client->name);
}
}
crm_trace("Destroying %s (%p)", client->name, user_data);
num_clients--;
crm_trace("Num unfree'd clients: %d", num_clients);
if (client->remote_auth_timeout) {
g_source_remove(client->remote_auth_timeout);
}
if (client->encrypted) {
#ifdef HAVE_GNUTLS_GNUTLS_H
if (client->session) {
void *sock_ptr = gnutls_transport_get_ptr(*client->session);
csock = GPOINTER_TO_INT(sock_ptr);
if (client->handshake_complete) {
gnutls_bye(*client->session, GNUTLS_SHUT_WR);
}
gnutls_deinit(*client->session);
gnutls_free(client->session);
}
#endif
} else {
csock = GPOINTER_TO_INT(client->session);
}
client->session = NULL;
if (csock > 0) {
close(csock);
}
free(client->name);
free(client->callback_id);
free(client->id);
free(client->user);
free(client->recv_buf);
free(client);
crm_trace("Freed the cib client");
if (cib_shutdown_flag) {
cib_shutdown(0);
}
return;
}
| 166,147
|
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 SparseBitSet::initFromRanges(const uint32_t* ranges, size_t nRanges) {
if (nRanges == 0) {
mMaxVal = 0;
mIndices.reset();
mBitmaps.reset();
return;
}
mMaxVal = ranges[nRanges * 2 - 1];
size_t indexSize = (mMaxVal + kPageMask) >> kLogValuesPerPage;
mIndices.reset(new uint32_t[indexSize]);
uint32_t nPages = calcNumPages(ranges, nRanges);
mBitmaps.reset(new element[nPages << (kLogValuesPerPage - kLogBitsPerEl)]);
memset(mBitmaps.get(), 0, nPages << (kLogValuesPerPage - 3));
mZeroPageIndex = noZeroPage;
uint32_t nonzeroPageEnd = 0;
uint32_t currentPage = 0;
for (size_t i = 0; i < nRanges; i++) {
uint32_t start = ranges[i * 2];
uint32_t end = ranges[i * 2 + 1];
uint32_t startPage = start >> kLogValuesPerPage;
uint32_t endPage = (end - 1) >> kLogValuesPerPage;
if (startPage >= nonzeroPageEnd) {
if (startPage > nonzeroPageEnd) {
if (mZeroPageIndex == noZeroPage) {
mZeroPageIndex = (currentPage++) << (kLogValuesPerPage - kLogBitsPerEl);
}
for (uint32_t j = nonzeroPageEnd; j < startPage; j++) {
mIndices[j] = mZeroPageIndex;
}
}
mIndices[startPage] = (currentPage++) << (kLogValuesPerPage - kLogBitsPerEl);
}
size_t index = ((currentPage - 1) << (kLogValuesPerPage - kLogBitsPerEl)) +
((start & kPageMask) >> kLogBitsPerEl);
size_t nElements = (end - (start & ~kElMask) + kElMask) >> kLogBitsPerEl;
if (nElements == 1) {
mBitmaps[index] |= (kElAllOnes >> (start & kElMask)) &
(kElAllOnes << ((-end) & kElMask));
} else {
mBitmaps[index] |= kElAllOnes >> (start & kElMask);
for (size_t j = 1; j < nElements - 1; j++) {
mBitmaps[index + j] = kElAllOnes;
}
mBitmaps[index + nElements - 1] |= kElAllOnes << ((-end) & kElMask);
}
for (size_t j = startPage + 1; j < endPage + 1; j++) {
mIndices[j] = (currentPage++) << (kLogValuesPerPage - kLogBitsPerEl);
}
nonzeroPageEnd = endPage + 1;
}
}
Commit Message: Reject fonts with invalid ranges in cmap
A corrupt or malicious font may have a negative size in its cmap
range, which in turn could lead to memory corruption. This patch
detects the case and rejects the font, and also includes an assertion
in the sparse bit set implementation if we missed any such case.
External issue:
https://code.google.com/p/android/issues/detail?id=192618
Bug: 26413177
Change-Id: Icc0c80e4ef389abba0964495b89aa0fae3e9f4b2
CWE ID: CWE-20
|
void SparseBitSet::initFromRanges(const uint32_t* ranges, size_t nRanges) {
if (nRanges == 0) {
mMaxVal = 0;
mIndices.reset();
mBitmaps.reset();
return;
}
mMaxVal = ranges[nRanges * 2 - 1];
size_t indexSize = (mMaxVal + kPageMask) >> kLogValuesPerPage;
mIndices.reset(new uint32_t[indexSize]);
uint32_t nPages = calcNumPages(ranges, nRanges);
mBitmaps.reset(new element[nPages << (kLogValuesPerPage - kLogBitsPerEl)]);
memset(mBitmaps.get(), 0, nPages << (kLogValuesPerPage - 3));
mZeroPageIndex = noZeroPage;
uint32_t nonzeroPageEnd = 0;
uint32_t currentPage = 0;
for (size_t i = 0; i < nRanges; i++) {
uint32_t start = ranges[i * 2];
uint32_t end = ranges[i * 2 + 1];
LOG_ALWAYS_FATAL_IF(end < start); // make sure range size is nonnegative
uint32_t startPage = start >> kLogValuesPerPage;
uint32_t endPage = (end - 1) >> kLogValuesPerPage;
if (startPage >= nonzeroPageEnd) {
if (startPage > nonzeroPageEnd) {
if (mZeroPageIndex == noZeroPage) {
mZeroPageIndex = (currentPage++) << (kLogValuesPerPage - kLogBitsPerEl);
}
for (uint32_t j = nonzeroPageEnd; j < startPage; j++) {
mIndices[j] = mZeroPageIndex;
}
}
mIndices[startPage] = (currentPage++) << (kLogValuesPerPage - kLogBitsPerEl);
}
size_t index = ((currentPage - 1) << (kLogValuesPerPage - kLogBitsPerEl)) +
((start & kPageMask) >> kLogBitsPerEl);
size_t nElements = (end - (start & ~kElMask) + kElMask) >> kLogBitsPerEl;
if (nElements == 1) {
mBitmaps[index] |= (kElAllOnes >> (start & kElMask)) &
(kElAllOnes << ((-end) & kElMask));
} else {
mBitmaps[index] |= kElAllOnes >> (start & kElMask);
for (size_t j = 1; j < nElements - 1; j++) {
mBitmaps[index + j] = kElAllOnes;
}
mBitmaps[index + nElements - 1] |= kElAllOnes << ((-end) & kElMask);
}
for (size_t j = startPage + 1; j < endPage + 1; j++) {
mIndices[j] = (currentPage++) << (kLogValuesPerPage - kLogBitsPerEl);
}
nonzeroPageEnd = endPage + 1;
}
}
| 174,236
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: virtual void SetUp() {
UUT_ = GET_PARAM(2);
/* Set up guard blocks for an inner block centered in the outer block */
for (int i = 0; i < kOutputBufferSize; ++i) {
if (IsIndexInBorder(i))
output_[i] = 255;
else
output_[i] = 0;
}
::libvpx_test::ACMRandom prng;
for (int i = 0; i < kInputBufferSize; ++i)
input_[i] = prng.Rand8Extremes();
}
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 SetUp() {
UUT_ = GET_PARAM(2);
#if CONFIG_VP9_HIGHBITDEPTH
if (UUT_->use_highbd_ != 0)
mask_ = (1 << UUT_->use_highbd_) - 1;
else
mask_ = 255;
#endif
/* Set up guard blocks for an inner block centered in the outer block */
for (int i = 0; i < kOutputBufferSize; ++i) {
if (IsIndexInBorder(i))
output_[i] = 255;
else
output_[i] = 0;
}
::libvpx_test::ACMRandom prng;
for (int i = 0; i < kInputBufferSize; ++i) {
if (i & 1) {
input_[i] = 255;
#if CONFIG_VP9_HIGHBITDEPTH
input16_[i] = mask_;
#endif
} else {
input_[i] = prng.Rand8Extremes();
#if CONFIG_VP9_HIGHBITDEPTH
input16_[i] = prng.Rand16() & mask_;
#endif
}
}
}
| 174,505
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_FUNCTION(locale_get_display_variant)
{
get_icu_disp_value_src_php( LOC_VARIANT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125
|
PHP_FUNCTION(locale_get_display_variant)
PHP_FUNCTION(locale_get_display_variant)
{
get_icu_disp_value_src_php( LOC_VARIANT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
| 167,189
|
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: alloc_limit_failure (char *fn_name, size_t size)
{
fprintf (stderr,
"%s: Maximum allocation size exceeded "
"(maxsize = %lu; size = %lu).\n",
fn_name,
(unsigned long)alloc_limit,
(unsigned long)size);
}
Commit Message: Fix integer overflows and harden memory allocator.
CWE ID: CWE-190
|
alloc_limit_failure (char *fn_name, size_t size)
{
fprintf (stderr,
"%s: Maximum allocation size exceeded "
"(maxsize = %lu; size = %lu).\n",
fn_name,
(unsigned long)alloc_limit,
(unsigned long)size);
}
| 168,355
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int tls_construct_cke_ecdhe(SSL *s, unsigned char **p, int *len, int *al)
{
#ifndef OPENSSL_NO_EC
unsigned char *encodedPoint = NULL;
int encoded_pt_len = 0;
EVP_PKEY *ckey = NULL, *skey = NULL;
skey = s->s3->peer_tmp;
if (skey == NULL) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
return 0;
}
ckey = ssl_generate_pkey(skey);
if (ssl_derive(s, ckey, skey) == 0) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EVP_LIB);
goto err;
}
/* Generate encoding of client key */
encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(ckey, &encodedPoint);
if (encoded_pt_len == 0) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EC_LIB);
goto err;
}
EVP_PKEY_free(ckey);
ckey = NULL;
*len = encoded_pt_len;
/* length of encoded point */
**p = *len;
*p += 1;
/* copy the point */
memcpy(*p, encodedPoint, *len);
/* increment len to account for length field */
*len += 1;
OPENSSL_free(encodedPoint);
return 1;
err:
EVP_PKEY_free(ckey);
return 0;
#else
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
#endif
}
Commit Message: Fix missing NULL checks in CKE processing
Reviewed-by: Rich Salz <rsalz@openssl.org>
CWE ID: CWE-476
|
static int tls_construct_cke_ecdhe(SSL *s, unsigned char **p, int *len, int *al)
{
#ifndef OPENSSL_NO_EC
unsigned char *encodedPoint = NULL;
int encoded_pt_len = 0;
EVP_PKEY *ckey = NULL, *skey = NULL;
skey = s->s3->peer_tmp;
if (skey == NULL) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
return 0;
}
ckey = ssl_generate_pkey(skey);
if (ckey == NULL) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
goto err;
}
if (ssl_derive(s, ckey, skey) == 0) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EVP_LIB);
goto err;
}
/* Generate encoding of client key */
encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(ckey, &encodedPoint);
if (encoded_pt_len == 0) {
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EC_LIB);
goto err;
}
EVP_PKEY_free(ckey);
ckey = NULL;
*len = encoded_pt_len;
/* length of encoded point */
**p = *len;
*p += 1;
/* copy the point */
memcpy(*p, encodedPoint, *len);
/* increment len to account for length field */
*len += 1;
OPENSSL_free(encodedPoint);
return 1;
err:
EVP_PKEY_free(ckey);
return 0;
#else
SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
#endif
}
| 168,434
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static ssize_t driver_override_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
return sprintf(buf, "%s\n", pdev->driver_override);
}
Commit Message: driver core: platform: fix race condition with driver_override
The driver_override implementation is susceptible to race condition when
different threads are reading vs storing a different driver override.
Add locking to avoid race condition.
Fixes: 3d713e0e382e ("driver core: platform: add device binding path 'driver_override'")
Cc: stable@vger.kernel.org
Signed-off-by: Adrian Salido <salidoa@google.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
CWE ID: CWE-362
|
static ssize_t driver_override_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
ssize_t len;
device_lock(dev);
len = sprintf(buf, "%s\n", pdev->driver_override);
device_unlock(dev);
return len;
}
| 167,991
|
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 read_public_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = file->size;
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_public_key(p, keysize, rsa);
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415
|
static int read_public_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = MIN(file->size, sizeof buf);
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_public_key(p, keysize, rsa);
}
| 169,081
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE SoftMPEG4Encoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (bitRate->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
bitRate->eControlRate = OMX_Video_ControlRateVariable;
bitRate->nTargetBitrate = mBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoH263:
{
OMX_VIDEO_PARAM_H263TYPE *h263type =
(OMX_VIDEO_PARAM_H263TYPE *)params;
if (h263type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
h263type->nAllowedPictureTypes =
(OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP);
h263type->eProfile = OMX_VIDEO_H263ProfileBaseline;
h263type->eLevel = OMX_VIDEO_H263Level45;
h263type->bPLUSPTYPEAllowed = OMX_FALSE;
h263type->bForceRoundingTypeToZero = OMX_FALSE;
h263type->nPictureHeaderRepetition = 0;
h263type->nGOBHeaderInterval = 0;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoMpeg4:
{
OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type =
(OMX_VIDEO_PARAM_MPEG4TYPE *)params;
if (mpeg4type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mpeg4type->eProfile = OMX_VIDEO_MPEG4ProfileCore;
mpeg4type->eLevel = OMX_VIDEO_MPEG4Level2;
mpeg4type->nAllowedPictureTypes =
(OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP);
mpeg4type->nBFrames = 0;
mpeg4type->nIDCVLCThreshold = 0;
mpeg4type->bACPred = OMX_TRUE;
mpeg4type->nMaxPacketSize = 256;
mpeg4type->nTimeIncRes = 1000;
mpeg4type->nHeaderExtension = 0;
mpeg4type->bReversibleVLC = OMX_FALSE;
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftMPEG4Encoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (!isValidOMXParam(bitRate)) {
return OMX_ErrorBadParameter;
}
if (bitRate->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
bitRate->eControlRate = OMX_Video_ControlRateVariable;
bitRate->nTargetBitrate = mBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoH263:
{
OMX_VIDEO_PARAM_H263TYPE *h263type =
(OMX_VIDEO_PARAM_H263TYPE *)params;
if (!isValidOMXParam(h263type)) {
return OMX_ErrorBadParameter;
}
if (h263type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
h263type->nAllowedPictureTypes =
(OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP);
h263type->eProfile = OMX_VIDEO_H263ProfileBaseline;
h263type->eLevel = OMX_VIDEO_H263Level45;
h263type->bPLUSPTYPEAllowed = OMX_FALSE;
h263type->bForceRoundingTypeToZero = OMX_FALSE;
h263type->nPictureHeaderRepetition = 0;
h263type->nGOBHeaderInterval = 0;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoMpeg4:
{
OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type =
(OMX_VIDEO_PARAM_MPEG4TYPE *)params;
if (!isValidOMXParam(mpeg4type)) {
return OMX_ErrorBadParameter;
}
if (mpeg4type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mpeg4type->eProfile = OMX_VIDEO_MPEG4ProfileCore;
mpeg4type->eLevel = OMX_VIDEO_MPEG4Level2;
mpeg4type->nAllowedPictureTypes =
(OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP);
mpeg4type->nBFrames = 0;
mpeg4type->nIDCVLCThreshold = 0;
mpeg4type->bACPred = OMX_TRUE;
mpeg4type->nMaxPacketSize = 256;
mpeg4type->nTimeIncRes = 1000;
mpeg4type->nHeaderExtension = 0;
mpeg4type->bReversibleVLC = OMX_FALSE;
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalGetParameter(index, params);
}
}
| 174,209
|
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::GetLast() const
{
if (m_cue_points == NULL)
return NULL;
if (m_count <= 0)
return NULL;
#if 0
LoadCuePoint(); //init cues
const size_t count = m_count + m_preload_count;
if (count == 0) //weird
return NULL;
const size_t index = count - 1;
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[index];
assert(pCP);
pCP->Load(m_pSegment->m_pReader);
assert(pCP->GetTimeCode() >= 0);
#else
const long index = m_count - 1;
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[index];
assert(pCP);
assert(pCP->GetTimeCode() >= 0);
#endif
return pCP;
}
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::GetLast() const
if (m_count <= 0)
return NULL;
#if 0
LoadCuePoint(); //init cues
const size_t count = m_count + m_preload_count;
if (count == 0) //weird
return NULL;
const size_t index = count - 1;
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[index];
assert(pCP);
pCP->Load(m_pSegment->m_pReader);
assert(pCP->GetTimeCode() >= 0);
#else
const long index = m_count - 1;
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[index];
assert(pCP);
assert(pCP->GetTimeCode() >= 0);
#endif
return pCP;
}
| 174,339
|
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: gsicc_open_search(const char* pname, int namelen, gs_memory_t *mem_gc,
const char* dirname, int dirlen, stream**strp)
{
char *buffer;
stream* str;
/* Check if we need to prepend the file name */
if ( dirname != NULL) {
/* If this fails, we will still try the file by itself and with
%rom% since someone may have left a space some of the spaces
as our defaults, even if they defined the directory to use.
This will occur only after searching the defined directory.
A warning is noted. */
buffer = (char *) gs_alloc_bytes(mem_gc, namelen + dirlen + 1,
"gsicc_open_search");
if (buffer == NULL)
return_error(gs_error_VMerror);
strcpy(buffer, dirname);
strcat(buffer, pname);
/* Just to make sure we were null terminated */
buffer[namelen + dirlen] = '\0';
str = sfopen(buffer, "r", mem_gc);
gs_free_object(mem_gc, buffer, "gsicc_open_search");
if (str != NULL) {
*strp = str;
return 0;
}
}
/* First just try it like it is */
str = sfopen(pname, "r", mem_gc);
if (str != NULL) {
*strp = str;
return 0;
}
/* If that fails, try %rom% */ /* FIXME: Not sure this is needed or correct */
strlen(DEFAULT_DIR_ICC),"gsicc_open_search");
if (buffer == NULL)
return_error(gs_error_VMerror);
strcpy(buffer, DEFAULT_DIR_ICC);
strcat(buffer, pname);
/* Just to make sure we were null terminated */
buffer[namelen + strlen(DEFAULT_DIR_ICC)] = '\0';
str = sfopen(buffer, "r", mem_gc);
gs_free_object(mem_gc, buffer, "gsicc_open_search");
if (str == NULL) {
gs_warn1("Could not find %s ",pname);
}
*strp = str;
return 0;
}
Commit Message:
CWE ID: CWE-20
|
gsicc_open_search(const char* pname, int namelen, gs_memory_t *mem_gc,
const char* dirname, int dirlen, stream**strp)
{
char *buffer;
stream* str;
/* Check if we need to prepend the file name */
if ( dirname != NULL) {
/* If this fails, we will still try the file by itself and with
%rom% since someone may have left a space some of the spaces
as our defaults, even if they defined the directory to use.
This will occur only after searching the defined directory.
A warning is noted. */
buffer = (char *) gs_alloc_bytes(mem_gc, namelen + dirlen + 1,
"gsicc_open_search");
if (buffer == NULL)
return_error(gs_error_VMerror);
strcpy(buffer, dirname);
strcat(buffer, pname);
/* Just to make sure we were null terminated */
buffer[namelen + dirlen] = '\0';
str = sfopen(buffer, "r", mem_gc);
gs_free_object(mem_gc, buffer, "gsicc_open_search");
if (str != NULL) {
*strp = str;
return 0;
}
}
/* First just try it like it is */
if (gs_check_file_permission(mem_gc, pname, namelen, "r") >= 0) {
str = sfopen(pname, "r", mem_gc);
if (str != NULL) {
*strp = str;
return 0;
}
}
/* If that fails, try %rom% */ /* FIXME: Not sure this is needed or correct */
strlen(DEFAULT_DIR_ICC),"gsicc_open_search");
if (buffer == NULL)
return_error(gs_error_VMerror);
strcpy(buffer, DEFAULT_DIR_ICC);
strcat(buffer, pname);
/* Just to make sure we were null terminated */
buffer[namelen + strlen(DEFAULT_DIR_ICC)] = '\0';
str = sfopen(buffer, "r", mem_gc);
gs_free_object(mem_gc, buffer, "gsicc_open_search");
if (str == NULL) {
gs_warn1("Could not find %s ",pname);
}
*strp = str;
return 0;
}
| 165,265
|
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 ras_getdatastd(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap,
jas_image_t *image)
{
int pad;
int nz;
int z;
int c;
int y;
int x;
int v;
int i;
jas_matrix_t *data[3];
/* Note: This function does not properly handle images with a colormap. */
/* Avoid compiler warnings about unused parameters. */
cmap = 0;
for (i = 0; i < jas_image_numcmpts(image); ++i) {
data[i] = jas_matrix_create(1, jas_image_width(image));
assert(data[i]);
}
pad = RAS_ROWSIZE(hdr) - (hdr->width * hdr->depth + 7) / 8;
for (y = 0; y < hdr->height; y++) {
nz = 0;
z = 0;
for (x = 0; x < hdr->width; x++) {
while (nz < hdr->depth) {
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
z = (z << 8) | c;
nz += 8;
}
v = (z >> (nz - hdr->depth)) & RAS_ONES(hdr->depth);
z &= RAS_ONES(nz - hdr->depth);
nz -= hdr->depth;
if (jas_image_numcmpts(image) == 3) {
jas_matrix_setv(data[0], x, (RAS_GETRED(v)));
jas_matrix_setv(data[1], x, (RAS_GETGREEN(v)));
jas_matrix_setv(data[2], x, (RAS_GETBLUE(v)));
} else {
jas_matrix_setv(data[0], x, (v));
}
}
if (pad) {
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
}
for (i = 0; i < jas_image_numcmpts(image); ++i) {
if (jas_image_writecmpt(image, i, 0, y, hdr->width, 1,
data[i])) {
return -1;
}
}
}
for (i = 0; i < jas_image_numcmpts(image); ++i) {
jas_matrix_destroy(data[i]);
}
return 0;
}
Commit Message: Fixed a few bugs in the RAS encoder and decoder where errors were tested
with assertions instead of being gracefully handled.
CWE ID:
|
static int ras_getdatastd(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap,
jas_image_t *image)
{
int pad;
int nz;
int z;
int c;
int y;
int x;
int v;
int i;
jas_matrix_t *data[3];
/* Note: This function does not properly handle images with a colormap. */
/* Avoid compiler warnings about unused parameters. */
cmap = 0;
assert(jas_image_numcmpts(image) <= 3);
for (i = 0; i < 3; ++i) {
data[i] = 0;
}
for (i = 0; i < jas_image_numcmpts(image); ++i) {
if (!(data[i] = jas_matrix_create(1, jas_image_width(image)))) {
goto error;
}
}
pad = RAS_ROWSIZE(hdr) - (hdr->width * hdr->depth + 7) / 8;
for (y = 0; y < hdr->height; y++) {
nz = 0;
z = 0;
for (x = 0; x < hdr->width; x++) {
while (nz < hdr->depth) {
if ((c = jas_stream_getc(in)) == EOF) {
goto error;
}
z = (z << 8) | c;
nz += 8;
}
v = (z >> (nz - hdr->depth)) & RAS_ONES(hdr->depth);
z &= RAS_ONES(nz - hdr->depth);
nz -= hdr->depth;
if (jas_image_numcmpts(image) == 3) {
jas_matrix_setv(data[0], x, (RAS_GETRED(v)));
jas_matrix_setv(data[1], x, (RAS_GETGREEN(v)));
jas_matrix_setv(data[2], x, (RAS_GETBLUE(v)));
} else {
jas_matrix_setv(data[0], x, (v));
}
}
if (pad) {
if ((c = jas_stream_getc(in)) == EOF) {
goto error;
}
}
for (i = 0; i < jas_image_numcmpts(image); ++i) {
if (jas_image_writecmpt(image, i, 0, y, hdr->width, 1,
data[i])) {
goto error;
}
}
}
for (i = 0; i < jas_image_numcmpts(image); ++i) {
jas_matrix_destroy(data[i]);
data[i] = 0;
}
return 0;
error:
for (i = 0; i < 3; ++i) {
if (data[i]) {
jas_matrix_destroy(data[i]);
}
}
return -1;
}
| 168,740
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void usb_xhci_exit(PCIDevice *dev)
{
int i;
XHCIState *xhci = XHCI(dev);
trace_usb_xhci_exit();
for (i = 0; i < xhci->numslots; i++) {
xhci_disable_slot(xhci, i + 1);
}
if (xhci->mfwrap_timer) {
timer_del(xhci->mfwrap_timer);
timer_free(xhci->mfwrap_timer);
xhci->mfwrap_timer = NULL;
}
memory_region_del_subregion(&xhci->mem, &xhci->mem_cap);
memory_region_del_subregion(&xhci->mem, &xhci->mem_oper);
memory_region_del_subregion(&xhci->mem, &xhci->mem_runtime);
memory_region_del_subregion(&xhci->mem, &xhci->mem_doorbell);
for (i = 0; i < xhci->numports; i++) {
XHCIPort *port = &xhci->ports[i];
memory_region_del_subregion(&xhci->mem, &port->mem);
}
/* destroy msix memory region */
if (dev->msix_table && dev->msix_pba
&& dev->msix_entry_used) {
memory_region_del_subregion(&xhci->mem, &dev->msix_table_mmio);
memory_region_del_subregion(&xhci->mem, &dev->msix_pba_mmio);
}
usb_bus_release(&xhci->bus);
usb_bus_release(&xhci->bus);
}
Commit Message:
CWE ID: CWE-399
|
static void usb_xhci_exit(PCIDevice *dev)
{
int i;
XHCIState *xhci = XHCI(dev);
trace_usb_xhci_exit();
for (i = 0; i < xhci->numslots; i++) {
xhci_disable_slot(xhci, i + 1);
}
if (xhci->mfwrap_timer) {
timer_del(xhci->mfwrap_timer);
timer_free(xhci->mfwrap_timer);
xhci->mfwrap_timer = NULL;
}
memory_region_del_subregion(&xhci->mem, &xhci->mem_cap);
memory_region_del_subregion(&xhci->mem, &xhci->mem_oper);
memory_region_del_subregion(&xhci->mem, &xhci->mem_runtime);
memory_region_del_subregion(&xhci->mem, &xhci->mem_doorbell);
for (i = 0; i < xhci->numports; i++) {
XHCIPort *port = &xhci->ports[i];
memory_region_del_subregion(&xhci->mem, &port->mem);
}
/* destroy msix memory region */
if (dev->msix_table && dev->msix_pba
&& dev->msix_entry_used) {
msix_uninit(dev, &xhci->mem, &xhci->mem);
}
usb_bus_release(&xhci->bus);
usb_bus_release(&xhci->bus);
}
| 164,926
|
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 OutOfProcessInstance::Init(uint32_t argc,
const char* argn[],
const char* argv[]) {
pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
std::string document_url = document_url_var.is_string() ?
document_url_var.AsString() : std::string();
std::string extension_url = std::string(kChromeExtension);
bool in_extension =
!document_url.compare(0, extension_url.size(), extension_url);
if (in_extension) {
for (uint32_t i = 0; i < argc; ++i) {
if (strcmp(argn[i], "full-frame") == 0) {
full_ = true;
break;
}
}
}
if (full_)
SetPluginToHandleFindRequests();
pp::VarDictionary translated_strings;
translated_strings.Set(kType, kJSSetTranslatedStringsType);
translated_strings.Set(kJSGetPasswordString,
GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
translated_strings.Set(kJSLoadingString,
GetLocalizedString(PP_RESOURCESTRING_PDFLOADING));
translated_strings.Set(kJSLoadFailedString,
GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED));
PostMessage(translated_strings);
text_input_.reset(new pp::TextInput_Dev(this));
const char* stream_url = nullptr;
const char* original_url = nullptr;
const char* headers = nullptr;
bool is_material = false;
for (uint32_t i = 0; i < argc; ++i) {
if (strcmp(argn[i], "src") == 0)
original_url = argv[i];
else if (strcmp(argn[i], "stream-url") == 0)
stream_url = argv[i];
else if (strcmp(argn[i], "headers") == 0)
headers = argv[i];
else if (strcmp(argn[i], "is-material") == 0)
is_material = true;
else if (strcmp(argn[i], "top-toolbar-height") == 0)
base::StringToInt(argv[i], &top_toolbar_height_);
}
if (is_material)
background_color_ = kBackgroundColorMaterial;
else
background_color_ = kBackgroundColor;
if (!original_url)
return false;
if (!stream_url)
stream_url = original_url;
if (IsPrintPreviewUrl(original_url))
return true;
LoadUrl(stream_url);
url_ = original_url;
return engine_->New(original_url, headers);
}
Commit Message: Prevent leaking PDF data cross-origin
BUG=520422
Review URL: https://codereview.chromium.org/1311973002
Cr-Commit-Position: refs/heads/master@{#345267}
CWE ID: CWE-20
|
bool OutOfProcessInstance::Init(uint32_t argc,
const char* argn[],
const char* argv[]) {
// the plugin to be loaded in the extension and print preview to avoid
// exposing sensitive APIs directly to external websites.
pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
if (!document_url_var.is_string())
return false;
std::string document_url = document_url_var.AsString();
std::string extension_url = std::string(kChromeExtension);
std::string print_preview_url = std::string(kChromePrint);
if (!base::StringPiece(document_url).starts_with(kChromeExtension) &&
!base::StringPiece(document_url).starts_with(kChromePrint)) {
return false;
}
// Check if the plugin is full frame. This is passed in from JS.
for (uint32_t i = 0; i < argc; ++i) {
if (strcmp(argn[i], "full-frame") == 0) {
full_ = true;
break;
}
}
if (full_)
SetPluginToHandleFindRequests();
pp::VarDictionary translated_strings;
translated_strings.Set(kType, kJSSetTranslatedStringsType);
translated_strings.Set(kJSGetPasswordString,
GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
translated_strings.Set(kJSLoadingString,
GetLocalizedString(PP_RESOURCESTRING_PDFLOADING));
translated_strings.Set(kJSLoadFailedString,
GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED));
PostMessage(translated_strings);
text_input_.reset(new pp::TextInput_Dev(this));
const char* stream_url = nullptr;
const char* original_url = nullptr;
const char* headers = nullptr;
bool is_material = false;
for (uint32_t i = 0; i < argc; ++i) {
if (strcmp(argn[i], "src") == 0)
original_url = argv[i];
else if (strcmp(argn[i], "stream-url") == 0)
stream_url = argv[i];
else if (strcmp(argn[i], "headers") == 0)
headers = argv[i];
else if (strcmp(argn[i], "is-material") == 0)
is_material = true;
else if (strcmp(argn[i], "top-toolbar-height") == 0)
base::StringToInt(argv[i], &top_toolbar_height_);
}
if (is_material)
background_color_ = kBackgroundColorMaterial;
else
background_color_ = kBackgroundColor;
if (!original_url)
return false;
if (!stream_url)
stream_url = original_url;
if (IsPrintPreviewUrl(original_url))
return true;
LoadUrl(stream_url);
url_ = original_url;
return engine_->New(original_url, headers);
}
| 172,042
|
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_CreateFalse( void )
{
cJSON *item = cJSON_New_Item();
if ( item )
item->type = cJSON_False;
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 <bmah@es.net>
CWE ID: CWE-119
|
cJSON *cJSON_CreateFalse( void )
| 167,271
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE SoftAVC::internalGetParameter(OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *)params;
if (bitRate->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
bitRate->eControlRate = OMX_Video_ControlRateVariable;
bitRate->nTargetBitrate = mBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoAvc:
{
OMX_VIDEO_PARAM_AVCTYPE *avcParams = (OMX_VIDEO_PARAM_AVCTYPE *)params;
if (avcParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
OMX_VIDEO_AVCLEVELTYPE omxLevel = OMX_VIDEO_AVCLevel41;
if (OMX_ErrorNone
!= ConvertAvcSpecLevelToOmxAvcLevel(mAVCEncLevel, &omxLevel)) {
return OMX_ErrorUndefined;
}
avcParams->eProfile = OMX_VIDEO_AVCProfileBaseline;
avcParams->eLevel = omxLevel;
avcParams->nRefFrames = 1;
avcParams->bUseHadamard = OMX_TRUE;
avcParams->nAllowedPictureTypes = (OMX_VIDEO_PictureTypeI
| OMX_VIDEO_PictureTypeP | OMX_VIDEO_PictureTypeB);
avcParams->nRefIdx10ActiveMinus1 = 0;
avcParams->nRefIdx11ActiveMinus1 = 0;
avcParams->bWeightedPPrediction = OMX_FALSE;
avcParams->bconstIpred = OMX_FALSE;
avcParams->bDirect8x8Inference = OMX_FALSE;
avcParams->bDirectSpatialTemporal = OMX_FALSE;
avcParams->nCabacInitIdc = 0;
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
|
OMX_ERRORTYPE SoftAVC::internalGetParameter(OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *)params;
if (!isValidOMXParam(bitRate)) {
return OMX_ErrorBadParameter;
}
if (bitRate->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
bitRate->eControlRate = OMX_Video_ControlRateVariable;
bitRate->nTargetBitrate = mBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoAvc:
{
OMX_VIDEO_PARAM_AVCTYPE *avcParams = (OMX_VIDEO_PARAM_AVCTYPE *)params;
if (!isValidOMXParam(avcParams)) {
return OMX_ErrorBadParameter;
}
if (avcParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
OMX_VIDEO_AVCLEVELTYPE omxLevel = OMX_VIDEO_AVCLevel41;
if (OMX_ErrorNone
!= ConvertAvcSpecLevelToOmxAvcLevel(mAVCEncLevel, &omxLevel)) {
return OMX_ErrorUndefined;
}
avcParams->eProfile = OMX_VIDEO_AVCProfileBaseline;
avcParams->eLevel = omxLevel;
avcParams->nRefFrames = 1;
avcParams->bUseHadamard = OMX_TRUE;
avcParams->nAllowedPictureTypes = (OMX_VIDEO_PictureTypeI
| OMX_VIDEO_PictureTypeP | OMX_VIDEO_PictureTypeB);
avcParams->nRefIdx10ActiveMinus1 = 0;
avcParams->nRefIdx11ActiveMinus1 = 0;
avcParams->bWeightedPPrediction = OMX_FALSE;
avcParams->bconstIpred = OMX_FALSE;
avcParams->bDirect8x8Inference = OMX_FALSE;
avcParams->bDirectSpatialTemporal = OMX_FALSE;
avcParams->nCabacInitIdc = 0;
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalGetParameter(index, params);
}
}
| 174,200
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void NetworkThrottleManagerImpl::SetTickClockForTesting(
std::unique_ptr<base::TickClock> tick_clock) {
tick_clock_ = std::move(tick_clock);
DCHECK(!outstanding_recomputation_timer_->IsRunning());
outstanding_recomputation_timer_ = base::MakeUnique<base::Timer>(
false /* retain_user_task */, false /* is_repeating */,
tick_clock_.get());
}
Commit Message: Replace base::MakeUnique with std::make_unique in net/.
base/memory/ptr_util.h includes will be cleaned up later.
Bug: 755727
Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434
Reviewed-on: https://chromium-review.googlesource.com/627300
Commit-Queue: Jeremy Roman <jbroman@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Reviewed-by: Bence Béky <bnc@chromium.org>
Cr-Commit-Position: refs/heads/master@{#498123}
CWE ID: CWE-311
|
void NetworkThrottleManagerImpl::SetTickClockForTesting(
std::unique_ptr<base::TickClock> tick_clock) {
tick_clock_ = std::move(tick_clock);
DCHECK(!outstanding_recomputation_timer_->IsRunning());
outstanding_recomputation_timer_ = std::make_unique<base::Timer>(
false /* retain_user_task */, false /* is_repeating */,
tick_clock_.get());
}
| 173,267
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long long Segment::GetDuration() const
{
assert(m_pInfo);
return m_pInfo->GetDuration();
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long long Segment::GetDuration() const
| 174,306
|
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 ParamTraits<LOGFONT>::Read(const Message* m, PickleIterator* iter,
param_type* r) {
const char *data;
int data_size = 0;
bool result = m->ReadData(iter, &data, &data_size);
if (result && data_size == sizeof(LOGFONT)) {
memcpy(r, data, sizeof(LOGFONT));
} else {
result = false;
NOTREACHED();
}
return result;
}
Commit Message: Verify lfFaceName is NUL terminated in IPC deserializer.
BUG=162066
Review URL: https://chromiumcodereview.appspot.com/11416115
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@168937 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
bool ParamTraits<LOGFONT>::Read(const Message* m, PickleIterator* iter,
param_type* r) {
const char *data;
int data_size = 0;
if (m->ReadData(iter, &data, &data_size) && data_size == sizeof(LOGFONT)) {
const LOGFONT *font = reinterpret_cast<LOGFONT*>(const_cast<char*>(data));
if (_tcsnlen(font->lfFaceName, LF_FACESIZE) < LF_FACESIZE) {
memcpy(r, data, sizeof(LOGFONT));
return true;
}
}
NOTREACHED();
return false;
}
| 171,588
|
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 main(int argc, char **argv) {
FILE *infile = NULL;
vpx_codec_ctx_t codec = {0};
vpx_codec_enc_cfg_t cfg = {0};
int frame_count = 0;
vpx_image_t raw;
vpx_codec_err_t res;
VpxVideoInfo info = {0};
VpxVideoWriter *writer = NULL;
const VpxInterface *encoder = NULL;
int update_frame_num = 0;
const int fps = 30; // TODO(dkovalev) add command line argument
const int bitrate = 200; // kbit/s TODO(dkovalev) add command line argument
exec_name = argv[0];
if (argc != 6)
die("Invalid number of arguments");
encoder = get_vpx_encoder_by_name("vp8");
if (!encoder)
die("Unsupported codec.");
update_frame_num = atoi(argv[5]);
if (!update_frame_num)
die("Couldn't parse frame number '%s'\n", argv[5]);
info.codec_fourcc = encoder->fourcc;
info.frame_width = strtol(argv[1], NULL, 0);
info.frame_height = strtol(argv[2], NULL, 0);
info.time_base.numerator = 1;
info.time_base.denominator = fps;
if (info.frame_width <= 0 ||
info.frame_height <= 0 ||
(info.frame_width % 2) != 0 ||
(info.frame_height % 2) != 0) {
die("Invalid frame size: %dx%d", info.frame_width, info.frame_height);
}
if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, info.frame_width,
info.frame_height, 1)) {
die("Failed to allocate image.");
}
printf("Using %s\n", vpx_codec_iface_name(encoder->interface()));
res = vpx_codec_enc_config_default(encoder->interface(), &cfg, 0);
if (res)
die_codec(&codec, "Failed to get default codec config.");
cfg.g_w = info.frame_width;
cfg.g_h = info.frame_height;
cfg.g_timebase.num = info.time_base.numerator;
cfg.g_timebase.den = info.time_base.denominator;
cfg.rc_target_bitrate = bitrate;
writer = vpx_video_writer_open(argv[4], kContainerIVF, &info);
if (!writer)
die("Failed to open %s for writing.", argv[4]);
if (!(infile = fopen(argv[3], "rb")))
die("Failed to open %s for reading.", argv[3]);
if (vpx_codec_enc_init(&codec, encoder->interface(), &cfg, 0))
die_codec(&codec, "Failed to initialize encoder");
while (vpx_img_read(&raw, infile)) {
if (frame_count + 1 == update_frame_num) {
vpx_ref_frame_t ref;
ref.frame_type = VP8_LAST_FRAME;
ref.img = raw;
if (vpx_codec_control(&codec, VP8_SET_REFERENCE, &ref))
die_codec(&codec, "Failed to set reference frame");
}
encode_frame(&codec, &raw, frame_count++, writer);
}
encode_frame(&codec, NULL, -1, writer);
printf("\n");
fclose(infile);
printf("Processed %d frames.\n", frame_count);
vpx_img_free(&raw);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec.");
vpx_video_writer_close(writer);
return EXIT_SUCCESS;
}
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
|
int main(int argc, char **argv) {
FILE *infile = NULL;
vpx_codec_ctx_t codec = {0};
vpx_codec_enc_cfg_t cfg = {0};
int frame_count = 0;
vpx_image_t raw;
vpx_codec_err_t res;
VpxVideoInfo info = {0};
VpxVideoWriter *writer = NULL;
const VpxInterface *encoder = NULL;
int update_frame_num = 0;
const int fps = 30; // TODO(dkovalev) add command line argument
const int bitrate = 200; // kbit/s TODO(dkovalev) add command line argument
exec_name = argv[0];
if (argc != 6)
die("Invalid number of arguments");
encoder = get_vpx_encoder_by_name("vp8");
if (!encoder)
die("Unsupported codec.");
update_frame_num = atoi(argv[5]);
if (!update_frame_num)
die("Couldn't parse frame number '%s'\n", argv[5]);
info.codec_fourcc = encoder->fourcc;
info.frame_width = strtol(argv[1], NULL, 0);
info.frame_height = strtol(argv[2], NULL, 0);
info.time_base.numerator = 1;
info.time_base.denominator = fps;
if (info.frame_width <= 0 ||
info.frame_height <= 0 ||
(info.frame_width % 2) != 0 ||
(info.frame_height % 2) != 0) {
die("Invalid frame size: %dx%d", info.frame_width, info.frame_height);
}
if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, info.frame_width,
info.frame_height, 1)) {
die("Failed to allocate image.");
}
printf("Using %s\n", vpx_codec_iface_name(encoder->codec_interface()));
res = vpx_codec_enc_config_default(encoder->codec_interface(), &cfg, 0);
if (res)
die_codec(&codec, "Failed to get default codec config.");
cfg.g_w = info.frame_width;
cfg.g_h = info.frame_height;
cfg.g_timebase.num = info.time_base.numerator;
cfg.g_timebase.den = info.time_base.denominator;
cfg.rc_target_bitrate = bitrate;
writer = vpx_video_writer_open(argv[4], kContainerIVF, &info);
if (!writer)
die("Failed to open %s for writing.", argv[4]);
if (!(infile = fopen(argv[3], "rb")))
die("Failed to open %s for reading.", argv[3]);
if (vpx_codec_enc_init(&codec, encoder->codec_interface(), &cfg, 0))
die_codec(&codec, "Failed to initialize encoder");
// Encode frames.
while (vpx_img_read(&raw, infile)) {
if (frame_count + 1 == update_frame_num) {
vpx_ref_frame_t ref;
ref.frame_type = VP8_LAST_FRAME;
ref.img = raw;
if (vpx_codec_control(&codec, VP8_SET_REFERENCE, &ref))
die_codec(&codec, "Failed to set reference frame");
}
encode_frame(&codec, &raw, frame_count++, writer);
}
// Flush encoder.
while (encode_frame(&codec, NULL, -1, writer)) {}
printf("\n");
fclose(infile);
printf("Processed %d frames.\n", frame_count);
vpx_img_free(&raw);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec.");
vpx_video_writer_close(writer);
return EXIT_SUCCESS;
}
| 174,498
|
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 CameraDeviceClient::dump(int fd, const Vector<String16>& args) {
String8 result;
result.appendFormat("CameraDeviceClient[%d] (%p) PID: %d, dump:\n",
mCameraId,
getRemoteCallback()->asBinder().get(),
mClientPid);
result.append(" State: ");
mFrameProcessor->dump(fd, args);
return dumpDevice(fd, args);
}
Commit Message: Camera: Disallow dumping clients directly
Camera service dumps should only be initiated through
ICameraService::dump.
Bug: 26265403
Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803
CWE ID: CWE-264
|
status_t CameraDeviceClient::dump(int fd, const Vector<String16>& args) {
return BasicClient::dump(fd, args);
}
status_t CameraDeviceClient::dumpClient(int fd, const Vector<String16>& args) {
String8 result;
result.appendFormat("CameraDeviceClient[%d] (%p) PID: %d, dump:\n",
mCameraId,
getRemoteCallback()->asBinder().get(),
mClientPid);
result.append(" State: ");
mFrameProcessor->dump(fd, args);
return dumpDevice(fd, args);
}
| 173,939
|
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 PKCS7_ctrl(PKCS7 *p7, int cmd, long larg, char *parg)
{
int nid;
long ret;
nid = OBJ_obj2nid(p7->type);
switch (cmd) {
case PKCS7_OP_SET_DETACHED_SIGNATURE:
if (nid == NID_pkcs7_signed) {
ret = p7->detached = (int)larg;
ASN1_OCTET_STRING *os;
os = p7->d.sign->contents->d.data;
ASN1_OCTET_STRING_free(os);
p7->d.sign->contents->d.data = NULL;
}
} else {
PKCS7err(PKCS7_F_PKCS7_CTRL,
PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE);
ret = 0;
}
break;
case PKCS7_OP_GET_DETACHED_SIGNATURE:
if (nid == NID_pkcs7_signed) {
if (!p7->d.sign || !p7->d.sign->contents->d.ptr)
ret = 1;
else
ret = 0;
p7->detached = ret;
} else {
PKCS7err(PKCS7_F_PKCS7_CTRL,
PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE);
ret = 0;
}
break;
default:
PKCS7err(PKCS7_F_PKCS7_CTRL, PKCS7_R_UNKNOWN_OPERATION);
ret = 0;
}
Commit Message:
CWE ID:
|
long PKCS7_ctrl(PKCS7 *p7, int cmd, long larg, char *parg)
{
int nid;
long ret;
nid = OBJ_obj2nid(p7->type);
switch (cmd) {
/* NOTE(emilia): does not support detached digested data. */
case PKCS7_OP_SET_DETACHED_SIGNATURE:
if (nid == NID_pkcs7_signed) {
ret = p7->detached = (int)larg;
ASN1_OCTET_STRING *os;
os = p7->d.sign->contents->d.data;
ASN1_OCTET_STRING_free(os);
p7->d.sign->contents->d.data = NULL;
}
} else {
PKCS7err(PKCS7_F_PKCS7_CTRL,
PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE);
ret = 0;
}
break;
case PKCS7_OP_GET_DETACHED_SIGNATURE:
if (nid == NID_pkcs7_signed) {
if (!p7->d.sign || !p7->d.sign->contents->d.ptr)
ret = 1;
else
ret = 0;
p7->detached = ret;
} else {
PKCS7err(PKCS7_F_PKCS7_CTRL,
PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE);
ret = 0;
}
break;
default:
PKCS7err(PKCS7_F_PKCS7_CTRL, PKCS7_R_UNKNOWN_OPERATION);
ret = 0;
}
| 164,808
|
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: valid_length(uint8_t option, int dl, int *type)
{
const struct dhcp_opt *opt;
ssize_t sz;
if (dl == 0)
return -1;
for (opt = dhcp_opts; opt->option; opt++) {
if (opt->option != option)
continue;
if (type)
*type = opt->type;
if (opt->type == 0 ||
opt->type & (STRING | RFC3442 | RFC5969))
return 0;
sz = 0;
if (opt->type & (UINT32 | IPV4))
sz = sizeof(uint32_t);
if (opt->type & UINT16)
sz = sizeof(uint16_t);
if (opt->type & UINT8)
sz = sizeof(uint8_t);
if (opt->type & (IPV4 | ARRAY))
return dl % sz;
return (dl == sz ? 0 : -1);
}
/* unknown option, so let it pass */
return 0;
}
Commit Message: Improve length checks in DHCP Options parsing of dhcpcd.
Bug: 26461634
Change-Id: Ic4c2eb381a6819e181afc8ab13891f3fc58b7deb
CWE ID: CWE-119
|
valid_length(uint8_t option, int dl, int *type)
{
const struct dhcp_opt *opt;
ssize_t sz;
if (dl == 0)
return -1;
for (opt = dhcp_opts; opt->option; opt++) {
if (opt->option != option)
continue;
if (type)
*type = opt->type;
/* The size of RFC3442 and RFC5969 options is checked at a later
* stage in the code */
if (opt->type == 0 ||
opt->type & (STRING | RFC3442 | RFC5969))
return 0;
/* The code does not use SINT16 / SINT32 together with ARRAY.
* It is however far easier to reason about the code if all
* possible array elements are included, and also does not code
* any additional CPU resources. sizeof(uintXX_t) ==
* sizeof(intXX_t) can be assumed. */
sz = 0;
if (opt->type & (UINT32 | SINT32 | IPV4))
sz = sizeof(uint32_t);
else if (opt->type & (UINT16 | SINT16))
sz = sizeof(uint16_t);
else if (opt->type & UINT8)
sz = sizeof(uint8_t);
if (opt->type & ARRAY) {
/* The result of modulo zero is undefined. There are no
* options defined in this file that do not match one of
* the if-clauses above, so the following is not really
* necessary. However, to avoid confusion and unexpected
* behavior if the defined options are ever extended,
* returning false here seems sensible. */
if (!sz) return -1;
return (dl % sz == 0) ? 0 : -1;
}
return (sz == dl) ? 0 : -1;
}
/* unknown option, so let it pass */
return 0;
}
| 173,900
|
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: pimv1_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
register const u_char *ep;
register u_char type;
ep = (const u_char *)ndo->ndo_snapend;
if (bp >= ep)
return;
ND_TCHECK(bp[1]);
type = bp[1];
ND_PRINT((ndo, " %s", tok2str(pimv1_type_str, "[type %u]", type)));
switch (type) {
case PIMV1_TYPE_QUERY:
if (ND_TTEST(bp[8])) {
switch (bp[8] >> 4) {
case 0:
ND_PRINT((ndo, " Dense-mode"));
break;
case 1:
ND_PRINT((ndo, " Sparse-mode"));
break;
case 2:
ND_PRINT((ndo, " Sparse-Dense-mode"));
break;
default:
ND_PRINT((ndo, " mode-%d", bp[8] >> 4));
break;
}
}
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[10],2);
ND_PRINT((ndo, " (Hold-time "));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[10]));
ND_PRINT((ndo, ")"));
}
break;
case PIMV1_TYPE_REGISTER:
ND_TCHECK2(bp[8], 20); /* ip header */
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[20]),
ipaddr_string(ndo, &bp[24])));
break;
case PIMV1_TYPE_REGISTER_STOP:
ND_TCHECK2(bp[12], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[8]),
ipaddr_string(ndo, &bp[12])));
break;
case PIMV1_TYPE_RP_REACHABILITY:
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[22], 2);
ND_PRINT((ndo, " group %s", ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_PRINT((ndo, " RP %s hold ", ipaddr_string(ndo, &bp[16])));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[22]));
}
break;
case PIMV1_TYPE_ASSERT:
ND_TCHECK2(bp[16], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[16]),
ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_TCHECK2(bp[24], 4);
ND_PRINT((ndo, " %s pref %d metric %d",
(bp[20] & 0x80) ? "RP-tree" : "SPT",
EXTRACT_32BITS(&bp[20]) & 0x7fffffff,
EXTRACT_32BITS(&bp[24])));
break;
case PIMV1_TYPE_JOIN_PRUNE:
case PIMV1_TYPE_GRAFT:
case PIMV1_TYPE_GRAFT_ACK:
if (ndo->ndo_vflag)
pimv1_join_prune_print(ndo, &bp[8], len - 8);
break;
}
ND_TCHECK(bp[4]);
if ((bp[4] >> 4) != 1)
ND_PRINT((ndo, " [v%d]", bp[4] >> 4));
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
return;
}
Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks.
Use ND_TCHECK macros to do bounds checking, and add length checks before
the bounds checks.
Add a bounds check that the review process found was missing.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
Update one test output file to reflect the changes.
CWE ID: CWE-125
|
pimv1_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
register u_char type;
ND_TCHECK(bp[1]);
type = bp[1];
ND_PRINT((ndo, " %s", tok2str(pimv1_type_str, "[type %u]", type)));
switch (type) {
case PIMV1_TYPE_QUERY:
if (ND_TTEST(bp[8])) {
switch (bp[8] >> 4) {
case 0:
ND_PRINT((ndo, " Dense-mode"));
break;
case 1:
ND_PRINT((ndo, " Sparse-mode"));
break;
case 2:
ND_PRINT((ndo, " Sparse-Dense-mode"));
break;
default:
ND_PRINT((ndo, " mode-%d", bp[8] >> 4));
break;
}
}
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[10],2);
ND_PRINT((ndo, " (Hold-time "));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[10]));
ND_PRINT((ndo, ")"));
}
break;
case PIMV1_TYPE_REGISTER:
ND_TCHECK2(bp[8], 20); /* ip header */
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[20]),
ipaddr_string(ndo, &bp[24])));
break;
case PIMV1_TYPE_REGISTER_STOP:
ND_TCHECK2(bp[12], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[8]),
ipaddr_string(ndo, &bp[12])));
break;
case PIMV1_TYPE_RP_REACHABILITY:
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[22], 2);
ND_PRINT((ndo, " group %s", ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_PRINT((ndo, " RP %s hold ", ipaddr_string(ndo, &bp[16])));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[22]));
}
break;
case PIMV1_TYPE_ASSERT:
ND_TCHECK2(bp[16], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[16]),
ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_TCHECK2(bp[24], 4);
ND_PRINT((ndo, " %s pref %d metric %d",
(bp[20] & 0x80) ? "RP-tree" : "SPT",
EXTRACT_32BITS(&bp[20]) & 0x7fffffff,
EXTRACT_32BITS(&bp[24])));
break;
case PIMV1_TYPE_JOIN_PRUNE:
case PIMV1_TYPE_GRAFT:
case PIMV1_TYPE_GRAFT_ACK:
if (ndo->ndo_vflag) {
if (len < 8)
goto trunc;
pimv1_join_prune_print(ndo, &bp[8], len - 8);
}
break;
}
ND_TCHECK(bp[4]);
if ((bp[4] >> 4) != 1)
ND_PRINT((ndo, " [v%d]", bp[4] >> 4));
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
return;
}
| 167,856
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_FUNCTION(locale_get_all_variants)
{
const char* loc_name = NULL;
int loc_name_len = 0;
int result = 0;
char* token = NULL;
char* variant = NULL;
char* saved_ptr = NULL;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s",
&loc_name, &loc_name_len ) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_parse: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
if(loc_name_len == 0) {
loc_name = intl_locale_get_default(TSRMLS_C);
}
array_init( return_value );
/* If the locale is grandfathered, stop, no variants */
if( findOffset( LOC_GRANDFATHERED , loc_name ) >= 0 ){
/* ("Grandfathered Tag. No variants."); */
}
else {
/* Call ICU variant */
variant = get_icu_value_internal( loc_name , LOC_VARIANT_TAG , &result ,0);
if( result > 0 && variant){
/* Tokenize on the "_" or "-" */
token = php_strtok_r( variant , DELIMITER , &saved_ptr);
add_next_index_stringl( return_value, token , strlen(token) ,TRUE );
/* tokenize on the "_" or "-" and stop at singleton if any */
while( (token = php_strtok_r(NULL , DELIMITER, &saved_ptr)) && (strlen(token)>1) ){
add_next_index_stringl( return_value, token , strlen(token) ,TRUE );
}
}
if( variant ){
efree( variant );
}
}
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125
|
PHP_FUNCTION(locale_get_all_variants)
{
const char* loc_name = NULL;
int loc_name_len = 0;
int result = 0;
char* token = NULL;
char* variant = NULL;
char* saved_ptr = NULL;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s",
&loc_name, &loc_name_len ) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_parse: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
if(loc_name_len == 0) {
loc_name = intl_locale_get_default(TSRMLS_C);
}
array_init( return_value );
/* If the locale is grandfathered, stop, no variants */
if( findOffset( LOC_GRANDFATHERED , loc_name ) >= 0 ){
/* ("Grandfathered Tag. No variants."); */
}
else {
/* Call ICU variant */
variant = get_icu_value_internal( loc_name , LOC_VARIANT_TAG , &result ,0);
if( result > 0 && variant){
/* Tokenize on the "_" or "-" */
token = php_strtok_r( variant , DELIMITER , &saved_ptr);
add_next_index_stringl( return_value, token , strlen(token) ,TRUE );
/* tokenize on the "_" or "-" and stop at singleton if any */
while( (token = php_strtok_r(NULL , DELIMITER, &saved_ptr)) && (strlen(token)>1) ){
add_next_index_stringl( return_value, token , strlen(token) ,TRUE );
}
}
if( variant ){
efree( variant );
}
}
}
| 167,192
|
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 ChromeRenderProcessObserver::OnControlMessageReceived(
const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ChromeRenderProcessObserver, message)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetIsIncognitoProcess,
OnSetIsIncognitoProcess)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetCacheCapacities, OnSetCacheCapacities)
IPC_MESSAGE_HANDLER(ChromeViewMsg_ClearCache, OnClearCache)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetFieldTrialGroup, OnSetFieldTrialGroup)
#if defined(USE_TCMALLOC)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetTcmallocHeapProfiling,
OnSetTcmallocHeapProfiling)
IPC_MESSAGE_HANDLER(ChromeViewMsg_WriteTcmallocHeapProfile,
OnWriteTcmallocHeapProfile)
#endif
IPC_MESSAGE_HANDLER(ChromeViewMsg_GetV8HeapStats, OnGetV8HeapStats)
IPC_MESSAGE_HANDLER(ChromeViewMsg_GetCacheResourceStats,
OnGetCacheResourceStats)
IPC_MESSAGE_HANDLER(ChromeViewMsg_PurgeMemory, OnPurgeMemory)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetContentSettingRules,
OnSetContentSettingRules)
IPC_MESSAGE_HANDLER(ChromeViewMsg_ToggleWebKitSharedTimer,
OnToggleWebKitSharedTimer)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
Commit Message: Disable tcmalloc profile files.
BUG=154983
TBR=darin@chromium.org
NOTRY=true
Review URL: https://chromiumcodereview.appspot.com/11087041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool ChromeRenderProcessObserver::OnControlMessageReceived(
const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ChromeRenderProcessObserver, message)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetIsIncognitoProcess,
OnSetIsIncognitoProcess)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetCacheCapacities, OnSetCacheCapacities)
IPC_MESSAGE_HANDLER(ChromeViewMsg_ClearCache, OnClearCache)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetFieldTrialGroup, OnSetFieldTrialGroup)
IPC_MESSAGE_HANDLER(ChromeViewMsg_GetV8HeapStats, OnGetV8HeapStats)
IPC_MESSAGE_HANDLER(ChromeViewMsg_GetCacheResourceStats,
OnGetCacheResourceStats)
IPC_MESSAGE_HANDLER(ChromeViewMsg_PurgeMemory, OnPurgeMemory)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetContentSettingRules,
OnSetContentSettingRules)
IPC_MESSAGE_HANDLER(ChromeViewMsg_ToggleWebKitSharedTimer,
OnToggleWebKitSharedTimer)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
| 170,665
|
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 balloon_process(struct work_struct *work)
{
enum bp_state state = BP_DONE;
long credit;
do {
mutex_lock(&balloon_mutex);
credit = current_credit();
if (credit > 0) {
if (balloon_is_inflated())
state = increase_reservation(credit);
else
state = reserve_additional_memory();
}
if (credit < 0)
state = decrease_reservation(-credit, GFP_BALLOON);
state = update_schedule(state);
mutex_unlock(&balloon_mutex);
cond_resched();
} while (credit && state == BP_DONE);
/* Schedule more work if there is some still to be done. */
if (state == BP_EAGAIN)
schedule_delayed_work(&balloon_worker, balloon_stats.schedule_delay * HZ);
}
Commit Message: xen: let alloc_xenballooned_pages() fail if not enough memory free
commit a1078e821b605813b63bf6bca414a85f804d5c66 upstream.
Instead of trying to allocate pages with GFP_USER in
add_ballooned_pages() check the available free memory via
si_mem_available(). GFP_USER is far less limiting memory exhaustion
than the test via si_mem_available().
This will avoid dom0 running out of memory due to excessive foreign
page mappings especially on ARM and on x86 in PVH mode, as those don't
have a pre-ballooned area which can be used for foreign mappings.
As the normal ballooning suffers from the same problem don't balloon
down more than si_mem_available() pages in one iteration. At the same
time limit the default maximum number of retries.
This is part of XSA-300.
Signed-off-by: Juergen Gross <jgross@suse.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
CWE ID: CWE-400
|
static void balloon_process(struct work_struct *work)
{
enum bp_state state = BP_DONE;
long credit;
do {
mutex_lock(&balloon_mutex);
credit = current_credit();
if (credit > 0) {
if (balloon_is_inflated())
state = increase_reservation(credit);
else
state = reserve_additional_memory();
}
if (credit < 0) {
long n_pages;
n_pages = min(-credit, si_mem_available());
state = decrease_reservation(n_pages, GFP_BALLOON);
if (state == BP_DONE && n_pages != -credit &&
n_pages < totalreserve_pages)
state = BP_EAGAIN;
}
state = update_schedule(state);
mutex_unlock(&balloon_mutex);
cond_resched();
} while (credit && state == BP_DONE);
/* Schedule more work if there is some still to be done. */
if (state == BP_EAGAIN)
schedule_delayed_work(&balloon_worker, balloon_stats.schedule_delay * HZ);
}
| 169,494
|
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 rtnl_fill_link_ifmap(struct sk_buff *skb, struct net_device *dev)
{
struct rtnl_link_ifmap map = {
.mem_start = dev->mem_start,
.mem_end = dev->mem_end,
.base_addr = dev->base_addr,
.irq = dev->irq,
.dma = dev->dma,
.port = dev->if_port,
};
if (nla_put(skb, IFLA_MAP, sizeof(map), &map))
return -EMSGSIZE;
return 0;
}
Commit Message: net: fix infoleak in rtnetlink
The stack object “map” has a total size of 32 bytes. Its last 4
bytes are padding generated by compiler. These padding bytes are
not initialized and sent out via “nla_put”.
Signed-off-by: Kangjie Lu <kjlu@gatech.edu>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-200
|
static int rtnl_fill_link_ifmap(struct sk_buff *skb, struct net_device *dev)
{
struct rtnl_link_ifmap map;
memset(&map, 0, sizeof(map));
map.mem_start = dev->mem_start;
map.mem_end = dev->mem_end;
map.base_addr = dev->base_addr;
map.irq = dev->irq;
map.dma = dev->dma;
map.port = dev->if_port;
if (nla_put(skb, IFLA_MAP, sizeof(map), &map))
return -EMSGSIZE;
return 0;
}
| 167,257
|
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 MockDownloadController::CreateGETDownload(
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
bool must_download, const DownloadInfo& info) {
}
Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack
The only exception is OMA DRM download.
And it only applies to context menu download interception.
Clean up the remaining unused code now.
BUG=647755
Review-Url: https://codereview.chromium.org/2371773003
Cr-Commit-Position: refs/heads/master@{#421332}
CWE ID: CWE-254
|
void MockDownloadController::CreateGETDownload(
| 171,885
|
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 *ExtractPostscript(Image *image,const ImageInfo *image_info,
MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)
{
char
postscript_file[MaxTextExtent];
const MagicInfo
*magic_info;
FILE
*ps_file;
ImageInfo
*clone_info;
Image
*image2;
unsigned char
magick[2*MaxTextExtent];
if ((clone_info=CloneImageInfo(image_info)) == NULL)
return(image);
clone_info->blob=(void *) NULL;
clone_info->length=0;
/* Obtain temporary file */
(void) AcquireUniqueFilename(postscript_file);
ps_file=fopen_utf8(postscript_file,"wb");
if (ps_file == (FILE *) NULL)
goto FINISH;
/* Copy postscript to temporary file */
(void) SeekBlob(image,PS_Offset,SEEK_SET);
(void) ReadBlob(image, 2*MaxTextExtent, magick);
(void) SeekBlob(image,PS_Offset,SEEK_SET);
while(PS_Size-- > 0)
{
(void) fputc(ReadBlobByte(image),ps_file);
}
(void) fclose(ps_file);
/* Detect file format - Check magic.mgk configuration file. */
magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception);
if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;
/* printf("Detected:%s \n",magic_info->name); */
if(exception->severity != UndefinedException) goto FINISH_UNL;
if(magic_info->name == (char *) NULL) goto FINISH_UNL;
(void) CopyMagickMemory(clone_info->magick,magic_info->name,MaxTextExtent);
/* Read nested image */
/*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file);
image2=ReadImage(clone_info,exception);
if (!image2)
goto FINISH_UNL;
/*
Replace current image with new image while copying base image
attributes.
*/
(void) CopyMagickMemory(image2->filename,image->filename,MaxTextExtent);
(void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MaxTextExtent);
(void) CopyMagickMemory(image2->magick,image->magick,MaxTextExtent);
image2->depth=image->depth;
DestroyBlob(image2);
image2->blob=ReferenceBlob(image->blob);
if ((image->rows == 0) || (image->columns == 0))
DeleteImageFromList(&image);
AppendImageToList(&image,image2);
FINISH_UNL:
(void) RelinquishUniqueFileResource(postscript_file);
FINISH:
DestroyImageInfo(clone_info);
return(image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/122
CWE ID: CWE-125
|
static Image *ExtractPostscript(Image *image,const ImageInfo *image_info,
MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)
{
char
postscript_file[MaxTextExtent];
const MagicInfo
*magic_info;
FILE
*ps_file;
ImageInfo
*clone_info;
Image
*image2;
unsigned char
magick[2*MaxTextExtent];
if ((clone_info=CloneImageInfo(image_info)) == NULL)
return(image);
clone_info->blob=(void *) NULL;
clone_info->length=0;
/* Obtain temporary file */
(void) AcquireUniqueFilename(postscript_file);
ps_file=fopen_utf8(postscript_file,"wb");
if (ps_file == (FILE *) NULL)
goto FINISH;
/* Copy postscript to temporary file */
(void) SeekBlob(image,PS_Offset,SEEK_SET);
(void) ReadBlob(image, 2*MaxTextExtent, magick);
(void) SeekBlob(image,PS_Offset,SEEK_SET);
while(PS_Size-- > 0)
{
(void) fputc(ReadBlobByte(image),ps_file);
}
(void) fclose(ps_file);
/* Detect file format - Check magic.mgk configuration file. */
magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception);
if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;
/* printf("Detected:%s \n",magic_info->name); */
if(exception->severity != UndefinedException) goto FINISH_UNL;
if(magic_info->name == (char *) NULL) goto FINISH_UNL;
(void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent);
/* Read nested image */
/*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file);
image2=ReadImage(clone_info,exception);
if (!image2)
goto FINISH_UNL;
/*
Replace current image with new image while copying base image
attributes.
*/
(void) CopyMagickMemory(image2->filename,image->filename,MaxTextExtent);
(void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MaxTextExtent);
(void) CopyMagickMemory(image2->magick,image->magick,MaxTextExtent);
image2->depth=image->depth;
DestroyBlob(image2);
image2->blob=ReferenceBlob(image->blob);
if ((image->rows == 0) || (image->columns == 0))
DeleteImageFromList(&image);
AppendImageToList(&image,image2);
FINISH_UNL:
(void) RelinquishUniqueFileResource(postscript_file);
FINISH:
DestroyImageInfo(clone_info);
return(image);
}
| 168,802
|
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: ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_cert *p;
struct ikev1_pl_cert cert;
static const char *certstr[] = {
"none", "pkcs7", "pgp", "dns",
"x509sign", "x509ke", "kerberos", "crl",
"arl", "spki", "x509attr",
};
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR)));
p = (const struct ikev1_pl_cert *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&cert, ext, sizeof(cert));
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_cert *p;
struct ikev1_pl_cert cert;
static const char *certstr[] = {
"none", "pkcs7", "pgp", "dns",
"x509sign", "x509ke", "kerberos", "crl",
"arl", "spki", "x509attr",
};
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR)));
p = (const struct ikev1_pl_cert *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&cert, ext, sizeof(cert));
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR)));
return NULL;
}
| 167,790
|
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 read_sequence_header(decoder_info_t *decoder_info, stream_t *stream) {
decoder_info->width = get_flc(16, stream);
decoder_info->height = get_flc(16, stream);
decoder_info->log2_sb_size = get_flc(3, stream);
decoder_info->pb_split = get_flc(1, stream);
decoder_info->tb_split_enable = get_flc(1, stream);
decoder_info->max_num_ref = get_flc(2, stream) + 1;
decoder_info->interp_ref = get_flc(2, stream);
decoder_info->max_delta_qp = get_flc(1, stream);
decoder_info->deblocking = get_flc(1, stream);
decoder_info->clpf = get_flc(1, stream);
decoder_info->use_block_contexts = get_flc(1, stream);
decoder_info->bipred = get_flc(2, stream);
decoder_info->qmtx = get_flc(1, stream);
if (decoder_info->qmtx) {
decoder_info->qmtx_offset = get_flc(6, stream) - 32;
}
decoder_info->subsample = get_flc(2, stream);
decoder_info->subsample = // 0: 400 1: 420 2: 422 3: 444
(decoder_info->subsample & 1) * 20 + (decoder_info->subsample & 2) * 22 +
((decoder_info->subsample & 3) == 3) * 2 + 400;
decoder_info->num_reorder_pics = get_flc(4, stream);
if (decoder_info->subsample != 400) {
decoder_info->cfl_intra = get_flc(1, stream);
decoder_info->cfl_inter = get_flc(1, stream);
}
decoder_info->bitdepth = get_flc(1, stream) ? 10 : 8;
if (decoder_info->bitdepth == 10)
decoder_info->bitdepth += 2 * get_flc(1, stream);
decoder_info->input_bitdepth = get_flc(1, stream) ? 10 : 8;
if (decoder_info->input_bitdepth == 10)
decoder_info->input_bitdepth += 2 * get_flc(1, stream);
}
Commit Message: Fix possible stack overflows in decoder for illegal bit streams
Fixes CVE-2018-0429
A vulnerability in the Thor decoder (available at:
https://github.com/cisco/thor) could allow an authenticated, local
attacker to cause segmentation faults and stack overflows when using a
non-conformant Thor bitstream as input.
The vulnerability is due to lack of input validation when parsing the
bitstream. A successful exploit could allow the attacker to cause a
stack overflow and potentially inject and execute arbitrary code.
CWE ID: CWE-119
|
void read_sequence_header(decoder_info_t *decoder_info, stream_t *stream) {
decoder_info->width = get_flc(16, stream);
decoder_info->height = get_flc(16, stream);
decoder_info->log2_sb_size = get_flc(3, stream);
decoder_info->log2_sb_size = clip(decoder_info->log2_sb_size, log2i(MIN_BLOCK_SIZE), log2i(MAX_SB_SIZE));
decoder_info->pb_split = get_flc(1, stream);
decoder_info->tb_split_enable = get_flc(1, stream);
decoder_info->max_num_ref = get_flc(2, stream) + 1;
decoder_info->interp_ref = get_flc(2, stream);
decoder_info->max_delta_qp = get_flc(1, stream);
decoder_info->deblocking = get_flc(1, stream);
decoder_info->clpf = get_flc(1, stream);
decoder_info->use_block_contexts = get_flc(1, stream);
decoder_info->bipred = get_flc(2, stream);
decoder_info->qmtx = get_flc(1, stream);
if (decoder_info->qmtx) {
decoder_info->qmtx_offset = get_flc(6, stream) - 32;
}
decoder_info->subsample = get_flc(2, stream);
decoder_info->subsample = // 0: 400 1: 420 2: 422 3: 444
(decoder_info->subsample & 1) * 20 + (decoder_info->subsample & 2) * 22 +
((decoder_info->subsample & 3) == 3) * 2 + 400;
decoder_info->num_reorder_pics = get_flc(4, stream);
if (decoder_info->subsample != 400) {
decoder_info->cfl_intra = get_flc(1, stream);
decoder_info->cfl_inter = get_flc(1, stream);
}
decoder_info->bitdepth = get_flc(1, stream) ? 10 : 8;
if (decoder_info->bitdepth == 10)
decoder_info->bitdepth += 2 * get_flc(1, stream);
decoder_info->input_bitdepth = get_flc(1, stream) ? 10 : 8;
if (decoder_info->input_bitdepth == 10)
decoder_info->input_bitdepth += 2 * get_flc(1, stream);
}
| 169,367
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_FUNCTION(mcrypt_module_is_block_algorithm)
{
MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
if (mcrypt_module_is_block_algorithm(module, dir) == 1) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
|
PHP_FUNCTION(mcrypt_module_is_block_algorithm)
{
MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
if (mcrypt_module_is_block_algorithm(module, dir) == 1) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
| 167,097
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: my_object_echo_variant (MyObject *obj, GValue *variant, GValue *ret, GError **error)
{
GType t;
t = G_VALUE_TYPE(variant);
g_value_init (ret, t);
g_value_copy (variant, ret);
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_echo_variant (MyObject *obj, GValue *variant, GValue *ret, GError **error)
| 165,093
|
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: frag6_print(netdissect_options *ndo, register const u_char *bp, register const u_char *bp2)
{
register const struct ip6_frag *dp;
register const struct ip6_hdr *ip6;
dp = (const struct ip6_frag *)bp;
ip6 = (const struct ip6_hdr *)bp2;
ND_TCHECK(dp->ip6f_offlg);
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "frag (0x%08x:%d|%ld)",
EXTRACT_32BITS(&dp->ip6f_ident),
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
} else {
ND_PRINT((ndo, "frag (%d|%ld)",
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
}
/* it is meaningless to decode non-first fragment */
if ((EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK) != 0)
return -1;
else
{
ND_PRINT((ndo, " "));
return sizeof(struct ip6_frag);
}
trunc:
ND_PRINT((ndo, "[|frag]"));
return -1;
}
Commit Message: CVE-2017-13031/Check for the presence of the entire IPv6 fragment header.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
Clean up some whitespace in tests/TESTLIST while we're at it.
CWE ID: CWE-125
|
frag6_print(netdissect_options *ndo, register const u_char *bp, register const u_char *bp2)
{
register const struct ip6_frag *dp;
register const struct ip6_hdr *ip6;
dp = (const struct ip6_frag *)bp;
ip6 = (const struct ip6_hdr *)bp2;
ND_TCHECK(*dp);
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "frag (0x%08x:%d|%ld)",
EXTRACT_32BITS(&dp->ip6f_ident),
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
} else {
ND_PRINT((ndo, "frag (%d|%ld)",
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
}
/* it is meaningless to decode non-first fragment */
if ((EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK) != 0)
return -1;
else
{
ND_PRINT((ndo, " "));
return sizeof(struct ip6_frag);
}
trunc:
ND_PRINT((ndo, "[|frag]"));
return -1;
}
| 167,852
|
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 ASessionDescription::getDimensions(
size_t index, unsigned long PT,
int32_t *width, int32_t *height) const {
*width = 0;
*height = 0;
char key[20];
sprintf(key, "a=framesize:%lu", PT);
AString value;
if (!findAttribute(index, key, &value)) {
return false;
}
const char *s = value.c_str();
char *end;
*width = strtoul(s, &end, 10);
CHECK_GT(end, s);
CHECK_EQ(*end, '-');
s = end + 1;
*height = strtoul(s, &end, 10);
CHECK_GT(end, s);
CHECK_EQ(*end, '\0');
return true;
}
Commit Message: Fix corruption via buffer overflow in mediaserver
change unbound sprintf() to snprintf() so network-provided values
can't overflow the buffers.
Applicable to all K/L/M/N branches.
Bug: 25747670
Change-Id: Id6a5120c2d08a6fbbd47deffb680ecf82015f4f6
CWE ID: CWE-284
|
bool ASessionDescription::getDimensions(
size_t index, unsigned long PT,
int32_t *width, int32_t *height) const {
*width = 0;
*height = 0;
char key[33];
snprintf(key, sizeof(key), "a=framesize:%lu", PT);
if (PT > 9999999) {
android_errorWriteLog(0x534e4554, "25747670");
}
AString value;
if (!findAttribute(index, key, &value)) {
return false;
}
const char *s = value.c_str();
char *end;
*width = strtoul(s, &end, 10);
CHECK_GT(end, s);
CHECK_EQ(*end, '-');
s = end + 1;
*height = strtoul(s, &end, 10);
CHECK_GT(end, s);
CHECK_EQ(*end, '\0');
return true;
}
| 173,410
|
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_qcd_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_qcd_t *qcd = &ms->parms.qcd;
int i;
fprintf(out, "qntsty = %d; numguard = %d; numstepsizes = %d\n",
(int) qcd->compparms.qntsty, qcd->compparms.numguard, qcd->compparms.numstepsizes);
for (i = 0; i < qcd->compparms.numstepsizes; ++i) {
fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n",
i, (unsigned) JPC_QCX_GETEXPN(qcd->compparms.stepsizes[i]),
i, (unsigned) JPC_QCX_GETMANT(qcd->compparms.stepsizes[i]));
}
return 0;
}
Commit Message: Changed the JPC bitstream code to more gracefully handle a request
for a larger sized integer than what can be handled (i.e., return
with an error instead of failing an assert).
CWE ID:
|
static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_qcd_t *qcd = &ms->parms.qcd;
int i;
fprintf(out, "qntsty = %d; numguard = %d; numstepsizes = %d\n",
(int) qcd->compparms.qntsty, qcd->compparms.numguard, qcd->compparms.numstepsizes);
for (i = 0; i < qcd->compparms.numstepsizes; ++i) {
fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n",
i, JAS_CAST(unsigned, JPC_QCX_GETEXPN(qcd->compparms.stepsizes[i])),
i, JAS_CAST(unsigned, JPC_QCX_GETMANT(qcd->compparms.stepsizes[i])));
}
return 0;
}
| 168,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: std::unique_ptr<HistogramBase> PersistentHistogramAllocator::GetHistogram(
Reference ref) {
PersistentHistogramData* data =
memory_allocator_->GetAsObject<PersistentHistogramData>(ref);
const size_t length = memory_allocator_->GetAllocSize(ref);
if (!data || data->name[0] == '\0' ||
reinterpret_cast<char*>(data)[length - 1] != '\0' ||
data->samples_metadata.id == 0 || data->logged_metadata.id == 0 ||
(data->logged_metadata.id != data->samples_metadata.id &&
data->logged_metadata.id != data->samples_metadata.id + 1) ||
HashMetricName(data->name) != data->samples_metadata.id) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_METADATA);
NOTREACHED();
return nullptr;
}
return CreateHistogram(data);
}
Commit Message: Remove UMA.CreatePersistentHistogram.Result
This histogram isn't showing anything meaningful and the problems it
could show are better observed by looking at the allocators directly.
Bug: 831013
Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9
Reviewed-on: https://chromium-review.googlesource.com/1008047
Commit-Queue: Brian White <bcwhite@chromium.org>
Reviewed-by: Alexei Svitkine <asvitkine@chromium.org>
Cr-Commit-Position: refs/heads/master@{#549986}
CWE ID: CWE-264
|
std::unique_ptr<HistogramBase> PersistentHistogramAllocator::GetHistogram(
Reference ref) {
PersistentHistogramData* data =
memory_allocator_->GetAsObject<PersistentHistogramData>(ref);
const size_t length = memory_allocator_->GetAllocSize(ref);
if (!data || data->name[0] == '\0' ||
reinterpret_cast<char*>(data)[length - 1] != '\0' ||
data->samples_metadata.id == 0 || data->logged_metadata.id == 0 ||
(data->logged_metadata.id != data->samples_metadata.id &&
data->logged_metadata.id != data->samples_metadata.id + 1) ||
HashMetricName(data->name) != data->samples_metadata.id) {
NOTREACHED();
return nullptr;
}
return CreateHistogram(data);
}
| 172,134
|
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 OMXNodeInstance::prepareForAdaptivePlayback(
OMX_U32 portIndex, OMX_BOOL enable, OMX_U32 maxFrameWidth,
OMX_U32 maxFrameHeight) {
Mutex::Autolock autolock(mLock);
CLOG_CONFIG(prepareForAdaptivePlayback, "%s:%u en=%d max=%ux%u",
portString(portIndex), portIndex, enable, maxFrameWidth, maxFrameHeight);
OMX_INDEXTYPE index;
OMX_STRING name = const_cast<OMX_STRING>(
"OMX.google.android.index.prepareForAdaptivePlayback");
OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index);
if (err != OMX_ErrorNone) {
CLOG_ERROR_IF(enable, getExtensionIndex, err, "%s", name);
return StatusFromOMXError(err);
}
PrepareForAdaptivePlaybackParams params;
InitOMXParams(¶ms);
params.nPortIndex = portIndex;
params.bEnable = enable;
params.nMaxFrameWidth = maxFrameWidth;
params.nMaxFrameHeight = maxFrameHeight;
err = OMX_SetParameter(mHandle, index, ¶ms);
CLOG_IF_ERROR(setParameter, err, "%s(%#x): %s:%u en=%d max=%ux%u", name, index,
portString(portIndex), portIndex, enable, maxFrameWidth, maxFrameHeight);
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200
|
status_t OMXNodeInstance::prepareForAdaptivePlayback(
OMX_U32 portIndex, OMX_BOOL enable, OMX_U32 maxFrameWidth,
OMX_U32 maxFrameHeight) {
Mutex::Autolock autolock(mLock);
if (mSailed) {
android_errorWriteLog(0x534e4554, "29422020");
return INVALID_OPERATION;
}
CLOG_CONFIG(prepareForAdaptivePlayback, "%s:%u en=%d max=%ux%u",
portString(portIndex), portIndex, enable, maxFrameWidth, maxFrameHeight);
OMX_INDEXTYPE index;
OMX_STRING name = const_cast<OMX_STRING>(
"OMX.google.android.index.prepareForAdaptivePlayback");
OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index);
if (err != OMX_ErrorNone) {
CLOG_ERROR_IF(enable, getExtensionIndex, err, "%s", name);
return StatusFromOMXError(err);
}
PrepareForAdaptivePlaybackParams params;
InitOMXParams(¶ms);
params.nPortIndex = portIndex;
params.bEnable = enable;
params.nMaxFrameWidth = maxFrameWidth;
params.nMaxFrameHeight = maxFrameHeight;
err = OMX_SetParameter(mHandle, index, ¶ms);
CLOG_IF_ERROR(setParameter, err, "%s(%#x): %s:%u en=%d max=%ux%u", name, index,
portString(portIndex), portIndex, enable, maxFrameWidth, maxFrameHeight);
return StatusFromOMXError(err);
}
| 174,136
|
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: Cluster::Cluster() :
m_pSegment(NULL),
m_element_start(0),
m_index(0),
m_pos(0),
m_element_size(0),
m_timecode(0),
m_entries(NULL),
m_entries_size(0),
m_entries_count(0) //means "no entries"
{
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
Cluster::Cluster() :
| 174,248
|
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 mp_encode_lua_table_as_array(lua_State *L, mp_buf *buf, int level) {
#if LUA_VERSION_NUM < 502
size_t len = lua_objlen(L,-1), j;
#else
size_t len = lua_rawlen(L,-1), j;
#endif
mp_encode_array(L,buf,len);
for (j = 1; j <= len; j++) {
lua_pushnumber(L,j);
lua_gettable(L,-2);
mp_encode_lua_type(L,buf,level+1);
}
}
Commit Message: Security: more cmsgpack fixes by @soloestoy.
@soloestoy sent me this additional fixes, after searching for similar
problems to the one reported in mp_pack(). I'm committing the changes
because it was not possible during to make a public PR to protect Redis
users and give Redis providers some time to patch their systems.
CWE ID: CWE-119
|
void mp_encode_lua_table_as_array(lua_State *L, mp_buf *buf, int level) {
#if LUA_VERSION_NUM < 502
size_t len = lua_objlen(L,-1), j;
#else
size_t len = lua_rawlen(L,-1), j;
#endif
mp_encode_array(L,buf,len);
luaL_checkstack(L, 1, "in function mp_encode_lua_table_as_array");
for (j = 1; j <= len; j++) {
lua_pushnumber(L,j);
lua_gettable(L,-2);
mp_encode_lua_type(L,buf,level+1);
}
}
| 169,239
|
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: GURL URLFixerUpper::FixupRelativeFile(const FilePath& base_dir,
const FilePath& text) {
FilePath old_cur_directory;
if (!base_dir.empty()) {
file_util::GetCurrentDirectory(&old_cur_directory);
file_util::SetCurrentDirectory(base_dir);
}
FilePath::StringType trimmed;
PrepareStringForFileOps(text, &trimmed);
bool is_file = true;
FilePath full_path;
if (!ValidPathForFile(trimmed, &full_path)) {
#if defined(OS_WIN)
std::wstring unescaped = UTF8ToWide(UnescapeURLComponent(
WideToUTF8(trimmed),
UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS));
#elif defined(OS_POSIX)
std::string unescaped = UnescapeURLComponent(
trimmed,
UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS);
#endif
if (!ValidPathForFile(unescaped, &full_path))
is_file = false;
}
if (!base_dir.empty())
file_util::SetCurrentDirectory(old_cur_directory);
if (is_file) {
GURL file_url = net::FilePathToFileURL(full_path);
if (file_url.is_valid())
return GURL(UTF16ToUTF8(net::FormatUrl(file_url, std::string(),
net::kFormatUrlOmitUsernamePassword, UnescapeRule::NORMAL, NULL,
NULL, NULL)));
}
#if defined(OS_WIN)
std::string text_utf8 = WideToUTF8(text.value());
#elif defined(OS_POSIX)
std::string text_utf8 = text.value();
#endif
return FixupURL(text_utf8, std::string());
}
Commit Message: Be a little more careful whether something is an URL or a file path.
BUG=72492
Review URL: http://codereview.chromium.org/7572046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@95731 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
GURL URLFixerUpper::FixupRelativeFile(const FilePath& base_dir,
const FilePath& text) {
FilePath old_cur_directory;
if (!base_dir.empty()) {
file_util::GetCurrentDirectory(&old_cur_directory);
file_util::SetCurrentDirectory(base_dir);
}
FilePath::StringType trimmed;
PrepareStringForFileOps(text, &trimmed);
bool is_file = true;
// Avoid recognizing definite non-file URLs as file paths.
GURL gurl(trimmed);
if (gurl.is_valid() && gurl.IsStandard())
is_file = false;
FilePath full_path;
if (is_file && !ValidPathForFile(trimmed, &full_path)) {
#if defined(OS_WIN)
std::wstring unescaped = UTF8ToWide(UnescapeURLComponent(
WideToUTF8(trimmed),
UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS));
#elif defined(OS_POSIX)
std::string unescaped = UnescapeURLComponent(
trimmed,
UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS);
#endif
if (!ValidPathForFile(unescaped, &full_path))
is_file = false;
}
if (!base_dir.empty())
file_util::SetCurrentDirectory(old_cur_directory);
if (is_file) {
GURL file_url = net::FilePathToFileURL(full_path);
if (file_url.is_valid())
return GURL(UTF16ToUTF8(net::FormatUrl(file_url, std::string(),
net::kFormatUrlOmitUsernamePassword, UnescapeRule::NORMAL, NULL,
NULL, NULL)));
}
#if defined(OS_WIN)
std::string text_utf8 = WideToUTF8(text.value());
#elif defined(OS_POSIX)
std::string text_utf8 = text.value();
#endif
return FixupURL(text_utf8, std::string());
}
| 170,364
|
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 red_channel_pipes_add_empty_msg(RedChannel *channel, int msg_type)
{
RingItem *link;
RING_FOREACH(link, &channel->clients) {
red_channel_client_pipe_add_empty_msg(
SPICE_CONTAINEROF(link, RedChannelClient, channel_link),
msg_type);
}
}
Commit Message:
CWE ID: CWE-399
|
void red_channel_pipes_add_empty_msg(RedChannel *channel, int msg_type)
{
RingItem *link, *next;
RING_FOREACH_SAFE(link, next, &channel->clients) {
red_channel_client_pipe_add_empty_msg(
SPICE_CONTAINEROF(link, RedChannelClient, channel_link),
msg_type);
}
}
| 164,663
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int picolcd_raw_event(struct hid_device *hdev,
struct hid_report *report, u8 *raw_data, int size)
{
struct picolcd_data *data = hid_get_drvdata(hdev);
unsigned long flags;
int ret = 0;
if (!data)
return 1;
if (report->id == REPORT_KEY_STATE) {
if (data->input_keys)
ret = picolcd_raw_keypad(data, report, raw_data+1, size-1);
} else if (report->id == REPORT_IR_DATA) {
ret = picolcd_raw_cir(data, report, raw_data+1, size-1);
} else {
spin_lock_irqsave(&data->lock, flags);
/*
* We let the caller of picolcd_send_and_wait() check if the
* report we got is one of the expected ones or not.
*/
if (data->pending) {
memcpy(data->pending->raw_data, raw_data+1, size-1);
data->pending->raw_size = size-1;
data->pending->in_report = report;
complete(&data->pending->ready);
}
spin_unlock_irqrestore(&data->lock, flags);
}
picolcd_debug_raw_event(data, hdev, report, raw_data, size);
return 1;
}
Commit Message: HID: picolcd: sanity check report size in raw_event() callback
The report passed to us from transport driver could potentially be
arbitrarily large, therefore we better sanity-check it so that raw_data
that we hold in picolcd_pending structure are always kept within proper
bounds.
Cc: stable@vger.kernel.org
Reported-by: Steven Vittitoe <scvitti@google.com>
Signed-off-by: Jiri Kosina <jkosina@suse.cz>
CWE ID: CWE-119
|
static int picolcd_raw_event(struct hid_device *hdev,
struct hid_report *report, u8 *raw_data, int size)
{
struct picolcd_data *data = hid_get_drvdata(hdev);
unsigned long flags;
int ret = 0;
if (!data)
return 1;
if (size > 64) {
hid_warn(hdev, "invalid size value (%d) for picolcd raw event\n",
size);
return 0;
}
if (report->id == REPORT_KEY_STATE) {
if (data->input_keys)
ret = picolcd_raw_keypad(data, report, raw_data+1, size-1);
} else if (report->id == REPORT_IR_DATA) {
ret = picolcd_raw_cir(data, report, raw_data+1, size-1);
} else {
spin_lock_irqsave(&data->lock, flags);
/*
* We let the caller of picolcd_send_and_wait() check if the
* report we got is one of the expected ones or not.
*/
if (data->pending) {
memcpy(data->pending->raw_data, raw_data+1, size-1);
data->pending->raw_size = size-1;
data->pending->in_report = report;
complete(&data->pending->ready);
}
spin_unlock_irqrestore(&data->lock, flags);
}
picolcd_debug_raw_event(data, hdev, report, raw_data, size);
return 1;
}
| 166,368
|
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 SeekHead::VoidElement* SeekHead::GetVoidElement(int idx) const
{
if (idx < 0)
return 0;
if (idx >= m_void_element_count)
return 0;
return m_void_elements + idx;
}
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 SeekHead::VoidElement* SeekHead::GetVoidElement(int idx) const
| 174,380
|
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::GetEditionCount() const
{
return m_editions_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::GetEditionCount() const
const Chapters::Edition* Chapters::GetEdition(int idx) const {
if (idx < 0)
return NULL;
if (idx >= m_editions_count)
return NULL;
return m_editions + idx;
}
| 174,311
|
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 quint32 swapBgrToRgb(quint32 pixel)
{
return ((pixel << 16) & 0xff0000) | ((pixel >> 16) & 0xff) | (pixel & 0xff00ff00);
}
Commit Message: [Qt] Remove an unnecessary masking from swapBgrToRgb()
https://bugs.webkit.org/show_bug.cgi?id=103630
Reviewed by Zoltan Herczeg.
Get rid of a masking command in swapBgrToRgb() to speed up a little bit.
* platform/graphics/qt/GraphicsContext3DQt.cpp:
(WebCore::swapBgrToRgb):
git-svn-id: svn://svn.chromium.org/blink/trunk@136375 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264
|
static inline quint32 swapBgrToRgb(quint32 pixel)
{
return (((pixel << 16) | (pixel >> 16)) & 0x00ff00ff) | (pixel & 0xff00ff00);
}
| 170,963
|
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: BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s)
{
UINT32 i;
BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE));
if (!bitmapUpdate)
goto fail;
if (Stream_GetRemainingLength(s) < 2)
goto fail;
Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */
WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %"PRIu32"", bitmapUpdate->number);
if (bitmapUpdate->number > bitmapUpdate->count)
{
UINT16 count;
BITMAP_DATA* newdata;
count = bitmapUpdate->number * 2;
newdata = (BITMAP_DATA*) realloc(bitmapUpdate->rectangles,
sizeof(BITMAP_DATA) * count);
if (!newdata)
goto fail;
bitmapUpdate->rectangles = newdata;
ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count],
sizeof(BITMAP_DATA) * (count - bitmapUpdate->count));
bitmapUpdate->count = count;
}
/* rectangles */
for (i = 0; i < bitmapUpdate->number; i++)
{
if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i]))
goto fail;
}
return bitmapUpdate;
fail:
free_bitmap_update(update->context, bitmapUpdate);
return NULL;
}
Commit Message: Fixed CVE-2018-8786
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-119
|
BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s)
{
UINT32 i;
BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE));
if (!bitmapUpdate)
goto fail;
if (Stream_GetRemainingLength(s) < 2)
goto fail;
Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */
WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %"PRIu32"", bitmapUpdate->number);
if (bitmapUpdate->number > bitmapUpdate->count)
{
UINT32 count = bitmapUpdate->number * 2;
BITMAP_DATA* newdata = (BITMAP_DATA*) realloc(bitmapUpdate->rectangles,
sizeof(BITMAP_DATA) * count);
if (!newdata)
goto fail;
bitmapUpdate->rectangles = newdata;
ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count],
sizeof(BITMAP_DATA) * (count - bitmapUpdate->count));
bitmapUpdate->count = count;
}
/* rectangles */
for (i = 0; i < bitmapUpdate->number; i++)
{
if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i]))
goto fail;
}
return bitmapUpdate;
fail:
free_bitmap_update(update->context, bitmapUpdate);
return NULL;
}
| 169,293
|
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: scandir(const char *dir, struct dirent ***namelist,
int (*select) (const struct dirent *),
int (*compar) (const struct dirent **, const struct dirent **))
{
DIR *d = opendir(dir);
struct dirent *current;
struct dirent **names;
int count = 0;
int pos = 0;
int result = -1;
if (NULL == d)
return -1;
while (NULL != readdir(d))
count++;
names = malloc(sizeof (struct dirent *) * count);
closedir(d);
d = opendir(dir);
if (NULL == d)
return -1;
while (NULL != (current = readdir(d))) {
if (NULL == select || select(current)) {
struct dirent *copyentry = malloc(current->d_reclen);
memcpy(copyentry, current, current->d_reclen);
names[pos] = copyentry;
pos++;
}
}
result = closedir(d);
if (pos != count)
names = realloc(names, sizeof (struct dirent *) * pos);
*namelist = names;
return pos;
}
Commit Message: misc oom and possible memory leak fix
CWE ID:
|
scandir(const char *dir, struct dirent ***namelist,
int (*select) (const struct dirent *),
int (*compar) (const struct dirent **, const struct dirent **))
{
DIR *d = opendir(dir);
struct dirent *current;
struct dirent **names;
int count = 0;
int pos = 0;
int result = -1;
if (NULL == d)
return -1;
while (NULL != readdir(d))
count++;
closedir(d);
names = malloc(sizeof (struct dirent *) * count);
if (!names)
return -1;
d = opendir(dir);
if (NULL == d) {
free(names);
return -1;
}
while (NULL != (current = readdir(d))) {
if (NULL == select || select(current)) {
struct dirent *copyentry = malloc(current->d_reclen);
/* FIXME: OOM, silently skip it?*/
if (!copyentry)
continue;
memcpy(copyentry, current, current->d_reclen);
names[pos] = copyentry;
pos++;
}
}
result = closedir(d);
if (pos != count)
names = realloc(names, sizeof (struct dirent *) * pos);
*namelist = names;
return pos;
}
| 169,754
|
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 SyncManager::Init(
const FilePath& database_location,
const WeakHandle<JsEventHandler>& event_handler,
const std::string& sync_server_and_path,
int sync_server_port,
bool use_ssl,
const scoped_refptr<base::TaskRunner>& blocking_task_runner,
HttpPostProviderFactory* post_factory,
ModelSafeWorkerRegistrar* registrar,
browser_sync::ExtensionsActivityMonitor* extensions_activity_monitor,
ChangeDelegate* change_delegate,
const std::string& user_agent,
const SyncCredentials& credentials,
bool enable_sync_tabs_for_other_clients,
sync_notifier::SyncNotifier* sync_notifier,
const std::string& restored_key_for_bootstrapping,
TestingMode testing_mode,
Encryptor* encryptor,
UnrecoverableErrorHandler* unrecoverable_error_handler,
ReportUnrecoverableErrorFunction report_unrecoverable_error_function) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(post_factory);
DVLOG(1) << "SyncManager starting Init...";
std::string server_string(sync_server_and_path);
return data_->Init(database_location,
event_handler,
server_string,
sync_server_port,
use_ssl,
blocking_task_runner,
post_factory,
registrar,
extensions_activity_monitor,
change_delegate,
user_agent,
credentials,
enable_sync_tabs_for_other_clients,
sync_notifier,
restored_key_for_bootstrapping,
testing_mode,
encryptor,
unrecoverable_error_handler,
report_unrecoverable_error_function);
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362
|
bool SyncManager::Init(
const FilePath& database_location,
const WeakHandle<JsEventHandler>& event_handler,
const std::string& sync_server_and_path,
int sync_server_port,
bool use_ssl,
const scoped_refptr<base::TaskRunner>& blocking_task_runner,
HttpPostProviderFactory* post_factory,
ModelSafeWorkerRegistrar* registrar,
browser_sync::ExtensionsActivityMonitor* extensions_activity_monitor,
ChangeDelegate* change_delegate,
const std::string& user_agent,
const SyncCredentials& credentials,
sync_notifier::SyncNotifier* sync_notifier,
const std::string& restored_key_for_bootstrapping,
TestingMode testing_mode,
Encryptor* encryptor,
UnrecoverableErrorHandler* unrecoverable_error_handler,
ReportUnrecoverableErrorFunction report_unrecoverable_error_function) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(post_factory);
DVLOG(1) << "SyncManager starting Init...";
std::string server_string(sync_server_and_path);
return data_->Init(database_location,
event_handler,
server_string,
sync_server_port,
use_ssl,
blocking_task_runner,
post_factory,
registrar,
extensions_activity_monitor,
change_delegate,
user_agent,
credentials,
sync_notifier,
restored_key_for_bootstrapping,
testing_mode,
encryptor,
unrecoverable_error_handler,
report_unrecoverable_error_function);
}
| 170,792
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void InspectorController::initializeDeferredAgents()
{
if (m_deferredAgentsInitialized)
return;
m_deferredAgentsInitialized = true;
InjectedScriptManager* injectedScriptManager = m_injectedScriptManager.get();
InspectorOverlay* overlay = m_overlay.get();
OwnPtr<InspectorResourceAgent> resourceAgentPtr(InspectorResourceAgent::create(m_pageAgent, m_inspectorClient));
InspectorResourceAgent* resourceAgent = resourceAgentPtr.get();
m_agents.append(resourceAgentPtr.release());
m_agents.append(InspectorCSSAgent::create(m_domAgent, m_pageAgent, resourceAgent));
m_agents.append(InspectorDOMStorageAgent::create(m_pageAgent));
m_agents.append(InspectorMemoryAgent::create());
m_agents.append(InspectorApplicationCacheAgent::create(m_pageAgent));
PageScriptDebugServer* pageScriptDebugServer = &PageScriptDebugServer::shared();
OwnPtr<InspectorDebuggerAgent> debuggerAgentPtr(PageDebuggerAgent::create(pageScriptDebugServer, m_pageAgent, injectedScriptManager, overlay));
InspectorDebuggerAgent* debuggerAgent = debuggerAgentPtr.get();
m_agents.append(debuggerAgentPtr.release());
m_agents.append(InspectorDOMDebuggerAgent::create(m_domAgent, debuggerAgent));
m_agents.append(InspectorProfilerAgent::create(injectedScriptManager, overlay));
m_agents.append(InspectorHeapProfilerAgent::create(injectedScriptManager));
m_agents.append(InspectorCanvasAgent::create(m_pageAgent, injectedScriptManager));
m_agents.append(InspectorInputAgent::create(m_page, m_inspectorClient));
}
Commit Message: [4/4] Process clearBrowserCahce/cookies commands in browser.
BUG=366585
Review URL: https://codereview.chromium.org/251183005
git-svn-id: svn://svn.chromium.org/blink/trunk@172984 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
|
void InspectorController::initializeDeferredAgents()
{
if (m_deferredAgentsInitialized)
return;
m_deferredAgentsInitialized = true;
InjectedScriptManager* injectedScriptManager = m_injectedScriptManager.get();
InspectorOverlay* overlay = m_overlay.get();
OwnPtr<InspectorResourceAgent> resourceAgentPtr(InspectorResourceAgent::create(m_pageAgent));
InspectorResourceAgent* resourceAgent = resourceAgentPtr.get();
m_agents.append(resourceAgentPtr.release());
m_agents.append(InspectorCSSAgent::create(m_domAgent, m_pageAgent, resourceAgent));
m_agents.append(InspectorDOMStorageAgent::create(m_pageAgent));
m_agents.append(InspectorMemoryAgent::create());
m_agents.append(InspectorApplicationCacheAgent::create(m_pageAgent));
PageScriptDebugServer* pageScriptDebugServer = &PageScriptDebugServer::shared();
OwnPtr<InspectorDebuggerAgent> debuggerAgentPtr(PageDebuggerAgent::create(pageScriptDebugServer, m_pageAgent, injectedScriptManager, overlay));
InspectorDebuggerAgent* debuggerAgent = debuggerAgentPtr.get();
m_agents.append(debuggerAgentPtr.release());
m_agents.append(InspectorDOMDebuggerAgent::create(m_domAgent, debuggerAgent));
m_agents.append(InspectorProfilerAgent::create(injectedScriptManager, overlay));
m_agents.append(InspectorHeapProfilerAgent::create(injectedScriptManager));
m_agents.append(InspectorCanvasAgent::create(m_pageAgent, injectedScriptManager));
m_agents.append(InspectorInputAgent::create(m_page, m_inspectorClient));
}
| 171,344
|
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 btsock_l2cap_signaled(int fd, int flags, uint32_t user_id)
{
l2cap_socket *sock;
char drop_it = FALSE;
/* We use MSG_DONTWAIT when sending data to JAVA, hence it can be accepted to hold the lock. */
pthread_mutex_lock(&state_lock);
sock = btsock_l2cap_find_by_id_l(user_id);
if (sock) {
if ((flags & SOCK_THREAD_FD_RD) && !sock->server) {
if (sock->connected) {
int size = 0;
if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl(sock->our_fd, FIONREAD, &size)
== 0 && size)) {
uint8_t *buffer = osi_malloc(L2CAP_MAX_SDU_LENGTH);
/* Apparently we hijack the req_id (UINT32) to pass the pointer to the buffer to
* the write complete callback, which call a free... wonder if this works on a
* 64 bit platform? */
if (buffer != NULL) {
/* The socket is created with SOCK_SEQPACKET, hence we read one message at
* the time. The maximum size of a message is allocated to ensure data is
* not lost. This is okay to do as Android uses virtual memory, hence even
* if we only use a fraction of the memory it should not block for others
* to use the memory. As the definition of ioctl(FIONREAD) do not clearly
* define what value will be returned if multiple messages are written to
* the socket before any message is read from the socket, we could
* potentially risk to allocate way more memory than needed. One of the use
* cases for this socket is obex where multiple 64kbyte messages are
* typically written to the socket in a tight loop, hence we risk the ioctl
* will return the total amount of data in the buffer, which could be
* multiple 64kbyte chunks.
* UPDATE: As bluedroid cannot handle 64kbyte buffers, the size is reduced
* to around 8kbyte - and using malloc for buffer allocation here seems to
* be wrong
* UPDATE: Since we are responsible for freeing the buffer in the
* write_complete_ind, it is OK to use malloc. */
int count = recv(fd, buffer, L2CAP_MAX_SDU_LENGTH,
MSG_NOSIGNAL | MSG_DONTWAIT);
APPL_TRACE_DEBUG("btsock_l2cap_signaled - %d bytes received from socket",
count);
if (sock->fixed_chan) {
if(BTA_JvL2capWriteFixed(sock->channel, (BD_ADDR*)&sock->addr,
(UINT32)buffer, btsock_l2cap_cbk, buffer, count,
(void *)user_id) != BTA_JV_SUCCESS) {
on_l2cap_write_fixed_done(buffer, user_id);
}
} else {
if(BTA_JvL2capWrite(sock->handle, (UINT32)buffer, buffer, count,
(void *)user_id) != BTA_JV_SUCCESS) {
on_l2cap_write_done(buffer, user_id);
}
}
} else {
APPL_TRACE_ERROR("Unable to allocate memory for data packet from JAVA...")
}
}
} else
drop_it = TRUE;
}
if (flags & SOCK_THREAD_FD_WR) {
if (flush_incoming_que_on_wr_signal_l(sock) && sock->connected)
btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id);
}
if (drop_it || (flags & SOCK_THREAD_FD_EXCEPTION)) {
int size = 0;
if (drop_it || ioctl(sock->our_fd, FIONREAD, &size) != 0 || size == 0)
btsock_l2cap_free_l(sock);
}
}
pthread_mutex_unlock(&state_lock);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
void btsock_l2cap_signaled(int fd, int flags, uint32_t user_id)
{
l2cap_socket *sock;
char drop_it = FALSE;
/* We use MSG_DONTWAIT when sending data to JAVA, hence it can be accepted to hold the lock. */
pthread_mutex_lock(&state_lock);
sock = btsock_l2cap_find_by_id_l(user_id);
if (sock) {
if ((flags & SOCK_THREAD_FD_RD) && !sock->server) {
if (sock->connected) {
int size = 0;
if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (TEMP_FAILURE_RETRY(ioctl(sock->our_fd, FIONREAD, &size))
== 0 && size)) {
uint8_t *buffer = osi_malloc(L2CAP_MAX_SDU_LENGTH);
/* Apparently we hijack the req_id (UINT32) to pass the pointer to the buffer to
* the write complete callback, which call a free... wonder if this works on a
* 64 bit platform? */
if (buffer != NULL) {
/* The socket is created with SOCK_SEQPACKET, hence we read one message at
* the time. The maximum size of a message is allocated to ensure data is
* not lost. This is okay to do as Android uses virtual memory, hence even
* if we only use a fraction of the memory it should not block for others
* to use the memory. As the definition of ioctl(FIONREAD) do not clearly
* define what value will be returned if multiple messages are written to
* the socket before any message is read from the socket, we could
* potentially risk to allocate way more memory than needed. One of the use
* cases for this socket is obex where multiple 64kbyte messages are
* typically written to the socket in a tight loop, hence we risk the ioctl
* will return the total amount of data in the buffer, which could be
* multiple 64kbyte chunks.
* UPDATE: As bluedroid cannot handle 64kbyte buffers, the size is reduced
* to around 8kbyte - and using malloc for buffer allocation here seems to
* be wrong
* UPDATE: Since we are responsible for freeing the buffer in the
* write_complete_ind, it is OK to use malloc. */
int count = TEMP_FAILURE_RETRY(recv(fd, buffer, L2CAP_MAX_SDU_LENGTH,
MSG_NOSIGNAL | MSG_DONTWAIT));
APPL_TRACE_DEBUG("btsock_l2cap_signaled - %d bytes received from socket",
count);
if (sock->fixed_chan) {
if(BTA_JvL2capWriteFixed(sock->channel, (BD_ADDR*)&sock->addr,
(UINT32)buffer, btsock_l2cap_cbk, buffer, count,
(void *)user_id) != BTA_JV_SUCCESS) {
on_l2cap_write_fixed_done(buffer, user_id);
}
} else {
if(BTA_JvL2capWrite(sock->handle, (UINT32)buffer, buffer, count,
(void *)user_id) != BTA_JV_SUCCESS) {
on_l2cap_write_done(buffer, user_id);
}
}
} else {
APPL_TRACE_ERROR("Unable to allocate memory for data packet from JAVA...")
}
}
} else
drop_it = TRUE;
}
if (flags & SOCK_THREAD_FD_WR) {
if (flush_incoming_que_on_wr_signal_l(sock) && sock->connected)
btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id);
}
if (drop_it || (flags & SOCK_THREAD_FD_EXCEPTION)) {
int size = 0;
if (drop_it || TEMP_FAILURE_RETRY(ioctl(sock->our_fd, FIONREAD, &size)) != 0 || size == 0)
btsock_l2cap_free_l(sock);
}
}
pthread_mutex_unlock(&state_lock);
}
| 173,453
|
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: gpk_parse_fileinfo(sc_card_t *card,
const u8 *buf, size_t buflen,
sc_file_t *file)
{
const u8 *sp, *end, *next;
int i, rc;
memset(file, 0, sizeof(*file));
for (i = 0; i < SC_MAX_AC_OPS; i++)
sc_file_add_acl_entry(file, i, SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE);
end = buf + buflen;
for (sp = buf; sp + 2 < end; sp = next) {
next = sp + 2 + sp[1];
if (next > end)
break;
if (sp[0] == 0x84) {
/* ignore if name is longer than what it should be */
if (sp[1] > sizeof(file->name))
continue;
memset(file->name, 0, sizeof(file->name));
memcpy(file->name, sp+2, sp[1]);
} else
if (sp[0] == 0x85) {
unsigned int ac[3], n;
file->id = (sp[4] << 8) | sp[5];
file->size = (sp[8] << 8) | sp[9];
file->record_length = sp[7];
/* Map ACLs. Note the third AC byte is
* valid of EFs only */
for (n = 0; n < 3; n++)
ac[n] = (sp[10+2*n] << 8) | sp[11+2*n];
/* Examine file type */
switch (sp[6] & 7) {
case 0x01: case 0x02: case 0x03: case 0x04:
case 0x05: case 0x06: case 0x07:
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = sp[6] & 7;
ac_to_acl(ac[0], file, SC_AC_OP_UPDATE);
ac_to_acl(ac[1], file, SC_AC_OP_WRITE);
ac_to_acl(ac[2], file, SC_AC_OP_READ);
break;
case 0x00: /* 0x38 is DF */
file->type = SC_FILE_TYPE_DF;
/* Icky: the GPK uses different ACLs
* for creating data files and
* 'sensitive' i.e. key files */
ac_to_acl(ac[0], file, SC_AC_OP_LOCK);
ac_to_acl(ac[1], file, SC_AC_OP_CREATE);
sc_file_add_acl_entry(file, SC_AC_OP_SELECT,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_DELETE,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_LIST_FILES,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
break;
}
} else
if (sp[0] == 0x6f) {
/* oops - this is a directory with an IADF.
* This happens with the personalized GemSafe cards
* for instance. */
file->type = SC_FILE_TYPE_DF;
rc = gpk_parse_fci(card, sp + 2, sp[1], file);
if (rc < 0)
return rc;
}
}
if (file->record_length)
file->record_count = file->size / file->record_length;
file->magic = SC_FILE_MAGIC;
return 0;
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
|
gpk_parse_fileinfo(sc_card_t *card,
const u8 *buf, size_t buflen,
sc_file_t *file)
{
const u8 *sp, *end, *next;
int i, rc;
memset(file, 0, sizeof(*file));
for (i = 0; i < SC_MAX_AC_OPS; i++)
sc_file_add_acl_entry(file, i, SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE);
end = buf + buflen;
for (sp = buf; sp + 2 < end; sp = next) {
next = sp + 2 + sp[1];
if (next > end)
break;
if (sp[0] == 0x84) {
/* ignore if name is longer than what it should be */
if (sp[1] > sizeof(file->name))
continue;
memset(file->name, 0, sizeof(file->name));
memcpy(file->name, sp+2, sp[1]);
} else
if (sp[0] == 0x85) {
unsigned int ac[3], n;
if (sp + 11 + 2*3 >= end)
break;
file->id = (sp[4] << 8) | sp[5];
file->size = (sp[8] << 8) | sp[9];
file->record_length = sp[7];
/* Map ACLs. Note the third AC byte is
* valid of EFs only */
for (n = 0; n < 3; n++)
ac[n] = (sp[10+2*n] << 8) | sp[11+2*n];
/* Examine file type */
switch (sp[6] & 7) {
case 0x01: case 0x02: case 0x03: case 0x04:
case 0x05: case 0x06: case 0x07:
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = sp[6] & 7;
ac_to_acl(ac[0], file, SC_AC_OP_UPDATE);
ac_to_acl(ac[1], file, SC_AC_OP_WRITE);
ac_to_acl(ac[2], file, SC_AC_OP_READ);
break;
case 0x00: /* 0x38 is DF */
file->type = SC_FILE_TYPE_DF;
/* Icky: the GPK uses different ACLs
* for creating data files and
* 'sensitive' i.e. key files */
ac_to_acl(ac[0], file, SC_AC_OP_LOCK);
ac_to_acl(ac[1], file, SC_AC_OP_CREATE);
sc_file_add_acl_entry(file, SC_AC_OP_SELECT,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_DELETE,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_LIST_FILES,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
break;
}
} else
if (sp[0] == 0x6f) {
/* oops - this is a directory with an IADF.
* This happens with the personalized GemSafe cards
* for instance. */
file->type = SC_FILE_TYPE_DF;
rc = gpk_parse_fci(card, sp + 2, sp[1], file);
if (rc < 0)
return rc;
}
}
if (file->record_length)
file->record_count = file->size / file->record_length;
file->magic = SC_FILE_MAGIC;
return 0;
}
| 169,056
|
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 jslGetTokenString(char *str, size_t len) {
if (lex->tk == LEX_ID) {
strncpy(str, "ID:", len);
strncat(str, jslGetTokenValueAsString(), len);
} else if (lex->tk == LEX_STR) {
strncpy(str, "String:'", len);
strncat(str, jslGetTokenValueAsString(), len);
strncat(str, "'", len);
} else
jslTokenAsString(lex->tk, str, len);
}
Commit Message: Fix strncat/cpy bounding issues (fix #1425)
CWE ID: CWE-119
|
void jslGetTokenString(char *str, size_t len) {
if (lex->tk == LEX_ID) {
espruino_snprintf(str, len, "ID:%s", jslGetTokenValueAsString());
} else if (lex->tk == LEX_STR) {
espruino_snprintf(str, len, "String:'%s'", jslGetTokenValueAsString());
} else
jslTokenAsString(lex->tk, str, len);
}
| 169,211
|
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 readContigStripsIntoBuffer (TIFF* in, uint8* buf)
{
uint8* bufp = buf;
int32 bytes_read = 0;
uint16 strip, nstrips = TIFFNumberOfStrips(in);
uint32 stripsize = TIFFStripSize(in);
uint32 rows = 0;
uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
tsize_t scanline_size = TIFFScanlineSize(in);
if (scanline_size == 0) {
TIFFError("", "TIFF scanline size is zero!");
return 0;
}
for (strip = 0; strip < nstrips; strip++) {
bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1);
rows = bytes_read / scanline_size;
if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize))
TIFFError("", "Strip %d: read %lu bytes, strip size %lu",
(int)strip + 1, (unsigned long) bytes_read,
(unsigned long)stripsize);
if (bytes_read < 0 && !ignore) {
TIFFError("", "Error reading strip %lu after %lu rows",
(unsigned long) strip, (unsigned long)rows);
return 0;
}
bufp += bytes_read;
}
return 1;
} /* end readContigStripsIntoBuffer */
Commit Message: * tools/tiffcp.c: fix read of undefined variable in case of missing
required tags. Found on test case of MSVR 35100.
* tools/tiffcrop.c: fix read of undefined buffer in
readContigStripsIntoBuffer() due to uint16 overflow. Probably not a
security issue but I can be wrong. Reported as MSVR 35100 by Axel
Souchet from the MSRC Vulnerabilities & Mitigations team.
CWE ID: CWE-190
|
static int readContigStripsIntoBuffer (TIFF* in, uint8* buf)
{
uint8* bufp = buf;
int32 bytes_read = 0;
uint32 strip, nstrips = TIFFNumberOfStrips(in);
uint32 stripsize = TIFFStripSize(in);
uint32 rows = 0;
uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
tsize_t scanline_size = TIFFScanlineSize(in);
if (scanline_size == 0) {
TIFFError("", "TIFF scanline size is zero!");
return 0;
}
for (strip = 0; strip < nstrips; strip++) {
bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1);
rows = bytes_read / scanline_size;
if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize))
TIFFError("", "Strip %d: read %lu bytes, strip size %lu",
(int)strip + 1, (unsigned long) bytes_read,
(unsigned long)stripsize);
if (bytes_read < 0 && !ignore) {
TIFFError("", "Error reading strip %lu after %lu rows",
(unsigned long) strip, (unsigned long)rows);
return 0;
}
bufp += bytes_read;
}
return 1;
} /* end readContigStripsIntoBuffer */
| 166,866
|
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: MediaElementAudioSourceHandler::MediaElementAudioSourceHandler(
AudioNode& node,
HTMLMediaElement& media_element)
: AudioHandler(kNodeTypeMediaElementAudioSource,
node,
node.context()->sampleRate()),
media_element_(media_element),
source_number_of_channels_(0),
source_sample_rate_(0),
passes_current_src_cors_access_check_(
PassesCurrentSrcCORSAccessCheck(media_element.currentSrc())),
maybe_print_cors_message_(!passes_current_src_cors_access_check_),
current_src_string_(media_element.currentSrc().GetString()) {
DCHECK(IsMainThread());
AddOutput(2);
if (Context()->GetExecutionContext()) {
task_runner_ = Context()->GetExecutionContext()->GetTaskRunner(
TaskType::kMediaElementEvent);
}
Initialize();
}
Commit Message: Redirect should not circumvent same-origin restrictions
Check whether we have access to the audio data when the format is set.
At this point we have enough information to determine this. The old approach
based on when the src was changed was incorrect because at the point, we
only know the new src; none of the response headers have been read yet.
This new approach also removes the incorrect message reported in 619114.
Bug: 826552, 619114
Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6
Reviewed-on: https://chromium-review.googlesource.com/1069540
Commit-Queue: Raymond Toy <rtoy@chromium.org>
Reviewed-by: Yutaka Hirano <yhirano@chromium.org>
Reviewed-by: Hongchan Choi <hongchan@chromium.org>
Cr-Commit-Position: refs/heads/master@{#564313}
CWE ID: CWE-20
|
MediaElementAudioSourceHandler::MediaElementAudioSourceHandler(
AudioNode& node,
HTMLMediaElement& media_element)
: AudioHandler(kNodeTypeMediaElementAudioSource,
node,
node.context()->sampleRate()),
media_element_(media_element),
source_number_of_channels_(0),
source_sample_rate_(0),
is_origin_tainted_(false) {
DCHECK(IsMainThread());
AddOutput(2);
if (Context()->GetExecutionContext()) {
task_runner_ = Context()->GetExecutionContext()->GetTaskRunner(
TaskType::kMediaElementEvent);
}
Initialize();
}
| 173,144
|
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: void* H264SwDecMalloc(u32 size) {
return malloc(size);
}
Commit Message: h264dec: check for overflows when calculating allocation size.
Bug: 27855419
Change-Id: Idabedca52913ec31ea5cb6a6109ab94e3fb2badd
CWE ID: CWE-119
|
void* H264SwDecMalloc(u32 size) {
void* H264SwDecMalloc(u32 size, u32 num) {
if (size > UINT32_MAX / num) {
ALOGE("can't allocate %u * %u bytes", size, num);
android_errorWriteLog(0x534e4554, "27855419");
return NULL;
}
return malloc(size * num);
}
| 173,875
|
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 RunMemCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 1000;
DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, input_extreme_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs);
for (int i = 0; i < count_test_block; ++i) {
for (int j = 0; j < kNumCoeffs; ++j) {
input_block[j] = rnd.Rand8() - rnd.Rand8();
input_extreme_block[j] = rnd.Rand8() % 2 ? 255 : -255;
}
if (i == 0)
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = 255;
if (i == 1)
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = -255;
fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_);
REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block,
output_block, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
EXPECT_EQ(output_block[j], output_ref_block[j]);
EXPECT_GE(4 * DCT_MAX_VALUE, abs(output_block[j]))
<< "Error: 16x16 FDCT has coefficient larger than 4*DCT_MAX_VALUE";
}
}
}
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 RunMemCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 1000;
DECLARE_ALIGNED(16, int16_t, input_extreme_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, output_ref_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, output_block[kNumCoeffs]);
for (int i = 0; i < count_test_block; ++i) {
// Initialize a test block with input range [-mask_, mask_].
for (int j = 0; j < kNumCoeffs; ++j) {
input_extreme_block[j] = rnd.Rand8() % 2 ? mask_ : -mask_;
}
if (i == 0) {
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = mask_;
} else if (i == 1) {
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = -mask_;
}
fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_);
ASM_REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block,
output_block, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
EXPECT_EQ(output_block[j], output_ref_block[j]);
EXPECT_GE(4 * DCT_MAX_VALUE << (bit_depth_ - 8), abs(output_block[j]))
<< "Error: 16x16 FDCT has coefficient larger than 4*DCT_MAX_VALUE";
}
}
}
| 174,526
|
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 mem_write(jas_stream_obj_t *obj, char *buf, int cnt)
{
int n;
int ret;
jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
long newbufsize;
long newpos;
assert(buf);
assert(cnt >= 0);
JAS_DBGLOG(100, ("mem_write(%p, %p, %d)\n", obj, buf, cnt));
newpos = m->pos_ + cnt;
if (newpos > m->bufsize_ && m->growable_) {
newbufsize = m->bufsize_;
while (newbufsize < newpos) {
newbufsize <<= 1;
assert(newbufsize >= 0);
}
JAS_DBGLOG(100, ("mem_write resizing from %d to %z\n", m->bufsize_,
newbufsize));
JAS_DBGLOG(100, ("mem_write resizing from %d to %ul\n", m->bufsize_,
JAS_CAST(unsigned long, newbufsize)));
if (mem_resize(m, newbufsize)) {
return -1;
}
}
if (m->pos_ > m->len_) {
/* The current position is beyond the end of the file, so
pad the file to the current position with zeros. */
n = JAS_MIN(m->pos_, m->bufsize_) - m->len_;
if (n > 0) {
memset(&m->buf_[m->len_], 0, n);
m->len_ += n;
}
if (m->pos_ != m->len_) {
/* The buffer is not big enough. */
return 0;
}
}
n = m->bufsize_ - m->pos_;
ret = JAS_MIN(n, cnt);
if (ret > 0) {
memcpy(&m->buf_[m->pos_], buf, ret);
m->pos_ += ret;
}
if (m->pos_ > m->len_) {
m->len_ = m->pos_;
}
assert(ret == cnt);
return ret;
}
Commit Message: Made some changes to the I/O stream library for memory streams.
There were a number of potential problems due to the possibility
of integer overflow.
Changed some integral types to the larger types size_t or ssize_t.
For example, the function mem_resize now takes the buffer size parameter
as a size_t.
Added a new function jas_stream_memopen2, which takes a
buffer size specified as a size_t instead of an int.
This can be used in jas_image_cmpt_create to avoid potential
overflow problems.
Added a new function jas_deprecated to warn about reliance on
deprecated library behavior.
CWE ID: CWE-190
|
static int mem_write(jas_stream_obj_t *obj, char *buf, int cnt)
{
size_t n;
int ret;
jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
size_t newbufsize;
size_t newpos;
assert(buf);
assert(cnt >= 0);
JAS_DBGLOG(100, ("mem_write(%p, %p, %d)\n", obj, buf, cnt));
newpos = m->pos_ + cnt;
if (newpos > m->bufsize_ && m->growable_) {
newbufsize = m->bufsize_;
while (newbufsize < newpos) {
//newbufsize <<= 1;
if (!jas_safe_size_mul(newbufsize, 2, &newbufsize)) {
JAS_DBGLOG(100, ("new buffer size would cause overflow\n"));
return -1;
}
}
JAS_DBGLOG(100, ("mem_write resizing from %d to %zu\n", m->bufsize_,
newbufsize));
assert(newbufsize > 0);
if (mem_resize(m, newbufsize)) {
return -1;
}
}
if (m->pos_ > m->len_) {
/* The current position is beyond the end of the file, so
pad the file to the current position with zeros. */
n = JAS_MIN(m->pos_, m->bufsize_) - m->len_;
if (n > 0) {
memset(&m->buf_[m->len_], 0, n);
m->len_ += n;
}
if (m->pos_ != m->len_) {
/* The buffer is not big enough. */
return 0;
}
}
n = m->bufsize_ - m->pos_;
ret = JAS_MIN(n, cnt);
if (ret > 0) {
memcpy(&m->buf_[m->pos_], buf, ret);
m->pos_ += ret;
}
if (m->pos_ > m->len_) {
m->len_ = m->pos_;
}
assert(ret == cnt);
return ret;
}
| 168,752
|
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 put_chars(u32 vtermno, const char *buf, int count)
{
struct port *port;
struct scatterlist sg[1];
if (unlikely(early_put_chars))
return early_put_chars(vtermno, buf, count);
port = find_port_by_vtermno(vtermno);
if (!port)
return -EPIPE;
sg_init_one(sg, buf, count);
return __send_to_port(port, sg, 1, count, (void *)buf, false);
}
Commit Message: virtio-console: avoid DMA from stack
put_chars() stuffs the buffer it gets into an sg, but that buffer may be
on the stack. This breaks with CONFIG_VMAP_STACK=y (for me, it
manifested as printks getting turned into NUL bytes).
Signed-off-by: Omar Sandoval <osandov@fb.com>
Signed-off-by: Michael S. Tsirkin <mst@redhat.com>
Reviewed-by: Amit Shah <amit.shah@redhat.com>
CWE ID: CWE-119
|
static int put_chars(u32 vtermno, const char *buf, int count)
{
struct port *port;
struct scatterlist sg[1];
void *data;
int ret;
if (unlikely(early_put_chars))
return early_put_chars(vtermno, buf, count);
port = find_port_by_vtermno(vtermno);
if (!port)
return -EPIPE;
data = kmemdup(buf, count, GFP_ATOMIC);
if (!data)
return -ENOMEM;
sg_init_one(sg, data, count);
ret = __send_to_port(port, sg, 1, count, data, false);
kfree(data);
return ret;
}
| 168,219
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.