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: void RenderWidgetHostViewAura::CopyFromCompositingSurfaceFinished(
base::WeakPtr<RenderWidgetHostViewAura> render_widget_host_view,
const base::Callback<void(bool)>& callback,
bool result) {
callback.Run(result);
if (!render_widget_host_view.get())
return;
--render_widget_host_view->pending_thumbnail_tasks_;
render_widget_host_view->AdjustSurfaceProtection();
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
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:
|
void RenderWidgetHostViewAura::CopyFromCompositingSurfaceFinished(
base::WeakPtr<RenderWidgetHostViewAura> render_widget_host_view,
const base::Callback<void(bool)>& callback,
bool result) {
callback.Run(result);
if (!render_widget_host_view.get())
return;
--render_widget_host_view->pending_thumbnail_tasks_;
}
| 171,378
|
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 Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) {
assert(pCluster);
assert(pCluster->m_index < 0);
assert(idx >= m_clusterCount);
const long count = m_clusterCount + m_clusterPreloadCount;
long& size = m_clusterSize;
assert(size >= count);
if (count >= size) {
const long n = (size <= 0) ? 2048 : 2 * size;
Cluster** const qq = new Cluster* [n];
Cluster** q = qq;
Cluster** p = m_clusters;
Cluster** const pp = p + count;
while (p != pp)
*q++ = *p++;
delete[] m_clusters;
m_clusters = qq;
size = n;
}
assert(m_clusters);
Cluster** const p = m_clusters + idx;
Cluster** q = m_clusters + count;
assert(q >= p);
assert(q < (m_clusters + size));
while (q > p) {
Cluster** const qq = q - 1;
assert((*qq)->m_index < 0);
*q = *qq;
q = qq;
}
m_clusters[idx] = pCluster;
++m_clusterPreloadCount;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) {
bool Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) {
assert(pCluster);
assert(pCluster->m_index < 0);
assert(idx >= m_clusterCount);
const long count = m_clusterCount + m_clusterPreloadCount;
long& size = m_clusterSize;
assert(size >= count);
if (count >= size) {
const long n = (size <= 0) ? 2048 : 2 * size;
Cluster** const qq = new (std::nothrow) Cluster*[n];
if (qq == NULL)
return false;
Cluster** q = qq;
Cluster** p = m_clusters;
Cluster** const pp = p + count;
while (p != pp)
*q++ = *p++;
delete[] m_clusters;
m_clusters = qq;
size = n;
}
assert(m_clusters);
Cluster** const p = m_clusters + idx;
Cluster** q = m_clusters + count;
assert(q >= p);
assert(q < (m_clusters + size));
while (q > p) {
Cluster** const qq = q - 1;
assert((*qq)->m_index < 0);
*q = *qq;
q = qq;
}
m_clusters[idx] = pCluster;
++m_clusterPreloadCount;
return true;
}
| 173,860
|
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 wifi_cleanup(wifi_handle handle, wifi_cleaned_up_handler handler)
{
hal_info *info = getHalInfo(handle);
char buf[64];
info->cleaned_up_handler = handler;
if (write(info->cleanup_socks[0], "Exit", 4) < 1) {
ALOGE("could not write to the cleanup socket");
} else {
memset(buf, 0, sizeof(buf));
int result = read(info->cleanup_socks[0], buf, sizeof(buf));
ALOGE("%s: Read after POLL returned %d, error no = %d", __FUNCTION__, result, errno);
if (strncmp(buf, "Done", 4) == 0) {
ALOGE("Event processing terminated");
} else {
ALOGD("Rx'ed %s", buf);
}
}
info->clean_up = true;
pthread_mutex_lock(&info->cb_lock);
int bad_commands = 0;
for (int i = 0; i < info->num_event_cb; i++) {
cb_info *cbi = &(info->event_cb[i]);
WifiCommand *cmd = (WifiCommand *)cbi->cb_arg;
ALOGI("Command left in event_cb %p:%s", cmd, (cmd ? cmd->getType(): ""));
}
while (info->num_cmd > bad_commands) {
int num_cmd = info->num_cmd;
cmd_info *cmdi = &(info->cmd[bad_commands]);
WifiCommand *cmd = cmdi->cmd;
if (cmd != NULL) {
ALOGI("Cancelling command %p:%s", cmd, cmd->getType());
pthread_mutex_unlock(&info->cb_lock);
cmd->cancel();
pthread_mutex_lock(&info->cb_lock);
/* release reference added when command is saved */
cmd->releaseRef();
if (num_cmd == info->num_cmd) {
ALOGI("Cancelling command %p:%s did not work", cmd, (cmd ? cmd->getType(): ""));
bad_commands++;
}
}
}
for (int i = 0; i < info->num_event_cb; i++) {
cb_info *cbi = &(info->event_cb[i]);
WifiCommand *cmd = (WifiCommand *)cbi->cb_arg;
ALOGE("Leaked command %p", cmd);
}
pthread_mutex_unlock(&info->cb_lock);
internal_cleaned_up_handler(handle);
}
Commit Message: Fix use-after-free in wifi_cleanup()
Release reference to cmd only after possibly calling getType().
BUG: 25753768
Change-Id: Id2156ce51acec04e8364706cf7eafc7d4adae9eb
(cherry picked from commit d7f3cb9915d9ac514393d0ad7767662958054b8f https://googleplex-android-review.git.corp.google.com/#/c/815223)
CWE ID: CWE-264
|
void wifi_cleanup(wifi_handle handle, wifi_cleaned_up_handler handler)
{
hal_info *info = getHalInfo(handle);
char buf[64];
info->cleaned_up_handler = handler;
if (write(info->cleanup_socks[0], "Exit", 4) < 1) {
ALOGE("could not write to the cleanup socket");
} else {
memset(buf, 0, sizeof(buf));
int result = read(info->cleanup_socks[0], buf, sizeof(buf));
ALOGE("%s: Read after POLL returned %d, error no = %d", __FUNCTION__, result, errno);
if (strncmp(buf, "Done", 4) == 0) {
ALOGE("Event processing terminated");
} else {
ALOGD("Rx'ed %s", buf);
}
}
info->clean_up = true;
pthread_mutex_lock(&info->cb_lock);
int bad_commands = 0;
for (int i = 0; i < info->num_event_cb; i++) {
cb_info *cbi = &(info->event_cb[i]);
WifiCommand *cmd = (WifiCommand *)cbi->cb_arg;
ALOGI("Command left in event_cb %p:%s", cmd, (cmd ? cmd->getType(): ""));
}
while (info->num_cmd > bad_commands) {
int num_cmd = info->num_cmd;
cmd_info *cmdi = &(info->cmd[bad_commands]);
WifiCommand *cmd = cmdi->cmd;
if (cmd != NULL) {
ALOGI("Cancelling command %p:%s", cmd, cmd->getType());
pthread_mutex_unlock(&info->cb_lock);
cmd->cancel();
pthread_mutex_lock(&info->cb_lock);
if (num_cmd == info->num_cmd) {
ALOGI("Cancelling command %p:%s did not work", cmd, (cmd ? cmd->getType(): ""));
bad_commands++;
}
/* release reference added when command is saved */
cmd->releaseRef();
}
}
for (int i = 0; i < info->num_event_cb; i++) {
cb_info *cbi = &(info->event_cb[i]);
WifiCommand *cmd = (WifiCommand *)cbi->cb_arg;
ALOGE("Leaked command %p", cmd);
}
pthread_mutex_unlock(&info->cb_lock);
internal_cleaned_up_handler(handle);
}
| 173,964
|
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: exit_ext2_xattr(void)
{
mb_cache_destroy(ext2_xattr_cache);
}
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
CWE ID: CWE-19
|
exit_ext2_xattr(void)
void ext2_xattr_destroy_cache(struct mb2_cache *cache)
{
if (cache)
mb2_cache_destroy(cache);
}
| 169,976
|
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 store_asoundrc(void) {
fs_build_mnt_dir();
char *src;
char *dest = RUN_ASOUNDRC_FILE;
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0644);
fclose(fp);
}
if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
/* coverity[toctou] */
char* rp = realpath(src, NULL);
if (!rp) {
fprintf(stderr, "Error: Cannot access %s\n", src);
exit(1);
}
if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) {
fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n");
exit(1);
}
free(rp);
}
copy_file_as_user(src, dest, getuid(), getgid(), 0644);
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
Commit Message: security fix
CWE ID: CWE-269
|
static int store_asoundrc(void) {
fs_build_mnt_dir();
char *src;
char *dest = RUN_ASOUNDRC_FILE;
// create an empty file as root, and change ownership to user
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0644);
fclose(fp);
}
if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
/* coverity[toctou] */
char* rp = realpath(src, NULL);
if (!rp) {
fprintf(stderr, "Error: Cannot access %s\n", src);
exit(1);
}
if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) {
fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n");
exit(1);
}
free(rp);
}
copy_file_as_user(src, dest, getuid(), getgid(), 0644);
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
| 168,372
|
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: mrb_obj_clone(mrb_state *mrb, mrb_value self)
{
struct RObject *p;
mrb_value clone;
if (mrb_immediate_p(self)) {
mrb_raisef(mrb, E_TYPE_ERROR, "can't clone %S", self);
}
if (mrb_type(self) == MRB_TT_SCLASS) {
mrb_raise(mrb, E_TYPE_ERROR, "can't clone singleton class");
}
p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self));
p->c = mrb_singleton_class_clone(mrb, self);
mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c);
clone = mrb_obj_value(p);
init_copy(mrb, clone, self);
p->flags = mrb_obj_ptr(self)->flags;
return clone;
}
Commit Message: Allow `Object#clone` to copy frozen status only; fix #4036
Copying all flags from the original object may overwrite the clone's
flags e.g. the embedded flag.
CWE ID: CWE-476
|
mrb_obj_clone(mrb_state *mrb, mrb_value self)
{
struct RObject *p;
mrb_value clone;
if (mrb_immediate_p(self)) {
mrb_raisef(mrb, E_TYPE_ERROR, "can't clone %S", self);
}
if (mrb_type(self) == MRB_TT_SCLASS) {
mrb_raise(mrb, E_TYPE_ERROR, "can't clone singleton class");
}
p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self));
p->c = mrb_singleton_class_clone(mrb, self);
mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c);
clone = mrb_obj_value(p);
init_copy(mrb, clone, self);
p->flags |= mrb_obj_ptr(self)->flags & MRB_FLAG_IS_FROZEN;
return clone;
}
| 169,202
|
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 r_bin_dwarf_dump_debug_info(FILE *f, const RBinDwarfDebugInfo *inf) {
size_t i, j, k;
RBinDwarfDIE *dies;
RBinDwarfAttrValue *values;
if (!inf || !f) {
return;
}
for (i = 0; i < inf->length; i++) {
fprintf (f, " Compilation Unit @ offset 0x%"PFMT64x":\n", inf->comp_units [i].offset);
fprintf (f, " Length: 0x%x\n", inf->comp_units [i].hdr.length);
fprintf (f, " Version: %d\n", inf->comp_units [i].hdr.version);
fprintf (f, " Abbrev Offset: 0x%x\n", inf->comp_units [i].hdr.abbrev_offset);
fprintf (f, " Pointer Size: %d\n", inf->comp_units [i].hdr.pointer_size);
dies = inf->comp_units[i].dies;
for (j = 0; j < inf->comp_units[i].length; j++) {
fprintf (f, " Abbrev Number: %"PFMT64u" ", dies[j].abbrev_code);
if (dies[j].tag && dies[j].tag <= DW_TAG_volatile_type &&
dwarf_tag_name_encodings[dies[j].tag]) {
fprintf (f, "(%s)\n", dwarf_tag_name_encodings[dies[j].tag]);
} else {
fprintf (f, "(Unknown abbrev tag)\n");
}
if (!dies[j].abbrev_code) {
continue;
}
values = dies[j].attr_values;
for (k = 0; k < dies[j].length; k++) {
if (!values[k].name)
continue;
if (values[k].name < DW_AT_vtable_elem_location &&
dwarf_attr_encodings[values[k].name]) {
fprintf (f, " %-18s : ", dwarf_attr_encodings[values[k].name]);
} else {
fprintf (f, " TODO\t");
}
r_bin_dwarf_dump_attr_value (&values[k], f);
fprintf (f, "\n");
}
}
}
}
Commit Message: Fix #8813 - segfault in dwarf parser
CWE ID: CWE-125
|
static void r_bin_dwarf_dump_debug_info(FILE *f, const RBinDwarfDebugInfo *inf) {
size_t i, j, k;
RBinDwarfDIE *dies;
RBinDwarfAttrValue *values;
if (!inf || !f) {
return;
}
for (i = 0; i < inf->length; i++) {
fprintf (f, " Compilation Unit @ offset 0x%"PFMT64x":\n", inf->comp_units [i].offset);
fprintf (f, " Length: 0x%x\n", inf->comp_units [i].hdr.length);
fprintf (f, " Version: %d\n", inf->comp_units [i].hdr.version);
fprintf (f, " Abbrev Offset: 0x%x\n", inf->comp_units [i].hdr.abbrev_offset);
fprintf (f, " Pointer Size: %d\n", inf->comp_units [i].hdr.pointer_size);
dies = inf->comp_units[i].dies;
for (j = 0; j < inf->comp_units[i].length; j++) {
fprintf (f, " Abbrev Number: %"PFMT64u" ", dies[j].abbrev_code);
if (dies[j].tag && dies[j].tag <= DW_TAG_volatile_type &&
dwarf_tag_name_encodings[dies[j].tag]) {
fprintf (f, "(%s)\n", dwarf_tag_name_encodings[dies[j].tag]);
} else {
fprintf (f, "(Unknown abbrev tag)\n");
}
if (!dies[j].abbrev_code) {
continue;
}
values = dies[j].attr_values;
for (k = 0; k < dies[j].length; k++) {
if (!values[k].name) {
continue;
}
if (values[k].name < DW_AT_vtable_elem_location &&
dwarf_attr_encodings[values[k].name]) {
fprintf (f, " %-18s : ", dwarf_attr_encodings[values[k].name]);
} else {
fprintf (f, " TODO\t");
}
r_bin_dwarf_dump_attr_value (&values[k], f);
fprintf (f, "\n");
}
}
}
}
| 167,668
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int jp2_bpcc_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_bpcc_t *bpcc = &box->data.bpcc;
unsigned int i;
bpcc->numcmpts = box->datalen;
if (!(bpcc->bpcs = jas_alloc2(bpcc->numcmpts, sizeof(uint_fast8_t)))) {
return -1;
}
for (i = 0; i < bpcc->numcmpts; ++i) {
if (jp2_getuint8(in, &bpcc->bpcs[i])) {
return -1;
}
}
return 0;
}
Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder.
Also, added some comments marking I/O stream interfaces that probably
need to be changed (in the long term) to fix integer overflow problems.
CWE ID: CWE-476
|
static int jp2_bpcc_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_bpcc_t *bpcc = &box->data.bpcc;
unsigned int i;
bpcc->bpcs = 0;
bpcc->numcmpts = box->datalen;
if (!(bpcc->bpcs = jas_alloc2(bpcc->numcmpts, sizeof(uint_fast8_t)))) {
return -1;
}
for (i = 0; i < bpcc->numcmpts; ++i) {
if (jp2_getuint8(in, &bpcc->bpcs[i])) {
return -1;
}
}
return 0;
}
| 168,320
|
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 lo_release(struct gendisk *disk, fmode_t mode)
{
struct loop_device *lo = disk->private_data;
int err;
if (atomic_dec_return(&lo->lo_refcnt))
return;
mutex_lock(&lo->lo_ctl_mutex);
if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
/*
* In autoclear mode, stop the loop thread
* and remove configuration after last close.
*/
err = loop_clr_fd(lo);
if (!err)
return;
} else if (lo->lo_state == Lo_bound) {
/*
* Otherwise keep thread (if running) and config,
* but flush possible ongoing bios in thread.
*/
blk_mq_freeze_queue(lo->lo_queue);
blk_mq_unfreeze_queue(lo->lo_queue);
}
mutex_unlock(&lo->lo_ctl_mutex);
}
Commit Message: loop: fix concurrent lo_open/lo_release
范龙飞 reports that KASAN can report a use-after-free in __lock_acquire.
The reason is due to insufficient serialization in lo_release(), which
will continue to use the loop device even after it has decremented the
lo_refcnt to zero.
In the meantime, another process can come in, open the loop device
again as it is being shut down. Confusion ensues.
Reported-by: 范龙飞 <long7573@126.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Jens Axboe <axboe@kernel.dk>
CWE ID: CWE-416
|
static void lo_release(struct gendisk *disk, fmode_t mode)
static void __lo_release(struct loop_device *lo)
{
int err;
if (atomic_dec_return(&lo->lo_refcnt))
return;
mutex_lock(&lo->lo_ctl_mutex);
if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
/*
* In autoclear mode, stop the loop thread
* and remove configuration after last close.
*/
err = loop_clr_fd(lo);
if (!err)
return;
} else if (lo->lo_state == Lo_bound) {
/*
* Otherwise keep thread (if running) and config,
* but flush possible ongoing bios in thread.
*/
blk_mq_freeze_queue(lo->lo_queue);
blk_mq_unfreeze_queue(lo->lo_queue);
}
mutex_unlock(&lo->lo_ctl_mutex);
}
| 169,352
|
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 key_notify_policy_flush(const struct km_event *c)
{
struct sk_buff *skb_out;
struct sadb_msg *hdr;
skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
if (!skb_out)
return -ENOBUFS;
hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg));
hdr->sadb_msg_type = SADB_X_SPDFLUSH;
hdr->sadb_msg_seq = c->seq;
hdr->sadb_msg_pid = c->portid;
hdr->sadb_msg_version = PF_KEY_V2;
hdr->sadb_msg_errno = (uint8_t) 0;
hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net);
return 0;
}
Commit Message: af_key: initialize satype in key_notify_policy_flush()
This field was left uninitialized. Some user daemons perform check against this
field.
Signed-off-by: Nicolas Dichtel <nicolas.dichtel@6wind.com>
Signed-off-by: Steffen Klassert <steffen.klassert@secunet.com>
CWE ID: CWE-119
|
static int key_notify_policy_flush(const struct km_event *c)
{
struct sk_buff *skb_out;
struct sadb_msg *hdr;
skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
if (!skb_out)
return -ENOBUFS;
hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg));
hdr->sadb_msg_type = SADB_X_SPDFLUSH;
hdr->sadb_msg_seq = c->seq;
hdr->sadb_msg_pid = c->portid;
hdr->sadb_msg_version = PF_KEY_V2;
hdr->sadb_msg_errno = (uint8_t) 0;
hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC;
hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net);
return 0;
}
| 166,073
|
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 Segment::LoadCluster(
long long& pos,
long& len)
{
for (;;)
{
const long result = DoLoadCluster(pos, len);
if (result <= 1)
return result;
}
}
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 Segment::LoadCluster(
if (result <= 1)
return result;
}
}
long Segment::DoLoadCluster(long long& pos, long& len) {
if (m_pos < 0)
return DoLoadClusterUnknownSize(pos, len);
long long total, avail;
long status = m_pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
long long cluster_off = -1; // offset relative to start of segment
long long cluster_size = -1; // size of cluster payload
for (;;) {
if ((total >= 0) && (m_pos >= total))
return 1; // no more clusters
if ((segment_stop >= 0) && (m_pos >= segment_stop))
return 1; // no more clusters
pos = m_pos;
// Read ID
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
| 174,396
|
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: kdc_process_s4u_x509_user(krb5_context context,
krb5_kdc_req *request,
krb5_pa_data *pa_data,
krb5_keyblock *tgs_subkey,
krb5_keyblock *tgs_session,
krb5_pa_s4u_x509_user **s4u_x509_user,
const char **status)
{
krb5_error_code code;
krb5_data req_data;
req_data.length = pa_data->length;
req_data.data = (char *)pa_data->contents;
code = decode_krb5_pa_s4u_x509_user(&req_data, s4u_x509_user);
if (code)
return code;
code = verify_s4u_x509_user_checksum(context,
tgs_subkey ? tgs_subkey :
tgs_session,
&req_data,
request->nonce, *s4u_x509_user);
if (code) {
*status = "INVALID_S4U2SELF_CHECKSUM";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return code;
}
if (krb5_princ_size(context, (*s4u_x509_user)->user_id.user) == 0 ||
(*s4u_x509_user)->user_id.subject_cert.length != 0) {
*status = "INVALID_S4U2SELF_REQUEST";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
}
return 0;
}
Commit Message: Prevent KDC unset status assertion failures
Assign status values if S4U2Self padata fails to decode, if an
S4U2Proxy request uses invalid KDC options, or if an S4U2Proxy request
uses an evidence ticket which does not match the canonicalized request
server principal name. Reported by Samuel Cabrero.
If a status value is not assigned during KDC processing, default to
"UNKNOWN_REASON" rather than failing an assertion. This change will
prevent future denial of service bugs due to similar mistakes, and
will allow us to omit assigning status values for unlikely errors such
as small memory allocation failures.
CVE-2017-11368:
In MIT krb5 1.7 and later, an authenticated attacker can cause an
assertion failure in krb5kdc by sending an invalid S4U2Self or
S4U2Proxy request.
CVSSv3 Vector: AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H/E:H/RL:O/RC:C
ticket: 8599 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-617
|
kdc_process_s4u_x509_user(krb5_context context,
krb5_kdc_req *request,
krb5_pa_data *pa_data,
krb5_keyblock *tgs_subkey,
krb5_keyblock *tgs_session,
krb5_pa_s4u_x509_user **s4u_x509_user,
const char **status)
{
krb5_error_code code;
krb5_data req_data;
req_data.length = pa_data->length;
req_data.data = (char *)pa_data->contents;
code = decode_krb5_pa_s4u_x509_user(&req_data, s4u_x509_user);
if (code) {
*status = "DECODE_PA_S4U_X509_USER";
return code;
}
code = verify_s4u_x509_user_checksum(context,
tgs_subkey ? tgs_subkey :
tgs_session,
&req_data,
request->nonce, *s4u_x509_user);
if (code) {
*status = "INVALID_S4U2SELF_CHECKSUM";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return code;
}
if (krb5_princ_size(context, (*s4u_x509_user)->user_id.user) == 0 ||
(*s4u_x509_user)->user_id.subject_cert.length != 0) {
*status = "INVALID_S4U2SELF_REQUEST";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
}
return 0;
}
| 168,043
|
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: gimp_write_and_read_file (Gimp *gimp,
gboolean with_unusual_stuff,
gboolean compat_paths,
gboolean use_gimp_2_8_features)
{
GimpImage *image;
GimpImage *loaded_image;
GimpPlugInProcedure *proc;
gchar *filename;
GFile *file;
/* Create the image */
image = gimp_create_mainimage (gimp,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
/* Assert valid state */
gimp_assert_mainimage (image,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
/* Write to file */
filename = g_build_filename (g_get_tmp_dir (), "gimp-test.xcf", NULL);
file = g_file_new_for_path (filename);
g_free (filename);
proc = gimp_plug_in_manager_file_procedure_find (image->gimp->plug_in_manager,
GIMP_FILE_PROCEDURE_GROUP_SAVE,
file,
NULL /*error*/);
file_save (gimp,
image,
NULL /*progress*/,
file,
proc,
GIMP_RUN_NONINTERACTIVE,
FALSE /*change_saved_state*/,
FALSE /*export_backward*/,
FALSE /*export_forward*/,
NULL /*error*/);
/* Load from file */
loaded_image = gimp_test_load_image (image->gimp, file);
/* Assert on the loaded file. If success, it means that there is no
* significant information loss when we wrote the image to a file
* and loaded it again
*/
gimp_assert_mainimage (loaded_image,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
g_file_delete (file, NULL, NULL);
g_object_unref (file);
}
Commit Message: Issue #1689: create unique temporary file with g_file_open_tmp().
Not sure this is really solving the issue reported, which is that
`g_get_tmp_dir()` uses environment variables (yet as g_file_open_tmp()
uses g_get_tmp_dir()…). But at least g_file_open_tmp() should create
unique temporary files, which prevents overriding existing files (which
is most likely the only real attack possible here, or at least the only
one I can think of unless some weird vulnerabilities exist in glib).
CWE ID: CWE-20
|
gimp_write_and_read_file (Gimp *gimp,
gboolean with_unusual_stuff,
gboolean compat_paths,
gboolean use_gimp_2_8_features)
{
GimpImage *image;
GimpImage *loaded_image;
GimpPlugInProcedure *proc;
gchar *filename = NULL;
gint file_handle;
GFile *file;
/* Create the image */
image = gimp_create_mainimage (gimp,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
/* Assert valid state */
gimp_assert_mainimage (image,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
/* Write to file */
file_handle = g_file_open_tmp ("gimp-test-XXXXXX.xcf", &filename, NULL);
g_assert (file_handle != -1);
close (file_handle);
file = g_file_new_for_path (filename);
g_free (filename);
proc = gimp_plug_in_manager_file_procedure_find (image->gimp->plug_in_manager,
GIMP_FILE_PROCEDURE_GROUP_SAVE,
file,
NULL /*error*/);
file_save (gimp,
image,
NULL /*progress*/,
file,
proc,
GIMP_RUN_NONINTERACTIVE,
FALSE /*change_saved_state*/,
FALSE /*export_backward*/,
FALSE /*export_forward*/,
NULL /*error*/);
/* Load from file */
loaded_image = gimp_test_load_image (image->gimp, file);
/* Assert on the loaded file. If success, it means that there is no
* significant information loss when we wrote the image to a file
* and loaded it again
*/
gimp_assert_mainimage (loaded_image,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
g_file_delete (file, NULL, NULL);
g_object_unref (file);
}
| 169,187
|
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 Document::InitContentSecurityPolicy(
ContentSecurityPolicy* csp,
const ContentSecurityPolicy* policy_to_inherit) {
SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create());
if (policy_to_inherit) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
} else if (frame_) {
Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent()
: frame_->Client()->Opener();
if (inherit_from && frame_ != inherit_from) {
DCHECK(inherit_from->GetSecurityContext() &&
inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
policy_to_inherit =
inherit_from->GetSecurityContext()->GetContentSecurityPolicy();
if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() ||
url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
}
}
}
if (policy_to_inherit && IsPluginDocument())
GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit);
GetContentSecurityPolicy()->BindToExecutionContext(this);
}
Commit Message: Fixed bug where PlzNavigate CSP in a iframe did not get the inherited CSP
When inheriting the CSP from a parent document to a local-scheme CSP,
it does not always get propagated to the PlzNavigate CSP. This means
that PlzNavigate CSP checks (like `frame-src`) would be ran against
a blank policy instead of the proper inherited policy.
Bug: 778658
Change-Id: I61bb0d432e1cea52f199e855624cb7b3078f56a9
Reviewed-on: https://chromium-review.googlesource.com/765969
Commit-Queue: Andy Paicu <andypaicu@chromium.org>
Reviewed-by: Mike West <mkwst@chromium.org>
Cr-Commit-Position: refs/heads/master@{#518245}
CWE ID: CWE-732
|
void Document::InitContentSecurityPolicy(
ContentSecurityPolicy* csp,
const ContentSecurityPolicy* policy_to_inherit) {
SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create());
GetContentSecurityPolicy()->BindToExecutionContext(this);
if (policy_to_inherit) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
} else if (frame_) {
Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent()
: frame_->Client()->Opener();
if (inherit_from && frame_ != inherit_from) {
DCHECK(inherit_from->GetSecurityContext() &&
inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
policy_to_inherit =
inherit_from->GetSecurityContext()->GetContentSecurityPolicy();
if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() ||
url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
}
}
}
if (policy_to_inherit && IsPluginDocument())
GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit);
}
| 172,683
|
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 InspectorHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
host_ = frame_host;
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
void InspectorHandler::SetRenderer(RenderProcessHost* process_host,
void InspectorHandler::SetRenderer(int process_host_id,
RenderFrameHostImpl* frame_host) {
host_ = frame_host;
}
| 172,748
|
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 TabStripModel::InternalCloseTabs(const std::vector<int>& indices,
uint32 close_types) {
if (indices.empty())
return true;
bool retval = true;
std::vector<TabContentsWrapper*> tabs;
for (size_t i = 0; i < indices.size(); ++i)
tabs.push_back(GetContentsAt(indices[i]));
if (browser_shutdown::GetShutdownType() == browser_shutdown::NOT_VALID) {
std::map<RenderProcessHost*, size_t> processes;
for (size_t i = 0; i < indices.size(); ++i) {
if (!delegate_->CanCloseContentsAt(indices[i])) {
retval = false;
continue;
}
TabContentsWrapper* detached_contents = GetContentsAt(indices[i]);
RenderProcessHost* process =
detached_contents->tab_contents()->GetRenderProcessHost();
std::map<RenderProcessHost*, size_t>::iterator iter =
processes.find(process);
if (iter == processes.end()) {
processes[process] = 1;
} else {
iter->second++;
}
}
for (std::map<RenderProcessHost*, size_t>::iterator iter =
processes.begin();
iter != processes.end(); ++iter) {
iter->first->FastShutdownForPageCount(iter->second);
}
}
for (size_t i = 0; i < tabs.size(); ++i) {
TabContentsWrapper* detached_contents = tabs[i];
int index = GetIndexOfTabContents(detached_contents);
if (index == kNoTab)
continue;
detached_contents->tab_contents()->OnCloseStarted();
if (!delegate_->CanCloseContentsAt(index)) {
retval = false;
continue;
}
if (!detached_contents->tab_contents()->closed_by_user_gesture()) {
detached_contents->tab_contents()->set_closed_by_user_gesture(
close_types & CLOSE_USER_GESTURE);
}
if (delegate_->RunUnloadListenerBeforeClosing(detached_contents)) {
retval = false;
continue;
}
InternalCloseTab(detached_contents, index,
(close_types & CLOSE_CREATE_HISTORICAL_TAB) != 0);
}
return retval;
}
Commit Message: chromeos: fix bug where "aw snap" page replaces first tab if it was a NTP when closing window with > 1 tab.
BUG=chromium-os:12088
TEST=verify bug per bug report.
Review URL: http://codereview.chromium.org/6882058
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83031 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
bool TabStripModel::InternalCloseTabs(const std::vector<int>& indices,
bool TabStripModel::InternalCloseTabs(const std::vector<int>& in_indices,
uint32 close_types) {
if (in_indices.empty())
return true;
std::vector<int> indices(in_indices);
bool retval = delegate_->CanCloseContents(&indices);
if (indices.empty())
return retval;
std::vector<TabContentsWrapper*> tabs;
for (size_t i = 0; i < indices.size(); ++i)
tabs.push_back(GetContentsAt(indices[i]));
if (browser_shutdown::GetShutdownType() == browser_shutdown::NOT_VALID) {
std::map<RenderProcessHost*, size_t> processes;
for (size_t i = 0; i < indices.size(); ++i) {
TabContentsWrapper* detached_contents = GetContentsAt(indices[i]);
RenderProcessHost* process =
detached_contents->tab_contents()->GetRenderProcessHost();
std::map<RenderProcessHost*, size_t>::iterator iter =
processes.find(process);
if (iter == processes.end()) {
processes[process] = 1;
} else {
iter->second++;
}
}
for (std::map<RenderProcessHost*, size_t>::iterator iter =
processes.begin();
iter != processes.end(); ++iter) {
iter->first->FastShutdownForPageCount(iter->second);
}
}
for (size_t i = 0; i < tabs.size(); ++i) {
TabContentsWrapper* detached_contents = tabs[i];
int index = GetIndexOfTabContents(detached_contents);
if (index == kNoTab)
continue;
detached_contents->tab_contents()->OnCloseStarted();
if (!detached_contents->tab_contents()->closed_by_user_gesture()) {
detached_contents->tab_contents()->set_closed_by_user_gesture(
close_types & CLOSE_USER_GESTURE);
}
if (delegate_->RunUnloadListenerBeforeClosing(detached_contents)) {
retval = false;
continue;
}
InternalCloseTab(detached_contents, index,
(close_types & CLOSE_CREATE_HISTORICAL_TAB) != 0);
}
return retval;
}
| 170,302
|
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 RenderWidgetHostViewAura::AcceleratedSurfacePostSubBuffer(
const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params_in_pixel,
int gpu_host_id) {
surface_route_id_ = params_in_pixel.route_id;
if (params_in_pixel.protection_state_id &&
params_in_pixel.protection_state_id != protection_state_id_) {
DCHECK(!current_surface_);
InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, false, NULL);
return;
}
if (ShouldFastACK(params_in_pixel.surface_handle)) {
InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, false, NULL);
return;
}
current_surface_ = params_in_pixel.surface_handle;
released_front_lock_ = NULL;
DCHECK(current_surface_);
UpdateExternalTexture();
ui::Compositor* compositor = GetCompositor();
if (!compositor) {
InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, true, NULL);
} else {
DCHECK(image_transport_clients_.find(params_in_pixel.surface_handle) !=
image_transport_clients_.end());
gfx::Size surface_size_in_pixel =
image_transport_clients_[params_in_pixel.surface_handle]->size();
gfx::Rect rect_to_paint = ConvertRectToDIP(this, gfx::Rect(
params_in_pixel.x,
surface_size_in_pixel.height() - params_in_pixel.y -
params_in_pixel.height,
params_in_pixel.width,
params_in_pixel.height));
rect_to_paint.Inset(-1, -1);
rect_to_paint.Intersect(window_->bounds());
window_->SchedulePaintInRect(rect_to_paint);
can_lock_compositor_ = NO_PENDING_COMMIT;
on_compositing_did_commit_callbacks_.push_back(
base::Bind(&RenderWidgetHostViewAura::InsertSyncPointAndACK,
params_in_pixel.route_id,
gpu_host_id,
true));
if (!compositor->HasObserver(this))
compositor->AddObserver(this);
}
}
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:
|
void RenderWidgetHostViewAura::AcceleratedSurfacePostSubBuffer(
const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params_in_pixel,
int gpu_host_id) {
const gfx::Rect surface_rect =
gfx::Rect(gfx::Point(), params_in_pixel.surface_size);
gfx::Rect damage_rect(params_in_pixel.x,
params_in_pixel.y,
params_in_pixel.width,
params_in_pixel.height);
BufferPresentedParams ack_params(
params_in_pixel.route_id, gpu_host_id, params_in_pixel.surface_handle);
if (!SwapBuffersPrepare(surface_rect, damage_rect, &ack_params))
return;
SkRegion damage(RectToSkIRect(damage_rect));
if (!skipped_damage_.isEmpty()) {
damage.op(skipped_damage_, SkRegion::kUnion_Op);
skipped_damage_.setEmpty();
}
DCHECK(surface_rect.Contains(SkIRectToRect(damage.getBounds())));
ui::Texture* current_texture = image_transport_clients_[current_surface_];
const gfx::Size surface_size_in_pixel = params_in_pixel.surface_size;
DLOG_IF(ERROR, ack_params.texture_to_produce &&
ack_params.texture_to_produce->size() != current_texture->size() &&
SkIRectToRect(damage.getBounds()) != surface_rect) <<
"Expected full damage rect after size change";
if (ack_params.texture_to_produce && !previous_damage_.isEmpty() &&
ack_params.texture_to_produce->size() == current_texture->size()) {
ImageTransportFactory* factory = ImageTransportFactory::GetInstance();
GLHelper* gl_helper = factory->GetGLHelper();
gl_helper->CopySubBufferDamage(
current_texture->PrepareTexture(),
ack_params.texture_to_produce->PrepareTexture(),
damage,
previous_damage_);
}
previous_damage_ = damage;
ui::Compositor* compositor = GetCompositor();
if (compositor) {
gfx::Rect rect_to_paint = ConvertRectToDIP(this, gfx::Rect(
params_in_pixel.x,
surface_size_in_pixel.height() - params_in_pixel.y -
params_in_pixel.height,
params_in_pixel.width,
params_in_pixel.height));
rect_to_paint.Inset(-1, -1);
rect_to_paint.Intersect(window_->bounds());
window_->SchedulePaintInRect(rect_to_paint);
}
SwapBuffersCompleted(ack_params);
}
| 171,374
|
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 MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if ((layer_info->channel_info[channel].type < -1) &&
(layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0))
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
if (mask != (Image *) NULL)
{
SetImageType(mask,GrayscaleType,exception);
channel_image=mask;
}
}
offset=TellBlob(image);
status=MagickFalse;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
layer_info->mask.image=mask;
return(status);
}
Commit Message: Slightly different fix for #714
CWE ID: CWE-834
|
static MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if ((layer_info->channel_info[channel].type < -1) &&
(layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0))
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
if (mask != (Image *) NULL)
{
SetImageType(mask,GrayscaleType,exception);
channel_image=mask;
}
}
offset=TellBlob(image);
status=MagickFalse;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
layer_info->mask.image=mask;
return(status);
}
| 170,016
|
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 gatherSecurityPolicyViolationEventData(
SecurityPolicyViolationEventInit& init,
ExecutionContext* context,
const String& directiveText,
const ContentSecurityPolicy::DirectiveType& effectiveType,
const KURL& blockedURL,
const String& header,
RedirectStatus redirectStatus,
ContentSecurityPolicyHeaderType headerType,
ContentSecurityPolicy::ViolationType violationType,
int contextLine,
const String& scriptSource) {
if (effectiveType == ContentSecurityPolicy::DirectiveType::FrameAncestors) {
init.setDocumentURI(blockedURL.getString());
init.setBlockedURI(blockedURL.getString());
} else {
init.setDocumentURI(context->url().getString());
switch (violationType) {
case ContentSecurityPolicy::InlineViolation:
init.setBlockedURI("inline");
break;
case ContentSecurityPolicy::EvalViolation:
init.setBlockedURI("eval");
break;
case ContentSecurityPolicy::URLViolation:
init.setBlockedURI(stripURLForUseInReport(
context, blockedURL, redirectStatus, effectiveType));
break;
}
}
String effectiveDirective =
ContentSecurityPolicy::getDirectiveName(effectiveType);
init.setViolatedDirective(effectiveDirective);
init.setEffectiveDirective(effectiveDirective);
init.setOriginalPolicy(header);
init.setDisposition(headerType == ContentSecurityPolicyHeaderTypeEnforce
? "enforce"
: "report");
init.setSourceFile(String());
init.setLineNumber(contextLine);
init.setColumnNumber(0);
init.setStatusCode(0);
if (context->isDocument()) {
Document* document = toDocument(context);
DCHECK(document);
init.setReferrer(document->referrer());
if (!SecurityOrigin::isSecure(context->url()) && document->loader())
init.setStatusCode(document->loader()->response().httpStatusCode());
}
std::unique_ptr<SourceLocation> location = SourceLocation::capture(context);
if (location->lineNumber()) {
KURL source = KURL(ParsedURLString, location->url());
init.setSourceFile(
stripURLForUseInReport(context, source, redirectStatus, effectiveType));
init.setLineNumber(location->lineNumber());
init.setColumnNumber(location->columnNumber());
}
if (!scriptSource.isEmpty())
init.setSample(scriptSource.stripWhiteSpace().left(40));
}
Commit Message: CSP: Strip the fragment from reported URLs.
We should have been stripping the fragment from the URL we report for
CSP violations, but we weren't. Now we are, by running the URLs through
`stripURLForUseInReport()`, which implements the stripping algorithm
from CSP2: https://www.w3.org/TR/CSP2/#strip-uri-for-reporting
Eventually, we will migrate more completely to the CSP3 world that
doesn't require such detailed stripping, as it exposes less data to the
reports, but we're not there yet.
BUG=678776
Review-Url: https://codereview.chromium.org/2619783002
Cr-Commit-Position: refs/heads/master@{#458045}
CWE ID: CWE-200
|
static void gatherSecurityPolicyViolationEventData(
SecurityPolicyViolationEventInit& init,
ExecutionContext* context,
const String& directiveText,
const ContentSecurityPolicy::DirectiveType& effectiveType,
const KURL& blockedURL,
const String& header,
RedirectStatus redirectStatus,
ContentSecurityPolicyHeaderType headerType,
ContentSecurityPolicy::ViolationType violationType,
int contextLine,
const String& scriptSource) {
if (effectiveType == ContentSecurityPolicy::DirectiveType::FrameAncestors) {
String strippedURL = stripURLForUseInReport(
context, blockedURL, RedirectStatus::NoRedirect,
ContentSecurityPolicy::DirectiveType::DefaultSrc);
init.setDocumentURI(strippedURL);
init.setBlockedURI(strippedURL);
} else {
String strippedURL = stripURLForUseInReport(
context, context->url(), RedirectStatus::NoRedirect,
ContentSecurityPolicy::DirectiveType::DefaultSrc);
init.setDocumentURI(strippedURL);
switch (violationType) {
case ContentSecurityPolicy::InlineViolation:
init.setBlockedURI("inline");
break;
case ContentSecurityPolicy::EvalViolation:
init.setBlockedURI("eval");
break;
case ContentSecurityPolicy::URLViolation:
init.setBlockedURI(stripURLForUseInReport(
context, blockedURL, redirectStatus, effectiveType));
break;
}
}
String effectiveDirective =
ContentSecurityPolicy::getDirectiveName(effectiveType);
init.setViolatedDirective(effectiveDirective);
init.setEffectiveDirective(effectiveDirective);
init.setOriginalPolicy(header);
init.setDisposition(headerType == ContentSecurityPolicyHeaderTypeEnforce
? "enforce"
: "report");
init.setSourceFile(String());
init.setLineNumber(contextLine);
init.setColumnNumber(0);
init.setStatusCode(0);
if (context->isDocument()) {
Document* document = toDocument(context);
DCHECK(document);
init.setReferrer(document->referrer());
if (!SecurityOrigin::isSecure(context->url()) && document->loader())
init.setStatusCode(document->loader()->response().httpStatusCode());
}
std::unique_ptr<SourceLocation> location = SourceLocation::capture(context);
if (location->lineNumber()) {
KURL source = KURL(ParsedURLString, location->url());
init.setSourceFile(
stripURLForUseInReport(context, source, redirectStatus, effectiveType));
init.setLineNumber(location->lineNumber());
init.setColumnNumber(location->columnNumber());
}
if (!scriptSource.isEmpty())
init.setSample(scriptSource.stripWhiteSpace().left(40));
}
| 172,361
|
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 update_logging() {
bool should_log = module_started &&
(logging_enabled_via_api || stack_config->get_btsnoop_turned_on());
if (should_log == is_logging)
return;
is_logging = should_log;
if (should_log) {
btsnoop_net_open();
const char *log_path = stack_config->get_btsnoop_log_path();
if (stack_config->get_btsnoop_should_save_last()) {
char last_log_path[PATH_MAX];
snprintf(last_log_path, PATH_MAX, "%s.%llu", log_path, btsnoop_timestamp());
if (!rename(log_path, last_log_path) && errno != ENOENT)
LOG_ERROR("%s unable to rename '%s' to '%s': %s", __func__, log_path, last_log_path, strerror(errno));
}
logfile_fd = open(log_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
if (logfile_fd == INVALID_FD) {
LOG_ERROR("%s unable to open '%s': %s", __func__, log_path, strerror(errno));
is_logging = false;
return;
}
write(logfile_fd, "btsnoop\0\0\0\0\1\0\0\x3\xea", 16);
} else {
if (logfile_fd != INVALID_FD)
close(logfile_fd);
logfile_fd = INVALID_FD;
btsnoop_net_close();
}
}
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
|
static void update_logging() {
bool should_log = module_started &&
(logging_enabled_via_api || stack_config->get_btsnoop_turned_on());
if (should_log == is_logging)
return;
is_logging = should_log;
if (should_log) {
btsnoop_net_open();
const char *log_path = stack_config->get_btsnoop_log_path();
if (stack_config->get_btsnoop_should_save_last()) {
char last_log_path[PATH_MAX];
snprintf(last_log_path, PATH_MAX, "%s.%llu", log_path, btsnoop_timestamp());
if (!rename(log_path, last_log_path) && errno != ENOENT)
LOG_ERROR("%s unable to rename '%s' to '%s': %s", __func__, log_path, last_log_path, strerror(errno));
}
logfile_fd = TEMP_FAILURE_RETRY(open(log_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH));
if (logfile_fd == INVALID_FD) {
LOG_ERROR("%s unable to open '%s': %s", __func__, log_path, strerror(errno));
is_logging = false;
return;
}
TEMP_FAILURE_RETRY(write(logfile_fd, "btsnoop\0\0\0\0\1\0\0\x3\xea", 16));
} else {
if (logfile_fd != INVALID_FD)
close(logfile_fd);
logfile_fd = INVALID_FD;
btsnoop_net_close();
}
}
| 173,473
|
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_ui16be(const iw_byte *b)
{
return (b[0]<<8) | b[1];
}
Commit Message: Trying to fix some invalid left shift operations
Fixes issue #16
CWE ID: CWE-682
|
IW_IMPL(unsigned int) iw_get_ui16be(const iw_byte *b)
{
return ((unsigned int)b[0]<<8) | (unsigned int)b[1];
}
| 168,197
|
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 AcceleratedStaticBitmapImage::Abandon() {
texture_holder_->Abandon();
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <gab@chromium.org>
Reviewed-by: Jeremy Roman <jbroman@chromium.org>
Commit-Queue: Fernando Serboncini <fserb@chromium.org>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119
|
void AcceleratedStaticBitmapImage::Abandon() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
texture_holder_->Abandon();
}
| 172,587
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool IsTraceEventArgsWhitelisted(const char* category_group_name,
const char* event_name) {
base::CStringTokenizer category_group_tokens(
category_group_name, category_group_name + strlen(category_group_name),
",");
while (category_group_tokens.GetNext()) {
const std::string& category_group_token = category_group_tokens.token();
for (int i = 0; kEventArgsWhitelist[i][0] != NULL; ++i) {
DCHECK(kEventArgsWhitelist[i][1]);
if (base::MatchPattern(category_group_token.c_str(),
kEventArgsWhitelist[i][0]) &&
base::MatchPattern(event_name, kEventArgsWhitelist[i][1])) {
return true;
}
}
}
return false;
}
Commit Message: Tracing: Add support for PII whitelisting of individual trace event arguments
R=dsinclair,shatch
BUG=546093
Review URL: https://codereview.chromium.org/1415013003
Cr-Commit-Position: refs/heads/master@{#356690}
CWE ID: CWE-399
|
bool IsTraceEventArgsWhitelisted(const char* category_group_name,
bool IsTraceArgumentNameWhitelisted(const char* const* granular_filter,
const char* arg_name) {
for (int i = 0; granular_filter[i] != nullptr; ++i) {
if (base::MatchPattern(arg_name, granular_filter[i]))
return true;
}
return false;
}
bool IsTraceEventArgsWhitelisted(
const char* category_group_name,
const char* event_name,
base::trace_event::ArgumentNameFilterPredicate* arg_name_filter) {
DCHECK(arg_name_filter);
base::CStringTokenizer category_group_tokens(
category_group_name, category_group_name + strlen(category_group_name),
",");
while (category_group_tokens.GetNext()) {
const std::string& category_group_token = category_group_tokens.token();
for (int i = 0; kEventArgsWhitelist[i].category_name != nullptr; ++i) {
const WhitelistEntry& whitelist_entry = kEventArgsWhitelist[i];
DCHECK(whitelist_entry.event_name);
if (base::MatchPattern(category_group_token.c_str(),
whitelist_entry.category_name) &&
base::MatchPattern(event_name, whitelist_entry.event_name)) {
if (whitelist_entry.arg_name_filter) {
*arg_name_filter = base::Bind(&IsTraceArgumentNameWhitelisted,
whitelist_entry.arg_name_filter);
}
return true;
}
}
}
return false;
}
| 171,680
|
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 FrameSelection::IsHandleVisible() const {
return GetSelectionInDOMTree().IsHandleVisible();
}
Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection
This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate|
since handle visibility is used only for setting |FrameSelection|, hence it is
a redundant member variable of |SelectionTemplate|.
Bug: 742093
Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e
Reviewed-on: https://chromium-review.googlesource.com/595389
Commit-Queue: Yoshifumi Inoue <yosin@chromium.org>
Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org>
Reviewed-by: Kent Tamura <tkent@chromium.org>
Cr-Commit-Position: refs/heads/master@{#491660}
CWE ID: CWE-119
|
bool FrameSelection::IsHandleVisible() const {
| 171,755
|
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 DownloadController::OnDownloadStarted(
DownloadItem* download_item) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
WebContents* web_contents = download_item->GetWebContents();
if (!web_contents)
return;
download_item->AddObserver(this);
ChromeDownloadDelegate::FromWebContents(web_contents)->OnDownloadStarted(
download_item->GetTargetFilePath().BaseName().value(),
download_item->GetMimeType());
}
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 DownloadController::OnDownloadStarted(
DownloadItem* download_item) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
WebContents* web_contents = download_item->GetWebContents();
if (!web_contents)
return;
download_item->AddObserver(this);
ChromeDownloadDelegate::FromWebContents(web_contents)->OnDownloadStarted(
download_item->GetTargetFilePath().BaseName().value());
}
| 171,882
|
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: nfsd4_encode_getdeviceinfo(struct nfsd4_compoundres *resp, __be32 nfserr,
struct nfsd4_getdeviceinfo *gdev)
{
struct xdr_stream *xdr = &resp->xdr;
const struct nfsd4_layout_ops *ops =
nfsd4_layout_ops[gdev->gd_layout_type];
u32 starting_len = xdr->buf->len, needed_len;
__be32 *p;
dprintk("%s: err %d\n", __func__, be32_to_cpu(nfserr));
if (nfserr)
goto out;
nfserr = nfserr_resource;
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out;
*p++ = cpu_to_be32(gdev->gd_layout_type);
/* If maxcount is 0 then just update notifications */
if (gdev->gd_maxcount != 0) {
nfserr = ops->encode_getdeviceinfo(xdr, gdev);
if (nfserr) {
/*
* We don't bother to burden the layout drivers with
* enforcing gd_maxcount, just tell the client to
* come back with a bigger buffer if it's not enough.
*/
if (xdr->buf->len + 4 > gdev->gd_maxcount)
goto toosmall;
goto out;
}
}
nfserr = nfserr_resource;
if (gdev->gd_notify_types) {
p = xdr_reserve_space(xdr, 4 + 4);
if (!p)
goto out;
*p++ = cpu_to_be32(1); /* bitmap length */
*p++ = cpu_to_be32(gdev->gd_notify_types);
} else {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out;
*p++ = 0;
}
nfserr = 0;
out:
kfree(gdev->gd_device);
dprintk("%s: done: %d\n", __func__, be32_to_cpu(nfserr));
return nfserr;
toosmall:
dprintk("%s: maxcount too small\n", __func__);
needed_len = xdr->buf->len + 4 /* notifications */;
xdr_truncate_encode(xdr, starting_len);
p = xdr_reserve_space(xdr, 4);
if (!p) {
nfserr = nfserr_resource;
} else {
*p++ = cpu_to_be32(needed_len);
nfserr = nfserr_toosmall;
}
goto out;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
|
nfsd4_encode_getdeviceinfo(struct nfsd4_compoundres *resp, __be32 nfserr,
struct nfsd4_getdeviceinfo *gdev)
{
struct xdr_stream *xdr = &resp->xdr;
const struct nfsd4_layout_ops *ops;
u32 starting_len = xdr->buf->len, needed_len;
__be32 *p;
dprintk("%s: err %d\n", __func__, be32_to_cpu(nfserr));
if (nfserr)
goto out;
nfserr = nfserr_resource;
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out;
*p++ = cpu_to_be32(gdev->gd_layout_type);
/* If maxcount is 0 then just update notifications */
if (gdev->gd_maxcount != 0) {
ops = nfsd4_layout_ops[gdev->gd_layout_type];
nfserr = ops->encode_getdeviceinfo(xdr, gdev);
if (nfserr) {
/*
* We don't bother to burden the layout drivers with
* enforcing gd_maxcount, just tell the client to
* come back with a bigger buffer if it's not enough.
*/
if (xdr->buf->len + 4 > gdev->gd_maxcount)
goto toosmall;
goto out;
}
}
nfserr = nfserr_resource;
if (gdev->gd_notify_types) {
p = xdr_reserve_space(xdr, 4 + 4);
if (!p)
goto out;
*p++ = cpu_to_be32(1); /* bitmap length */
*p++ = cpu_to_be32(gdev->gd_notify_types);
} else {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out;
*p++ = 0;
}
nfserr = 0;
out:
kfree(gdev->gd_device);
dprintk("%s: done: %d\n", __func__, be32_to_cpu(nfserr));
return nfserr;
toosmall:
dprintk("%s: maxcount too small\n", __func__);
needed_len = xdr->buf->len + 4 /* notifications */;
xdr_truncate_encode(xdr, starting_len);
p = xdr_reserve_space(xdr, 4);
if (!p) {
nfserr = nfserr_resource;
} else {
*p++ = cpu_to_be32(needed_len);
nfserr = nfserr_toosmall;
}
goto out;
}
| 168,148
|
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: WindowOpenDisposition BrowserView::GetDispositionForPopupBounds(
const gfx::Rect& bounds) {
return WindowOpenDisposition::NEW_POPUP;
}
Commit Message: Mac: turn popups into new tabs while in fullscreen.
It's platform convention to show popups as new tabs while in
non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.)
This was implemented for Cocoa in a BrowserWindow override, but
it makes sense to just stick it into Browser and remove a ton
of override code put in just to support this.
BUG=858929, 868416
TEST=as in bugs
Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d
Reviewed-on: https://chromium-review.googlesource.com/1153455
Reviewed-by: Sidney San Martín <sdy@chromium.org>
Commit-Queue: Avi Drissman <avi@chromium.org>
Cr-Commit-Position: refs/heads/master@{#578755}
CWE ID: CWE-20
|
WindowOpenDisposition BrowserView::GetDispositionForPopupBounds(
| 173,207
|
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 UINT drdynvc_process_create_request(drdynvcPlugin* drdynvc, int Sp,
int cbChId, wStream* s)
{
size_t pos;
UINT status;
UINT32 ChannelId;
wStream* data_out;
UINT channel_status;
if (!drdynvc)
return CHANNEL_RC_BAD_CHANNEL_HANDLE;
if (drdynvc->state == DRDYNVC_STATE_CAPABILITIES)
{
/**
* For some reason the server does not always send the
* capabilities pdu as it should. When this happens,
* send a capabilities response.
*/
drdynvc->version = 3;
if ((status = drdynvc_send_capability_response(drdynvc)))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "drdynvc_send_capability_response failed!");
return status;
}
drdynvc->state = DRDYNVC_STATE_READY;
}
ChannelId = drdynvc_read_variable_uint(s, cbChId);
pos = Stream_GetPosition(s);
WLog_Print(drdynvc->log, WLOG_DEBUG, "process_create_request: ChannelId=%"PRIu32" ChannelName=%s",
ChannelId,
Stream_Pointer(s));
channel_status = dvcman_create_channel(drdynvc, drdynvc->channel_mgr, ChannelId,
(char*) Stream_Pointer(s));
data_out = Stream_New(NULL, pos + 4);
if (!data_out)
{
WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!");
return CHANNEL_RC_NO_MEMORY;
}
Stream_Write_UINT8(data_out, 0x10 | cbChId);
Stream_SetPosition(s, 1);
Stream_Copy(s, data_out, pos - 1);
if (channel_status == CHANNEL_RC_OK)
{
WLog_Print(drdynvc->log, WLOG_DEBUG, "channel created");
Stream_Write_UINT32(data_out, 0);
}
else
{
WLog_Print(drdynvc->log, WLOG_DEBUG, "no listener");
Stream_Write_UINT32(data_out, (UINT32)0xC0000001); /* same code used by mstsc */
}
status = drdynvc_send(drdynvc, data_out);
if (status != CHANNEL_RC_OK)
{
WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08"PRIX32"]",
WTSErrorToString(status), status);
return status;
}
if (channel_status == CHANNEL_RC_OK)
{
if ((status = dvcman_open_channel(drdynvc, drdynvc->channel_mgr, ChannelId)))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_open_channel failed with error %"PRIu32"!", status);
return status;
}
}
else
{
if ((status = dvcman_close_channel(drdynvc->channel_mgr, ChannelId)))
WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_close_channel failed with error %"PRIu32"!", status);
}
return status;
}
Commit Message: Fix for #4866: Added additional length checks
CWE ID:
|
static UINT drdynvc_process_create_request(drdynvcPlugin* drdynvc, int Sp,
int cbChId, wStream* s)
{
size_t pos;
UINT status;
UINT32 ChannelId;
wStream* data_out;
UINT channel_status;
char* name;
size_t length;
if (!drdynvc)
return CHANNEL_RC_BAD_CHANNEL_HANDLE;
if (drdynvc->state == DRDYNVC_STATE_CAPABILITIES)
{
/**
* For some reason the server does not always send the
* capabilities pdu as it should. When this happens,
* send a capabilities response.
*/
drdynvc->version = 3;
if ((status = drdynvc_send_capability_response(drdynvc)))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "drdynvc_send_capability_response failed!");
return status;
}
drdynvc->state = DRDYNVC_STATE_READY;
}
if (Stream_GetRemainingLength(s) < drdynvc_cblen_to_bytes(cbChId))
return ERROR_INVALID_DATA;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
pos = Stream_GetPosition(s);
name = Stream_Pointer(s);
length = Stream_GetRemainingLength(s);
if (strnlen(name, length) >= length)
return ERROR_INVALID_DATA;
WLog_Print(drdynvc->log, WLOG_DEBUG, "process_create_request: ChannelId=%"PRIu32" ChannelName=%s",
ChannelId, name);
channel_status = dvcman_create_channel(drdynvc, drdynvc->channel_mgr, ChannelId, name);
data_out = Stream_New(NULL, pos + 4);
if (!data_out)
{
WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!");
return CHANNEL_RC_NO_MEMORY;
}
Stream_Write_UINT8(data_out, 0x10 | cbChId);
Stream_SetPosition(s, 1);
Stream_Copy(s, data_out, pos - 1);
if (channel_status == CHANNEL_RC_OK)
{
WLog_Print(drdynvc->log, WLOG_DEBUG, "channel created");
Stream_Write_UINT32(data_out, 0);
}
else
{
WLog_Print(drdynvc->log, WLOG_DEBUG, "no listener");
Stream_Write_UINT32(data_out, (UINT32)0xC0000001); /* same code used by mstsc */
}
status = drdynvc_send(drdynvc, data_out);
if (status != CHANNEL_RC_OK)
{
WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08"PRIX32"]",
WTSErrorToString(status), status);
return status;
}
if (channel_status == CHANNEL_RC_OK)
{
if ((status = dvcman_open_channel(drdynvc, drdynvc->channel_mgr, ChannelId)))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_open_channel failed with error %"PRIu32"!", status);
return status;
}
}
else
{
if ((status = dvcman_close_channel(drdynvc->channel_mgr, ChannelId)))
WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_close_channel failed with error %"PRIu32"!", status);
}
return status;
}
| 168,936
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_FUNCTION(mcrypt_create_iv)
{
char *iv;
long source = RANDOM;
long size;
int n = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &size, &source) == FAILURE) {
return;
}
if (size <= 0 || size >= INT_MAX) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create an IV with a size of less than 1 or greater than %d", INT_MAX);
RETURN_FALSE;
}
iv = ecalloc(size + 1, 1);
if (source == RANDOM || source == URANDOM) {
#if PHP_WIN32
/* random/urandom equivalent on Windows */
BYTE *iv_b = (BYTE *) iv;
if (php_win32_get_random_bytes(iv_b, (size_t) size) == FAILURE){
efree(iv);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not gather sufficient random data");
RETURN_FALSE;
}
n = size;
#else
int *fd = &MCG(fd[source]);
size_t read_bytes = 0;
if (*fd < 0) {
*fd = open(source == RANDOM ? "/dev/random" : "/dev/urandom", O_RDONLY);
if (*fd < 0) {
efree(iv);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot open source device");
RETURN_FALSE;
}
}
while (read_bytes < size) {
n = read(*fd, iv + read_bytes, size - read_bytes);
if (n < 0) {
break;
}
read_bytes += n;
}
n = read_bytes;
if (n < size) {
efree(iv);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not gather sufficient random data");
RETURN_FALSE;
}
#endif
} else {
n = size;
while (size) {
iv[--size] = (char) (255.0 * php_rand(TSRMLS_C) / RAND_MAX);
}
}
RETURN_STRINGL(iv, n, 0);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
|
PHP_FUNCTION(mcrypt_create_iv)
{
char *iv;
long source = RANDOM;
long size;
int n = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &size, &source) == FAILURE) {
return;
}
if (size <= 0 || size >= INT_MAX) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create an IV with a size of less than 1 or greater than %d", INT_MAX);
RETURN_FALSE;
}
iv = ecalloc(size + 1, 1);
if (source == RANDOM || source == URANDOM) {
#if PHP_WIN32
/* random/urandom equivalent on Windows */
BYTE *iv_b = (BYTE *) iv;
if (php_win32_get_random_bytes(iv_b, (size_t) size) == FAILURE){
efree(iv);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not gather sufficient random data");
RETURN_FALSE;
}
n = size;
#else
int *fd = &MCG(fd[source]);
size_t read_bytes = 0;
if (*fd < 0) {
*fd = open(source == RANDOM ? "/dev/random" : "/dev/urandom", O_RDONLY);
if (*fd < 0) {
efree(iv);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot open source device");
RETURN_FALSE;
}
}
while (read_bytes < size) {
n = read(*fd, iv + read_bytes, size - read_bytes);
if (n < 0) {
break;
}
read_bytes += n;
}
n = read_bytes;
if (n < size) {
efree(iv);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not gather sufficient random data");
RETURN_FALSE;
}
#endif
} else {
n = size;
while (size) {
iv[--size] = (char) (255.0 * php_rand(TSRMLS_C) / RAND_MAX);
}
}
RETURN_STRINGL(iv, n, 0);
}
| 167,111
|
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 omx_video::empty_this_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
OMX_ERRORTYPE ret1 = OMX_ErrorNone;
unsigned int nBufferIndex ;
DEBUG_PRINT_LOW("ETB: buffer = %p, buffer->pBuffer[%p]", buffer, buffer->pBuffer);
if (m_state == OMX_StateInvalid) {
DEBUG_PRINT_ERROR("ERROR: Empty this buffer in Invalid State");
return OMX_ErrorInvalidState;
}
if (buffer == NULL || (buffer->nSize != sizeof(OMX_BUFFERHEADERTYPE))) {
DEBUG_PRINT_ERROR("ERROR: omx_video::etb--> buffer is null or buffer size is invalid");
return OMX_ErrorBadParameter;
}
if (buffer->nVersion.nVersion != OMX_SPEC_VERSION) {
DEBUG_PRINT_ERROR("ERROR: omx_video::etb--> OMX Version Invalid");
return OMX_ErrorVersionMismatch;
}
if (buffer->nInputPortIndex != (OMX_U32)PORT_INDEX_IN) {
DEBUG_PRINT_ERROR("ERROR: Bad port index to call empty_this_buffer");
return OMX_ErrorBadPortIndex;
}
if (!m_sInPortDef.bEnabled) {
DEBUG_PRINT_ERROR("ERROR: Cannot call empty_this_buffer while I/P port is disabled");
return OMX_ErrorIncorrectStateOperation;
}
nBufferIndex = buffer - ((!meta_mode_enable)?m_inp_mem_ptr:meta_buffer_hdr);
if (nBufferIndex > m_sInPortDef.nBufferCountActual ) {
DEBUG_PRINT_ERROR("ERROR: ETB: Invalid buffer index[%d]", nBufferIndex);
return OMX_ErrorBadParameter;
}
m_etb_count++;
DEBUG_PRINT_LOW("DBG: i/p nTimestamp = %u", (unsigned)buffer->nTimeStamp);
post_event ((unsigned long)hComp,(unsigned long)buffer,m_input_msg_id);
return OMX_ErrorNone;
}
Commit Message: DO NOT MERGE mm-video-v4l2: venc: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27903498
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVenc problem #3)
CRs-Fixed: 1010088
Change-Id: I898b42034c0add621d4f9d8e02ca0ed4403d4fd3
CWE ID:
|
OMX_ERRORTYPE omx_video::empty_this_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
OMX_ERRORTYPE ret1 = OMX_ErrorNone;
unsigned int nBufferIndex ;
DEBUG_PRINT_LOW("ETB: buffer = %p, buffer->pBuffer[%p]", buffer, buffer->pBuffer);
if (m_state != OMX_StateExecuting &&
m_state != OMX_StatePause &&
m_state != OMX_StateIdle) {
DEBUG_PRINT_ERROR("ERROR: Empty this buffer in Invalid State");
return OMX_ErrorInvalidState;
}
if (buffer == NULL || (buffer->nSize != sizeof(OMX_BUFFERHEADERTYPE))) {
DEBUG_PRINT_ERROR("ERROR: omx_video::etb--> buffer is null or buffer size is invalid");
return OMX_ErrorBadParameter;
}
if (buffer->nVersion.nVersion != OMX_SPEC_VERSION) {
DEBUG_PRINT_ERROR("ERROR: omx_video::etb--> OMX Version Invalid");
return OMX_ErrorVersionMismatch;
}
if (buffer->nInputPortIndex != (OMX_U32)PORT_INDEX_IN) {
DEBUG_PRINT_ERROR("ERROR: Bad port index to call empty_this_buffer");
return OMX_ErrorBadPortIndex;
}
if (!m_sInPortDef.bEnabled) {
DEBUG_PRINT_ERROR("ERROR: Cannot call empty_this_buffer while I/P port is disabled");
return OMX_ErrorIncorrectStateOperation;
}
nBufferIndex = buffer - ((!meta_mode_enable)?m_inp_mem_ptr:meta_buffer_hdr);
if (nBufferIndex > m_sInPortDef.nBufferCountActual ) {
DEBUG_PRINT_ERROR("ERROR: ETB: Invalid buffer index[%d]", nBufferIndex);
return OMX_ErrorBadParameter;
}
m_etb_count++;
DEBUG_PRINT_LOW("DBG: i/p nTimestamp = %u", (unsigned)buffer->nTimeStamp);
post_event ((unsigned long)hComp,(unsigned long)buffer,m_input_msg_id);
return OMX_ErrorNone;
}
| 173,745
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: const Chapters::Atom* Chapters::Edition::GetAtom(int index) const
{
if (index < 0)
return NULL;
if (index >= m_atoms_count)
return NULL;
return m_atoms + index;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
const Chapters::Atom* Chapters::Edition::GetAtom(int index) const
const Chapters::Display* Chapters::Atom::GetDisplay(int index) const {
if (index < 0)
return NULL;
if (index >= m_displays_count)
return NULL;
return m_displays + index;
}
| 174,281
|
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 test_base64_lengths(void)
{
const char *in = "FuseMuse";
char out1[32];
char out2[32];
size_t enclen;
int declen;
/* Encoding a zero-length string should fail */
enclen = mutt_b64_encode(out1, in, 0, 32);
if (!TEST_CHECK(enclen == 0))
{
TEST_MSG("Expected: %zu", 0);
TEST_MSG("Actual : %zu", enclen);
}
/* Decoding a zero-length string should fail, too */
out1[0] = '\0';
declen = mutt_b64_decode(out2, out1);
if (!TEST_CHECK(declen == -1))
{
TEST_MSG("Expected: %zu", -1);
TEST_MSG("Actual : %zu", declen);
}
/* Encode one to eight bytes, check the lengths of the returned string */
for (size_t i = 1; i <= 8; ++i)
{
enclen = mutt_b64_encode(out1, in, i, 32);
size_t exp = ((i + 2) / 3) << 2;
if (!TEST_CHECK(enclen == exp))
{
TEST_MSG("Expected: %zu", exp);
TEST_MSG("Actual : %zu", enclen);
}
declen = mutt_b64_decode(out2, out1);
if (!TEST_CHECK(declen == i))
{
TEST_MSG("Expected: %zu", i);
TEST_MSG("Actual : %zu", declen);
}
out2[declen] = '\0';
if (!TEST_CHECK(strncmp(out2, in, i) == 0))
{
TEST_MSG("Expected: %s", in);
TEST_MSG("Actual : %s", out2);
}
}
}
Commit Message: Check outbuf length in mutt_to_base64()
The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c.
Thanks to Jeriko One for the bug report.
CWE ID: CWE-119
|
void test_base64_lengths(void)
{
const char *in = "FuseMuse";
char out1[32];
char out2[32];
size_t enclen;
int declen;
/* Encoding a zero-length string should fail */
enclen = mutt_b64_encode(out1, in, 0, 32);
if (!TEST_CHECK(enclen == 0))
{
TEST_MSG("Expected: %zu", 0);
TEST_MSG("Actual : %zu", enclen);
}
/* Decoding a zero-length string should fail, too */
out1[0] = '\0';
declen = mutt_b64_decode(out2, out1, sizeof(out2));
if (!TEST_CHECK(declen == -1))
{
TEST_MSG("Expected: %zu", -1);
TEST_MSG("Actual : %zu", declen);
}
/* Encode one to eight bytes, check the lengths of the returned string */
for (size_t i = 1; i <= 8; ++i)
{
enclen = mutt_b64_encode(out1, in, i, 32);
size_t exp = ((i + 2) / 3) << 2;
if (!TEST_CHECK(enclen == exp))
{
TEST_MSG("Expected: %zu", exp);
TEST_MSG("Actual : %zu", enclen);
}
declen = mutt_b64_decode(out2, out1, sizeof(out2));
if (!TEST_CHECK(declen == i))
{
TEST_MSG("Expected: %zu", i);
TEST_MSG("Actual : %zu", declen);
}
out2[declen] = '\0';
if (!TEST_CHECK(strncmp(out2, in, i) == 0))
{
TEST_MSG("Expected: %s", in);
TEST_MSG("Actual : %s", out2);
}
}
}
| 169,131
|
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: char* engrave_tombstone(pid_t pid, pid_t tid, int signal, int original_si_code,
uintptr_t abort_msg_address, bool dump_sibling_threads,
bool* detach_failed, int* total_sleep_time_usec) {
log_t log;
log.current_tid = tid;
log.crashed_tid = tid;
if ((mkdir(TOMBSTONE_DIR, 0755) == -1) && (errno != EEXIST)) {
_LOG(&log, logtype::ERROR, "failed to create %s: %s\n", TOMBSTONE_DIR, strerror(errno));
}
if (chown(TOMBSTONE_DIR, AID_SYSTEM, AID_SYSTEM) == -1) {
_LOG(&log, logtype::ERROR, "failed to change ownership of %s: %s\n", TOMBSTONE_DIR, strerror(errno));
}
int fd = -1;
char* path = NULL;
if (selinux_android_restorecon(TOMBSTONE_DIR, 0) == 0) {
path = find_and_open_tombstone(&fd);
} else {
_LOG(&log, logtype::ERROR, "Failed to restore security context, not writing tombstone.\n");
}
if (fd < 0) {
_LOG(&log, logtype::ERROR, "Skipping tombstone write, nothing to do.\n");
*detach_failed = false;
return NULL;
}
log.tfd = fd;
int amfd = activity_manager_connect();
log.amfd = amfd;
*detach_failed = dump_crash(&log, pid, tid, signal, original_si_code, abort_msg_address,
dump_sibling_threads, total_sleep_time_usec);
ALOGI("\nTombstone written to: %s\n", path);
close(amfd);
close(fd);
return path;
}
Commit Message: Don't create tombstone directory.
Partial backport of cf79748.
Bug: http://b/26403620
Change-Id: Ib877ab6cfab6aef079830c5a50ba81141ead35ee
CWE ID: CWE-264
|
char* engrave_tombstone(pid_t pid, pid_t tid, int signal, int original_si_code,
uintptr_t abort_msg_address, bool dump_sibling_threads,
bool* detach_failed, int* total_sleep_time_usec) {
log_t log;
log.current_tid = tid;
log.crashed_tid = tid;
int fd = -1;
char* path = find_and_open_tombstone(&fd);
if (fd < 0) {
_LOG(&log, logtype::ERROR, "Skipping tombstone write, nothing to do.\n");
*detach_failed = false;
return NULL;
}
log.tfd = fd;
int amfd = activity_manager_connect();
log.amfd = amfd;
*detach_failed = dump_crash(&log, pid, tid, signal, original_si_code, abort_msg_address,
dump_sibling_threads, total_sleep_time_usec);
ALOGI("\nTombstone written to: %s\n", path);
close(amfd);
close(fd);
return path;
}
| 173,890
|
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: V8ContextNativeHandler::V8ContextNativeHandler(ScriptContext* context,
Dispatcher* dispatcher)
: ObjectBackedNativeHandler(context),
context_(context),
dispatcher_(dispatcher) {
RouteFunction("GetAvailability",
base::Bind(&V8ContextNativeHandler::GetAvailability,
base::Unretained(this)));
RouteFunction("GetModuleSystem",
base::Bind(&V8ContextNativeHandler::GetModuleSystem,
base::Unretained(this)));
RouteFunction(
"RunWithNativesEnabledModuleSystem",
base::Bind(&V8ContextNativeHandler::RunWithNativesEnabledModuleSystem,
base::Unretained(this)));
}
Commit Message: Add a test that getModuleSystem() doesn't work cross origin
BUG=504011
R=kalman@chromium.org
TBR=fukino@chromium.org
Review URL: https://codereview.chromium.org/1241443004
Cr-Commit-Position: refs/heads/master@{#338663}
CWE ID: CWE-79
|
V8ContextNativeHandler::V8ContextNativeHandler(ScriptContext* context,
Dispatcher* dispatcher)
: ObjectBackedNativeHandler(context),
context_(context),
dispatcher_(dispatcher) {
RouteFunction("GetAvailability",
base::Bind(&V8ContextNativeHandler::GetAvailability,
base::Unretained(this)));
RouteFunction("GetModuleSystem",
base::Bind(&V8ContextNativeHandler::GetModuleSystem,
base::Unretained(this)));
RouteFunction(
"RunWithNativesEnabled",
base::Bind(&V8ContextNativeHandler::RunWithNativesEnabled,
base::Unretained(this)));
}
| 171,949
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool ChromePluginServiceFilter::IsPluginEnabled(
int render_process_id,
int render_view_id,
const void* context,
const GURL& url,
const GURL& policy_url,
webkit::WebPluginInfo* plugin) {
base::AutoLock auto_lock(lock_);
const ProcessDetails* details = GetProcess(render_process_id);
if (details) {
for (size_t i = 0; i < details->overridden_plugins.size(); ++i) {
if (details->overridden_plugins[i].render_view_id == render_view_id &&
(details->overridden_plugins[i].url == url ||
details->overridden_plugins[i].url.is_empty())) {
bool use = details->overridden_plugins[i].plugin.path == plugin->path;
if (!use)
return false;
*plugin = details->overridden_plugins[i].plugin;
break;
}
}
}
ResourceContextMap::iterator prefs_it =
resource_context_map_.find(context);
if (prefs_it == resource_context_map_.end())
return false;
PluginPrefs* plugin_prefs = prefs_it->second.get();
if (!plugin_prefs->IsPluginEnabled(*plugin))
return false;
RestrictedPluginMap::const_iterator it =
restricted_plugins_.find(plugin->path);
if (it != restricted_plugins_.end()) {
if (it->second.first != plugin_prefs)
return false;
const GURL& origin = it->second.second;
if (!origin.is_empty() &&
(policy_url.scheme() != origin.scheme() ||
policy_url.host() != origin.host() ||
policy_url.port() != origin.port())) {
return false;
}
}
return true;
}
Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/
BUG=172573
Review URL: https://codereview.chromium.org/12177018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-287
|
bool ChromePluginServiceFilter::IsPluginEnabled(
bool ChromePluginServiceFilter::IsPluginAvailable(
int render_process_id,
int render_view_id,
const void* context,
const GURL& url,
const GURL& policy_url,
webkit::WebPluginInfo* plugin) {
base::AutoLock auto_lock(lock_);
const ProcessDetails* details = GetProcess(render_process_id);
if (details) {
for (size_t i = 0; i < details->overridden_plugins.size(); ++i) {
if (details->overridden_plugins[i].render_view_id == render_view_id &&
(details->overridden_plugins[i].url == url ||
details->overridden_plugins[i].url.is_empty())) {
bool use = details->overridden_plugins[i].plugin.path == plugin->path;
if (use)
*plugin = details->overridden_plugins[i].plugin;
return use;
}
}
}
ResourceContextMap::iterator prefs_it =
resource_context_map_.find(context);
if (prefs_it == resource_context_map_.end())
return false;
PluginPrefs* plugin_prefs = prefs_it->second.get();
if (!plugin_prefs->IsPluginEnabled(*plugin))
return false;
RestrictedPluginMap::const_iterator it =
restricted_plugins_.find(plugin->path);
if (it != restricted_plugins_.end()) {
if (it->second.first != plugin_prefs)
return false;
const GURL& origin = it->second.second;
if (!origin.is_empty() &&
(policy_url.scheme() != origin.scheme() ||
policy_url.host() != origin.host() ||
policy_url.port() != origin.port())) {
return false;
}
}
return true;
}
| 171,470
|
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: Address LargeObjectArena::doAllocateLargeObjectPage(size_t allocationSize,
size_t gcInfoIndex) {
size_t largeObjectSize = LargeObjectPage::pageHeaderSize() + allocationSize;
#if defined(ADDRESS_SANITIZER)
largeObjectSize += allocationGranularity;
#endif
getThreadState()->shouldFlushHeapDoesNotContainCache();
PageMemory* pageMemory = PageMemory::allocate(
largeObjectSize, getThreadState()->heap().getRegionTree());
Address largeObjectAddress = pageMemory->writableStart();
Address headerAddress =
largeObjectAddress + LargeObjectPage::pageHeaderSize();
#if DCHECK_IS_ON()
for (size_t i = 0; i < largeObjectSize; ++i)
ASSERT(!largeObjectAddress[i]);
#endif
ASSERT(gcInfoIndex > 0);
HeapObjectHeader* header = new (NotNull, headerAddress)
HeapObjectHeader(largeObjectSizeInHeader, gcInfoIndex);
Address result = headerAddress + sizeof(*header);
ASSERT(!(reinterpret_cast<uintptr_t>(result) & allocationMask));
LargeObjectPage* largeObject = new (largeObjectAddress)
LargeObjectPage(pageMemory, this, allocationSize);
ASSERT(header->checkHeader());
ASAN_POISON_MEMORY_REGION(header, sizeof(*header));
ASAN_POISON_MEMORY_REGION(largeObject->getAddress() + largeObject->size(),
allocationGranularity);
largeObject->link(&m_firstPage);
getThreadState()->heap().heapStats().increaseAllocatedSpace(
largeObject->size());
getThreadState()->increaseAllocatedObjectSize(largeObject->size());
return result;
}
Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect.
This requires changing its signature. This is a preliminary stage to making it
private.
BUG=633030
Review-Url: https://codereview.chromium.org/2698673003
Cr-Commit-Position: refs/heads/master@{#460489}
CWE ID: CWE-119
|
Address LargeObjectArena::doAllocateLargeObjectPage(size_t allocationSize,
size_t gcInfoIndex) {
size_t largeObjectSize = LargeObjectPage::pageHeaderSize() + allocationSize;
#if defined(ADDRESS_SANITIZER)
largeObjectSize += allocationGranularity;
#endif
getThreadState()->shouldFlushHeapDoesNotContainCache();
PageMemory* pageMemory = PageMemory::allocate(
largeObjectSize, getThreadState()->heap().getRegionTree());
Address largeObjectAddress = pageMemory->writableStart();
Address headerAddress =
largeObjectAddress + LargeObjectPage::pageHeaderSize();
#if DCHECK_IS_ON()
for (size_t i = 0; i < largeObjectSize; ++i)
ASSERT(!largeObjectAddress[i]);
#endif
ASSERT(gcInfoIndex > 0);
HeapObjectHeader* header = new (NotNull, headerAddress)
HeapObjectHeader(largeObjectSizeInHeader, gcInfoIndex);
Address result = headerAddress + sizeof(*header);
ASSERT(!(reinterpret_cast<uintptr_t>(result) & allocationMask));
LargeObjectPage* largeObject = new (largeObjectAddress)
LargeObjectPage(pageMemory, this, allocationSize);
header->checkHeader();
ASAN_POISON_MEMORY_REGION(header, sizeof(*header));
ASAN_POISON_MEMORY_REGION(largeObject->getAddress() + largeObject->size(),
allocationGranularity);
largeObject->link(&m_firstPage);
getThreadState()->heap().heapStats().increaseAllocatedSpace(
largeObject->size());
getThreadState()->increaseAllocatedObjectSize(largeObject->size());
return result;
}
| 172,709
|
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 GpuChannel::OnControlMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(GpuChannel, msg)
IPC_MESSAGE_HANDLER(GpuChannelMsg_Initialize, OnInitialize)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_CreateOffscreenCommandBuffer,
OnCreateOffscreenCommandBuffer)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_DestroyCommandBuffer,
OnDestroyCommandBuffer)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_WillGpuSwitchOccur,
OnWillGpuSwitchOccur)
IPC_MESSAGE_HANDLER(GpuChannelMsg_CloseChannel, OnCloseChannel)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
DCHECK(handled) << msg.type();
return handled;
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
bool GpuChannel::OnControlMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(GpuChannel, msg)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_CreateOffscreenCommandBuffer,
OnCreateOffscreenCommandBuffer)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_DestroyCommandBuffer,
OnDestroyCommandBuffer)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_WillGpuSwitchOccur,
OnWillGpuSwitchOccur)
IPC_MESSAGE_HANDLER(GpuChannelMsg_CloseChannel, OnCloseChannel)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
DCHECK(handled) << msg.type();
return handled;
}
| 170,933
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long Chapters::Parse() {
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start; // payload start
const long long stop = pos + m_size; // payload stop
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x05B9) { // EditionEntry ID
status = ParseEdition(pos, size);
if (status < 0) // error
return status;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
long Chapters::Parse() {
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start; // payload start
const long long stop = pos + m_size; // payload stop
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x05B9) { // EditionEntry ID
status = ParseEdition(pos, size);
if (status < 0) // error
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,838
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
{
struct sshbuf *b;
struct sshcipher_ctx *cc;
struct sshcomp *comp;
struct sshenc *enc;
struct sshmac *mac;
struct newkeys *newkey;
int r;
if ((newkey = ssh->state->newkeys[mode]) == NULL)
return SSH_ERR_INTERNAL_ERROR;
enc = &newkey->enc;
mac = &newkey->mac;
comp = &newkey->comp;
cc = (mode == MODE_OUT) ? ssh->state->send_context :
ssh->state->receive_context;
if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
return r;
if ((b = sshbuf_new()) == NULL)
return SSH_ERR_ALLOC_FAIL;
/* The cipher struct is constant and shared, you export pointer */
if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
(r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
(r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
(r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
(r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
(r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
goto out;
if (cipher_authlen(enc->cipher) == 0) {
if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
(r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
(r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
goto out;
}
if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
(r = sshbuf_put_u32(b, comp->enabled)) != 0 ||
(r = sshbuf_put_cstring(b, comp->name)) != 0)
goto out;
r = sshbuf_put_stringb(m, b);
out:
sshbuf_free(b);
return r;
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119
|
newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
{
struct sshbuf *b;
struct sshcipher_ctx *cc;
struct sshcomp *comp;
struct sshenc *enc;
struct sshmac *mac;
struct newkeys *newkey;
int r;
if ((newkey = ssh->state->newkeys[mode]) == NULL)
return SSH_ERR_INTERNAL_ERROR;
enc = &newkey->enc;
mac = &newkey->mac;
comp = &newkey->comp;
cc = (mode == MODE_OUT) ? ssh->state->send_context :
ssh->state->receive_context;
if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
return r;
if ((b = sshbuf_new()) == NULL)
return SSH_ERR_ALLOC_FAIL;
/* The cipher struct is constant and shared, you export pointer */
if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
(r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
(r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
(r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
(r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
(r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
goto out;
if (cipher_authlen(enc->cipher) == 0) {
if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
(r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
(r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
goto out;
}
if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
(r = sshbuf_put_cstring(b, comp->name)) != 0)
goto out;
r = sshbuf_put_stringb(m, b);
out:
sshbuf_free(b);
return r;
}
| 168,651
|
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 NetworkHandler::SetNetworkConditions(
network::mojom::NetworkConditionsPtr conditions) {
if (!process_)
return;
StoragePartition* partition = process_->GetStoragePartition();
network::mojom::NetworkContext* context = partition->GetNetworkContext();
context->SetNetworkConditions(host_id_, std::move(conditions));
}
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 NetworkHandler::SetNetworkConditions(
network::mojom::NetworkConditionsPtr conditions) {
if (!storage_partition_)
return;
network::mojom::NetworkContext* context =
storage_partition_->GetNetworkContext();
context->SetNetworkConditions(host_id_, std::move(conditions));
}
| 172,762
|
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 Add(int original_content_length, int received_content_length) {
AddInt64ToListPref(
kNumDaysInHistory - 1, original_content_length, original_update_.Get());
AddInt64ToListPref(
kNumDaysInHistory - 1, received_content_length, received_update_.Get());
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
|
void Add(int original_content_length, int received_content_length) {
original_.Add(original_content_length);
received_.Add(received_content_length);
}
| 171,321
|
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 PHP_FUNCTION(xmlwriter_open_uri)
{
char *valid_file = NULL;
xmlwriter_object *intern;
xmlTextWriterPtr ptr;
char *source;
char resolved_path[MAXPATHLEN + 1];
int source_len;
#ifdef ZEND_ENGINE_2
zval *this = getThis();
ze_xmlwriter_object *ze_obj = NULL;
#endif
#ifndef ZEND_ENGINE_2
xmlOutputBufferPtr out_buffer;
void *ioctx;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &source, &source_len) == FAILURE) {
return;
}
#ifdef ZEND_ENGINE_2
if (this) {
/* We do not use XMLWRITER_FROM_OBJECT, xmlwriter init function here */
ze_obj = (ze_xmlwriter_object*) zend_object_store_get_object(this TSRMLS_CC);
}
#endif
if (source_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string as source");
RETURN_FALSE;
}
valid_file = _xmlwriter_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC);
if (!valid_file) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to resolve file path");
RETURN_FALSE;
}
/* TODO: Fix either the PHP stream or libxml APIs: it can then detect when a given
path is valid and not report out of memory error. Once it is done, remove the
directory check in _xmlwriter_get_valid_file_path */
#ifndef ZEND_ENGINE_2
ioctx = php_xmlwriter_streams_IO_open_write_wrapper(valid_file TSRMLS_CC);
if (ioctx == NULL) {
RETURN_FALSE;
}
out_buffer = xmlOutputBufferCreateIO(php_xmlwriter_streams_IO_write,
php_xmlwriter_streams_IO_close, ioctx, NULL);
if (out_buffer == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create output buffer");
RETURN_FALSE;
}
ptr = xmlNewTextWriter(out_buffer);
#else
ptr = xmlNewTextWriterFilename(valid_file, 0);
#endif
if (!ptr) {
RETURN_FALSE;
}
intern = emalloc(sizeof(xmlwriter_object));
intern->ptr = ptr;
intern->output = NULL;
#ifndef ZEND_ENGINE_2
intern->uri_output = out_buffer;
#else
if (this) {
if (ze_obj->xmlwriter_ptr) {
xmlwriter_free_resource_ptr(ze_obj->xmlwriter_ptr TSRMLS_CC);
}
ze_obj->xmlwriter_ptr = intern;
RETURN_TRUE;
} else
#endif
{
ZEND_REGISTER_RESOURCE(return_value,intern,le_xmlwriter);
}
}
Commit Message:
CWE ID: CWE-254
|
static PHP_FUNCTION(xmlwriter_open_uri)
{
char *valid_file = NULL;
xmlwriter_object *intern;
xmlTextWriterPtr ptr;
char *source;
char resolved_path[MAXPATHLEN + 1];
int source_len;
#ifdef ZEND_ENGINE_2
zval *this = getThis();
ze_xmlwriter_object *ze_obj = NULL;
#endif
#ifndef ZEND_ENGINE_2
xmlOutputBufferPtr out_buffer;
void *ioctx;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &source, &source_len) == FAILURE) {
return;
}
#ifdef ZEND_ENGINE_2
if (this) {
/* We do not use XMLWRITER_FROM_OBJECT, xmlwriter init function here */
ze_obj = (ze_xmlwriter_object*) zend_object_store_get_object(this TSRMLS_CC);
}
#endif
if (source_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string as source");
RETURN_FALSE;
}
valid_file = _xmlwriter_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC);
if (!valid_file) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to resolve file path");
RETURN_FALSE;
}
/* TODO: Fix either the PHP stream or libxml APIs: it can then detect when a given
path is valid and not report out of memory error. Once it is done, remove the
directory check in _xmlwriter_get_valid_file_path */
#ifndef ZEND_ENGINE_2
ioctx = php_xmlwriter_streams_IO_open_write_wrapper(valid_file TSRMLS_CC);
if (ioctx == NULL) {
RETURN_FALSE;
}
out_buffer = xmlOutputBufferCreateIO(php_xmlwriter_streams_IO_write,
php_xmlwriter_streams_IO_close, ioctx, NULL);
if (out_buffer == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create output buffer");
RETURN_FALSE;
}
ptr = xmlNewTextWriter(out_buffer);
#else
ptr = xmlNewTextWriterFilename(valid_file, 0);
#endif
if (!ptr) {
RETURN_FALSE;
}
intern = emalloc(sizeof(xmlwriter_object));
intern->ptr = ptr;
intern->output = NULL;
#ifndef ZEND_ENGINE_2
intern->uri_output = out_buffer;
#else
if (this) {
if (ze_obj->xmlwriter_ptr) {
xmlwriter_free_resource_ptr(ze_obj->xmlwriter_ptr TSRMLS_CC);
}
ze_obj->xmlwriter_ptr = intern;
RETURN_TRUE;
} else
#endif
{
ZEND_REGISTER_RESOURCE(return_value,intern,le_xmlwriter);
}
}
| 165,318
|
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 TabGroupHeader::OnPaint(gfx::Canvas* canvas) {
constexpr SkColor kPlaceholderColor = SkColorSetRGB(0xAA, 0xBB, 0xCC);
gfx::Rect fill_bounds(GetLocalBounds());
fill_bounds.Inset(TabStyle::GetTabOverlap(), 0);
canvas->FillRect(fill_bounds, kPlaceholderColor);
}
Commit Message: Paint tab groups with the group color.
* The background of TabGroupHeader now uses the group color.
* The backgrounds of tabs in the group are tinted with the group color.
This treatment, along with the colors chosen, are intended to be
a placeholder.
Bug: 905491
Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504
Commit-Queue: Bret Sepulveda <bsep@chromium.org>
Reviewed-by: Taylor Bergquist <tbergquist@chromium.org>
Cr-Commit-Position: refs/heads/master@{#660498}
CWE ID: CWE-20
|
void TabGroupHeader::OnPaint(gfx::Canvas* canvas) {
gfx::Rect fill_bounds(GetLocalBounds());
fill_bounds.Inset(TabStyle::GetTabOverlap(), 0);
const SkColor color = GetGroupData()->color();
canvas->FillRect(fill_bounds, color);
title_label_->SetBackgroundColor(color);
}
const TabGroupData* TabGroupHeader::GetGroupData() {
return controller_->GetDataForGroup(group_);
}
| 172,518
|
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: int32_t PepperFlashRendererHost::OnNavigate(
ppapi::host::HostMessageContext* host_context,
const ppapi::URLRequestInfoData& data,
const std::string& target,
bool from_user_action) {
content::PepperPluginInstance* plugin_instance =
host_->GetPluginInstance(pp_instance());
if (!plugin_instance)
return PP_ERROR_FAILED;
ppapi::proxy::HostDispatcher* host_dispatcher =
ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
host_dispatcher->set_allow_plugin_reentrancy();
base::WeakPtr<PepperFlashRendererHost> weak_ptr = weak_factory_.GetWeakPtr();
navigate_replies_.push_back(host_context->MakeReplyMessageContext());
plugin_instance->Navigate(data, target.c_str(), from_user_action);
if (weak_ptr.get()) {
SendReply(navigate_replies_.back(), IPC::Message());
navigate_replies_.pop_back();
}
return PP_OK_COMPLETIONPENDING;
}
Commit Message: PPB_Flash.Navigate(): Disallow certain HTTP request headers.
With this CL, PPB_Flash.Navigate() fails the operation with
PP_ERROR_NOACCESS if the request headers contain non-simple headers.
BUG=332023
TEST=None
Review URL: https://codereview.chromium.org/136393004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@249114 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
int32_t PepperFlashRendererHost::OnNavigate(
ppapi::host::HostMessageContext* host_context,
const ppapi::URLRequestInfoData& data,
const std::string& target,
bool from_user_action) {
content::PepperPluginInstance* plugin_instance =
host_->GetPluginInstance(pp_instance());
if (!plugin_instance)
return PP_ERROR_FAILED;
std::map<std::string, FlashNavigateUsage>& rejected_headers =
g_rejected_headers.Get();
if (rejected_headers.empty()) {
for (size_t i = 0; i < arraysize(kRejectedHttpRequestHeaders); ++i)
rejected_headers[kRejectedHttpRequestHeaders[i]] =
static_cast<FlashNavigateUsage>(i);
}
net::HttpUtil::HeadersIterator header_iter(data.headers.begin(),
data.headers.end(),
"\n\r");
bool rejected = false;
while (header_iter.GetNext()) {
std::string lower_case_header_name = StringToLowerASCII(header_iter.name());
if (!IsSimpleHeader(lower_case_header_name, header_iter.values())) {
rejected = true;
std::map<std::string, FlashNavigateUsage>::const_iterator iter =
rejected_headers.find(lower_case_header_name);
FlashNavigateUsage usage = iter != rejected_headers.end() ?
iter->second : REJECT_OTHER_HEADERS;
RecordFlashNavigateUsage(usage);
}
}
RecordFlashNavigateUsage(TOTAL_NAVIGATE_REQUESTS);
if (rejected) {
RecordFlashNavigateUsage(TOTAL_REJECTED_NAVIGATE_REQUESTS);
return PP_ERROR_NOACCESS;
}
ppapi::proxy::HostDispatcher* host_dispatcher =
ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
host_dispatcher->set_allow_plugin_reentrancy();
base::WeakPtr<PepperFlashRendererHost> weak_ptr = weak_factory_.GetWeakPtr();
navigate_replies_.push_back(host_context->MakeReplyMessageContext());
plugin_instance->Navigate(data, target.c_str(), from_user_action);
if (weak_ptr.get()) {
SendReply(navigate_replies_.back(), IPC::Message());
navigate_replies_.pop_back();
}
return PP_OK_COMPLETIONPENDING;
}
| 171,709
|
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 MockNetworkTransaction::RestartWithAuth(
const AuthCredentials& credentials,
const CompletionCallback& callback) {
if (!IsReadyToRestartForAuth())
return ERR_FAILED;
HttpRequestInfo auth_request_info = *request_;
auth_request_info.extra_headers.AddHeaderFromString("Authorization: Bar");
return StartInternal(&auth_request_info, callback, BoundNetLog());
}
Commit Message: Replace fixed string uses of AddHeaderFromString
Uses of AddHeaderFromString() with a static string may as well be
replaced with SetHeader(). Do so.
BUG=None
Review-Url: https://codereview.chromium.org/2236933005
Cr-Commit-Position: refs/heads/master@{#418161}
CWE ID: CWE-119
|
int MockNetworkTransaction::RestartWithAuth(
const AuthCredentials& credentials,
const CompletionCallback& callback) {
if (!IsReadyToRestartForAuth())
return ERR_FAILED;
HttpRequestInfo auth_request_info = *request_;
auth_request_info.extra_headers.SetHeader("Authorization", "Bar");
return StartInternal(&auth_request_info, callback, BoundNetLog());
}
| 171,601
|
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: BurnLibrary* CrosLibrary::GetBurnLibrary() {
return burn_lib_.GetDefaultImpl(use_stub_impl_);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
|
BurnLibrary* CrosLibrary::GetBurnLibrary() {
| 170,621
|
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 IDNSpoofChecker::SetAllowedUnicodeSet(UErrorCode* status) {
if (U_FAILURE(*status))
return;
const icu::UnicodeSet* recommended_set =
uspoof_getRecommendedUnicodeSet(status);
icu::UnicodeSet allowed_set;
allowed_set.addAll(*recommended_set);
const icu::UnicodeSet* inclusion_set = uspoof_getInclusionUnicodeSet(status);
allowed_set.addAll(*inclusion_set);
allowed_set.remove(0x338u);
allowed_set.remove(0x58au); // Armenian Hyphen
allowed_set.remove(0x2010u);
allowed_set.remove(0x2019u); // Right Single Quotation Mark
allowed_set.remove(0x2027u);
allowed_set.remove(0x30a0u); // Katakana-Hiragana Double Hyphen
allowed_set.remove(0x2bbu); // Modifier Letter Turned Comma
allowed_set.remove(0x2bcu); // Modifier Letter Apostrophe
#if defined(OS_MACOSX)
allowed_set.remove(0x0620u);
allowed_set.remove(0x0F8Cu);
allowed_set.remove(0x0F8Du);
allowed_set.remove(0x0F8Eu);
allowed_set.remove(0x0F8Fu);
#endif
allowed_set.remove(0x01CDu, 0x01DCu); // Latin Ext B; Pinyin
allowed_set.remove(0x1C80u, 0x1C8Fu); // Cyrillic Extended-C
allowed_set.remove(0x1E00u, 0x1E9Bu); // Latin Extended Additional
allowed_set.remove(0x1F00u, 0x1FFFu); // Greek Extended
allowed_set.remove(0xA640u, 0xA69Fu); // Cyrillic Extended-B
allowed_set.remove(0xA720u, 0xA7FFu); // Latin Extended-D
uspoof_setAllowedUnicodeSet(checker_, &allowed_set, status);
}
Commit Message: Block modifier-letter-voicing character from domain names
This character (ˬ) is easy to miss between other characters. It's one of the three characters from Spacing-Modifier-Letters block that ICU lists in its recommended set in uspoof.cpp. Two of these characters (modifier-letter-turned-comma and modifier-letter-apostrophe) are already blocked in crbug/678812.
Bug: 896717
Change-Id: I24b2b591de8cc7822cd55aa005b15676be91175e
Reviewed-on: https://chromium-review.googlesource.com/c/1303037
Commit-Queue: Mustafa Emre Acer <meacer@chromium.org>
Reviewed-by: Tommy Li <tommycli@chromium.org>
Cr-Commit-Position: refs/heads/master@{#604128}
CWE ID: CWE-20
|
void IDNSpoofChecker::SetAllowedUnicodeSet(UErrorCode* status) {
if (U_FAILURE(*status))
return;
const icu::UnicodeSet* recommended_set =
uspoof_getRecommendedUnicodeSet(status);
icu::UnicodeSet allowed_set;
allowed_set.addAll(*recommended_set);
const icu::UnicodeSet* inclusion_set = uspoof_getInclusionUnicodeSet(status);
allowed_set.addAll(*inclusion_set);
allowed_set.remove(0x338u);
allowed_set.remove(0x58au); // Armenian Hyphen
allowed_set.remove(0x2010u);
allowed_set.remove(0x2019u); // Right Single Quotation Mark
allowed_set.remove(0x2027u);
allowed_set.remove(0x30a0u); // Katakana-Hiragana Double Hyphen
allowed_set.remove(0x2bbu); // Modifier Letter Turned Comma
allowed_set.remove(0x2bcu); // Modifier Letter Apostrophe
// Block modifier letter voicing.
allowed_set.remove(0x2ecu);
#if defined(OS_MACOSX)
allowed_set.remove(0x0620u);
allowed_set.remove(0x0F8Cu);
allowed_set.remove(0x0F8Du);
allowed_set.remove(0x0F8Eu);
allowed_set.remove(0x0F8Fu);
#endif
allowed_set.remove(0x01CDu, 0x01DCu); // Latin Ext B; Pinyin
allowed_set.remove(0x1C80u, 0x1C8Fu); // Cyrillic Extended-C
allowed_set.remove(0x1E00u, 0x1E9Bu); // Latin Extended Additional
allowed_set.remove(0x1F00u, 0x1FFFu); // Greek Extended
allowed_set.remove(0xA640u, 0xA69Fu); // Cyrillic Extended-B
allowed_set.remove(0xA720u, 0xA7FFu); // Latin Extended-D
uspoof_setAllowedUnicodeSet(checker_, &allowed_set, status);
}
| 172,638
|
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 SetUp() {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
SyncCredentials credentials;
credentials.email = "foo@bar.com";
credentials.sync_token = "sometoken";
sync_notifier_mock_ = new StrictMock<SyncNotifierMock>();
EXPECT_CALL(*sync_notifier_mock_, AddObserver(_)).
WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierAddObserver));
EXPECT_CALL(*sync_notifier_mock_, SetUniqueId(_));
EXPECT_CALL(*sync_notifier_mock_, SetState(""));
EXPECT_CALL(*sync_notifier_mock_,
UpdateCredentials(credentials.email, credentials.sync_token));
EXPECT_CALL(*sync_notifier_mock_, UpdateEnabledTypes(_)).
Times(AtLeast(1)).
WillRepeatedly(
Invoke(this, &SyncManagerTest::SyncNotifierUpdateEnabledTypes));
EXPECT_CALL(*sync_notifier_mock_, RemoveObserver(_)).
WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierRemoveObserver));
sync_manager_.AddObserver(&observer_);
EXPECT_CALL(observer_, OnInitializationComplete(_, _)).
WillOnce(SaveArg<0>(&js_backend_));
EXPECT_FALSE(sync_notifier_observer_);
EXPECT_FALSE(js_backend_.IsInitialized());
sync_manager_.Init(temp_dir_.path(),
WeakHandle<JsEventHandler>(),
"bogus", 0, false,
base::MessageLoopProxy::current(),
new TestHttpPostProviderFactory(), this,
&extensions_activity_monitor_, this, "bogus",
credentials,
false /* enable_sync_tabs_for_other_clients */,
sync_notifier_mock_, "",
sync_api::SyncManager::TEST_IN_MEMORY,
&encryptor_,
&handler_,
NULL);
EXPECT_TRUE(sync_notifier_observer_);
EXPECT_TRUE(js_backend_.IsInitialized());
EXPECT_EQ(1, update_enabled_types_call_count_);
ModelSafeRoutingInfo routes;
GetModelSafeRoutingInfo(&routes);
for (ModelSafeRoutingInfo::iterator i = routes.begin(); i != routes.end();
++i) {
type_roots_[i->first] = MakeServerNodeForType(
sync_manager_.GetUserShare(), i->first);
}
PumpLoop();
}
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
|
void SetUp() {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
SyncCredentials credentials;
credentials.email = "foo@bar.com";
credentials.sync_token = "sometoken";
sync_notifier_mock_ = new StrictMock<SyncNotifierMock>();
EXPECT_CALL(*sync_notifier_mock_, AddObserver(_)).
WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierAddObserver));
EXPECT_CALL(*sync_notifier_mock_, SetUniqueId(_));
EXPECT_CALL(*sync_notifier_mock_, SetState(""));
EXPECT_CALL(*sync_notifier_mock_,
UpdateCredentials(credentials.email, credentials.sync_token));
EXPECT_CALL(*sync_notifier_mock_, UpdateEnabledTypes(_)).
Times(AtLeast(1)).
WillRepeatedly(
Invoke(this, &SyncManagerTest::SyncNotifierUpdateEnabledTypes));
EXPECT_CALL(*sync_notifier_mock_, RemoveObserver(_)).
WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierRemoveObserver));
sync_manager_.AddObserver(&observer_);
EXPECT_CALL(observer_, OnInitializationComplete(_, _)).
WillOnce(SaveArg<0>(&js_backend_));
EXPECT_FALSE(sync_notifier_observer_);
EXPECT_FALSE(js_backend_.IsInitialized());
sync_manager_.Init(temp_dir_.path(),
WeakHandle<JsEventHandler>(),
"bogus", 0, false,
base::MessageLoopProxy::current(),
new TestHttpPostProviderFactory(), this,
&extensions_activity_monitor_, this, "bogus",
credentials,
sync_notifier_mock_, "",
sync_api::SyncManager::TEST_IN_MEMORY,
&encryptor_,
&handler_,
NULL);
EXPECT_TRUE(sync_notifier_observer_);
EXPECT_TRUE(js_backend_.IsInitialized());
EXPECT_EQ(1, update_enabled_types_call_count_);
ModelSafeRoutingInfo routes;
GetModelSafeRoutingInfo(&routes);
for (ModelSafeRoutingInfo::iterator i = routes.begin(); i != routes.end();
++i) {
type_roots_[i->first] = MakeServerNodeForType(
sync_manager_.GetUserShare(), i->first);
}
PumpLoop();
}
| 170,799
|
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 spl_filesystem_object * spl_filesystem_object_create_info(spl_filesystem_object *source, char *file_path, int file_path_len, int use_copy, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */
{
spl_filesystem_object *intern;
zval *arg1;
zend_error_handling error_handling;
if (!file_path || !file_path_len) {
#if defined(PHP_WIN32)
zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot create SplFileInfo for empty path");
if (file_path && !use_copy) {
efree(file_path);
}
#else
if (file_path && !use_copy) {
efree(file_path);
}
file_path_len = 1;
file_path = "/";
#endif
return NULL;
}
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
ce = ce ? ce : source->info_class;
zend_update_class_constants(ce TSRMLS_CC);
return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC);
Z_TYPE_P(return_value) = IS_OBJECT;
if (ce->constructor->common.scope != spl_ce_SplFileInfo) {
MAKE_STD_ZVAL(arg1);
ZVAL_STRINGL(arg1, file_path, file_path_len, use_copy);
zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1);
zval_ptr_dtor(&arg1);
} else {
spl_filesystem_info_set_filename(intern, file_path, file_path_len, use_copy TSRMLS_CC);
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
return intern;
} /* }}} */
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
static spl_filesystem_object * spl_filesystem_object_create_info(spl_filesystem_object *source, char *file_path, int file_path_len, int use_copy, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */
{
spl_filesystem_object *intern;
zval *arg1;
zend_error_handling error_handling;
if (!file_path || !file_path_len) {
#if defined(PHP_WIN32)
zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot create SplFileInfo for empty path");
if (file_path && !use_copy) {
efree(file_path);
}
#else
if (file_path && !use_copy) {
efree(file_path);
}
file_path_len = 1;
file_path = "/";
#endif
return NULL;
}
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
ce = ce ? ce : source->info_class;
zend_update_class_constants(ce TSRMLS_CC);
return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC);
Z_TYPE_P(return_value) = IS_OBJECT;
if (ce->constructor->common.scope != spl_ce_SplFileInfo) {
MAKE_STD_ZVAL(arg1);
ZVAL_STRINGL(arg1, file_path, file_path_len, use_copy);
zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1);
zval_ptr_dtor(&arg1);
} else {
spl_filesystem_info_set_filename(intern, file_path, file_path_len, use_copy TSRMLS_CC);
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
return intern;
} /* }}} */
| 167,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: static void _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC)
{
zend_hash_destroy(&pglobals->ht_rc);
}
Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free
CWE ID: CWE-415
|
static void _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC)
static void _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC)
{
zend_hash_destroy(&pglobals->ht_rc);
}
| 167,119
|
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 authz_status lua_authz_check(request_rec *r, const char *require_line,
const void *parsed_require_line)
{
apr_pool_t *pool;
ap_lua_vm_spec *spec;
lua_State *L;
ap_lua_server_cfg *server_cfg = ap_get_module_config(r->server->module_config,
&lua_module);
const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config,
&lua_module);
const lua_authz_provider_spec *prov_spec = parsed_require_line;
int result;
int nargs = 0;
spec = create_vm_spec(&pool, r, cfg, server_cfg, prov_spec->file_name,
NULL, 0, prov_spec->function_name, "authz provider");
L = ap_lua_get_lua_state(pool, spec, r);
if (L == NULL) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02314)
"Unable to compile VM for authz provider %s", prov_spec->name);
return AUTHZ_GENERAL_ERROR;
}
lua_getglobal(L, prov_spec->function_name);
if (!lua_isfunction(L, -1)) {
ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(02319)
"Unable to find entry function '%s' in %s (not a valid function)",
prov_spec->function_name, prov_spec->file_name);
ap_lua_release_state(L, spec, r);
return AUTHZ_GENERAL_ERROR;
}
ap_lua_run_lua_request(L, r);
if (prov_spec->args) {
int i;
if (!lua_checkstack(L, prov_spec->args->nelts)) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02315)
"Error: authz provider %s: too many arguments", prov_spec->name);
ap_lua_release_state(L, spec, r);
return AUTHZ_GENERAL_ERROR;
}
for (i = 0; i < prov_spec->args->nelts; i++) {
const char *arg = APR_ARRAY_IDX(prov_spec->args, i, const char *);
lua_pushstring(L, arg);
}
nargs = prov_spec->args->nelts;
}
if (lua_pcall(L, 1 + nargs, 1, 0)) {
const char *err = lua_tostring(L, -1);
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02316)
"Error executing authz provider %s: %s", prov_spec->name, err);
ap_lua_release_state(L, spec, r);
return AUTHZ_GENERAL_ERROR;
}
if (!lua_isnumber(L, -1)) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02317)
"Error: authz provider %s did not return integer", prov_spec->name);
ap_lua_release_state(L, spec, r);
return AUTHZ_GENERAL_ERROR;
}
result = lua_tointeger(L, -1);
ap_lua_release_state(L, spec, r);
switch (result) {
case AUTHZ_DENIED:
case AUTHZ_GRANTED:
case AUTHZ_NEUTRAL:
case AUTHZ_GENERAL_ERROR:
case AUTHZ_DENIED_NO_USER:
return result;
default:
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02318)
"Error: authz provider %s: invalid return value %d",
prov_spec->name, result);
}
return AUTHZ_GENERAL_ERROR;
}
Commit Message: Merge r1642499 from trunk:
*) SECURITY: CVE-2014-8109 (cve.mitre.org)
mod_lua: Fix handling of the Require line when a LuaAuthzProvider is
used in multiple Require directives with different arguments.
PR57204 [Edward Lu <Chaosed0 gmail.com>]
Submitted By: Edward Lu
Committed By: covener
Submitted by: covener
Reviewed/backported by: jim
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x@1642861 13f79535-47bb-0310-9956-ffa450edef68
CWE ID: CWE-264
|
static authz_status lua_authz_check(request_rec *r, const char *require_line,
const void *parsed_require_line)
{
apr_pool_t *pool;
ap_lua_vm_spec *spec;
lua_State *L;
ap_lua_server_cfg *server_cfg = ap_get_module_config(r->server->module_config,
&lua_module);
const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config,
&lua_module);
const lua_authz_provider_func *prov_func = parsed_require_line;
const lua_authz_provider_spec *prov_spec = prov_func->spec;
int result;
int nargs = 0;
spec = create_vm_spec(&pool, r, cfg, server_cfg, prov_spec->file_name,
NULL, 0, prov_spec->function_name, "authz provider");
L = ap_lua_get_lua_state(pool, spec, r);
if (L == NULL) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02314)
"Unable to compile VM for authz provider %s", prov_spec->name);
return AUTHZ_GENERAL_ERROR;
}
lua_getglobal(L, prov_spec->function_name);
if (!lua_isfunction(L, -1)) {
ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(02319)
"Unable to find entry function '%s' in %s (not a valid function)",
prov_spec->function_name, prov_spec->file_name);
ap_lua_release_state(L, spec, r);
return AUTHZ_GENERAL_ERROR;
}
ap_lua_run_lua_request(L, r);
if (prov_func->args) {
int i;
if (!lua_checkstack(L, prov_func->args->nelts)) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02315)
"Error: authz provider %s: too many arguments", prov_spec->name);
ap_lua_release_state(L, spec, r);
return AUTHZ_GENERAL_ERROR;
}
for (i = 0; i < prov_func->args->nelts; i++) {
const char *arg = APR_ARRAY_IDX(prov_func->args, i, const char *);
lua_pushstring(L, arg);
}
nargs = prov_func->args->nelts;
}
if (lua_pcall(L, 1 + nargs, 1, 0)) {
const char *err = lua_tostring(L, -1);
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02316)
"Error executing authz provider %s: %s", prov_spec->name, err);
ap_lua_release_state(L, spec, r);
return AUTHZ_GENERAL_ERROR;
}
if (!lua_isnumber(L, -1)) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02317)
"Error: authz provider %s did not return integer", prov_spec->name);
ap_lua_release_state(L, spec, r);
return AUTHZ_GENERAL_ERROR;
}
result = lua_tointeger(L, -1);
ap_lua_release_state(L, spec, r);
switch (result) {
case AUTHZ_DENIED:
case AUTHZ_GRANTED:
case AUTHZ_NEUTRAL:
case AUTHZ_GENERAL_ERROR:
case AUTHZ_DENIED_NO_USER:
return result;
default:
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02318)
"Error: authz provider %s: invalid return value %d",
prov_spec->name, result);
}
return AUTHZ_GENERAL_ERROR;
}
| 166,250
|
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 mark_files_ro(struct super_block *sb)
{
struct file *f;
lg_global_lock(&files_lglock);
do_file_list_for_each_entry(sb, f) {
if (!file_count(f))
continue;
if (!(f->f_mode & FMODE_WRITE))
continue;
spin_lock(&f->f_lock);
f->f_mode &= ~FMODE_WRITE;
spin_unlock(&f->f_lock);
if (file_check_writeable(f) != 0)
continue;
__mnt_drop_write(f->f_path.mnt);
file_release_write(f);
} while_file_list_for_each_entry;
lg_global_unlock(&files_lglock);
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
CWE ID: CWE-17
|
void mark_files_ro(struct super_block *sb)
| 166,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: ft_var_readpackedpoints( FT_Stream stream,
FT_UInt *point_cnt )
{
FT_UShort *points;
FT_Int n;
FT_Int runcnt;
FT_Int i;
FT_Int j;
FT_Int first;
FT_Memory memory = stream->memory;
FT_Error error = TT_Err_Ok;
FT_UNUSED( error );
*point_cnt = n = FT_GET_BYTE();
if ( n == 0 )
return ALL_POINTS;
if ( n & GX_PT_POINTS_ARE_WORDS )
n = FT_GET_BYTE() | ( ( n & GX_PT_POINT_RUN_COUNT_MASK ) << 8 );
if ( FT_NEW_ARRAY( points, n ) )
return NULL;
i = 0;
while ( i < n )
{
runcnt = FT_GET_BYTE();
if ( runcnt & GX_PT_POINTS_ARE_WORDS )
{
runcnt = runcnt & GX_PT_POINT_RUN_COUNT_MASK;
first = points[i++] = FT_GET_USHORT();
if ( runcnt < 1 )
goto Exit;
/* first point not included in runcount */
for ( j = 0; j < runcnt; ++j )
points[i++] = (FT_UShort)( first += FT_GET_USHORT() );
}
else
{
first = points[i++] = FT_GET_BYTE();
if ( runcnt < 1 )
goto Exit;
for ( j = 0; j < runcnt; ++j )
points[i++] = (FT_UShort)( first += FT_GET_BYTE() );
}
}
Exit:
return points;
}
Commit Message:
CWE ID: CWE-119
|
ft_var_readpackedpoints( FT_Stream stream,
FT_UInt *point_cnt )
{
FT_UShort *points;
FT_Int n;
FT_Int runcnt;
FT_Int i;
FT_Int j;
FT_Int first;
FT_Memory memory = stream->memory;
FT_Error error = TT_Err_Ok;
FT_UNUSED( error );
*point_cnt = n = FT_GET_BYTE();
if ( n == 0 )
return ALL_POINTS;
if ( n & GX_PT_POINTS_ARE_WORDS )
n = FT_GET_BYTE() | ( ( n & GX_PT_POINT_RUN_COUNT_MASK ) << 8 );
if ( FT_NEW_ARRAY( points, n ) )
return NULL;
i = 0;
while ( i < n )
{
runcnt = FT_GET_BYTE();
if ( runcnt & GX_PT_POINTS_ARE_WORDS )
{
runcnt = runcnt & GX_PT_POINT_RUN_COUNT_MASK;
first = points[i++] = FT_GET_USHORT();
if ( runcnt < 1 || i + runcnt >= n )
goto Exit;
/* first point not included in runcount */
for ( j = 0; j < runcnt; ++j )
points[i++] = (FT_UShort)( first += FT_GET_USHORT() );
}
else
{
first = points[i++] = FT_GET_BYTE();
if ( runcnt < 1 || i + runcnt >= n )
goto Exit;
for ( j = 0; j < runcnt; ++j )
points[i++] = (FT_UShort)( first += FT_GET_BYTE() );
}
}
Exit:
return points;
}
| 164,897
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static boolean str_fill_input_buffer(j_decompress_ptr cinfo)
{
int c;
struct str_src_mgr * src = (struct str_src_mgr *)cinfo->src;
if (src->abort) return FALSE;
if (src->index == 0) {
c = 0xFF;
src->index++;
src->index++;
}
else if (src->index == 1) {
c = 0xD8;
src->index++;
}
else c = src->str->getChar();
if (c != EOF)
{
src->buffer = c;
src->pub.next_input_byte = &src->buffer;
src->pub.bytes_in_buffer = 1;
return TRUE;
}
else return FALSE;
}
Commit Message:
CWE ID: CWE-20
|
static boolean str_fill_input_buffer(j_decompress_ptr cinfo)
{
int c;
struct str_src_mgr * src = (struct str_src_mgr *)cinfo->src;
if (src->index == 0) {
c = 0xFF;
src->index++;
src->index++;
}
else if (src->index == 1) {
c = 0xD8;
src->index++;
}
else c = src->str->getChar();
if (c != EOF)
{
src->buffer = c;
src->pub.next_input_byte = &src->buffer;
src->pub.bytes_in_buffer = 1;
return TRUE;
}
else return FALSE;
}
| 165,395
|
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: wb_id(netdissect_options *ndo,
const struct pkt_id *id, u_int len)
{
int i;
const char *cp;
const struct id_off *io;
char c;
int nid;
ND_PRINT((ndo, " wb-id:"));
if (len < sizeof(*id) || !ND_TTEST(*id))
return (-1);
len -= sizeof(*id);
ND_PRINT((ndo, " %u/%s:%u (max %u/%s:%u) ",
EXTRACT_32BITS(&id->pi_ps.slot),
ipaddr_string(ndo, &id->pi_ps.page.p_sid),
EXTRACT_32BITS(&id->pi_ps.page.p_uid),
EXTRACT_32BITS(&id->pi_mslot),
ipaddr_string(ndo, &id->pi_mpage.p_sid),
EXTRACT_32BITS(&id->pi_mpage.p_uid)));
nid = EXTRACT_16BITS(&id->pi_ps.nid);
len -= sizeof(*io) * nid;
io = (struct id_off *)(id + 1);
cp = (char *)(io + nid);
if (!ND_TTEST2(cp, len)) {
ND_PRINT((ndo, "\""));
fn_print(ndo, (u_char *)cp, (u_char *)cp + len);
ND_PRINT((ndo, "\""));
}
c = '<';
for (i = 0; i < nid && ND_TTEST(*io); ++io, ++i) {
ND_PRINT((ndo, "%c%s:%u",
c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off)));
c = ',';
}
if (i >= nid) {
ND_PRINT((ndo, ">"));
return (0);
}
return (-1);
}
Commit Message: whiteboard: fixup a few reversed tests (GH #446)
This is a follow-up to commit 3a3ec26.
CWE ID: CWE-20
|
wb_id(netdissect_options *ndo,
const struct pkt_id *id, u_int len)
{
int i;
const char *cp;
const struct id_off *io;
char c;
int nid;
ND_PRINT((ndo, " wb-id:"));
if (len < sizeof(*id) || !ND_TTEST(*id))
return (-1);
len -= sizeof(*id);
ND_PRINT((ndo, " %u/%s:%u (max %u/%s:%u) ",
EXTRACT_32BITS(&id->pi_ps.slot),
ipaddr_string(ndo, &id->pi_ps.page.p_sid),
EXTRACT_32BITS(&id->pi_ps.page.p_uid),
EXTRACT_32BITS(&id->pi_mslot),
ipaddr_string(ndo, &id->pi_mpage.p_sid),
EXTRACT_32BITS(&id->pi_mpage.p_uid)));
nid = EXTRACT_16BITS(&id->pi_ps.nid);
len -= sizeof(*io) * nid;
io = (struct id_off *)(id + 1);
cp = (char *)(io + nid);
if (ND_TTEST2(cp, len)) {
ND_PRINT((ndo, "\""));
fn_print(ndo, (u_char *)cp, (u_char *)cp + len);
ND_PRINT((ndo, "\""));
}
c = '<';
for (i = 0; i < nid && ND_TTEST(*io); ++io, ++i) {
ND_PRINT((ndo, "%c%s:%u",
c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off)));
c = ',';
}
if (i >= nid) {
ND_PRINT((ndo, ">"));
return (0);
}
return (-1);
}
| 168,892
|
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 *listen_fn_(UNUSED_ATTR void *context) {
prctl(PR_SET_NAME, (unsigned long)LISTEN_THREAD_NAME_, 0, 0, 0);
listen_socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_socket_ == -1) {
LOG_ERROR("%s socket creation failed: %s", __func__, strerror(errno));
goto cleanup;
}
int enable = 1;
if (setsockopt(listen_socket_, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == -1) {
LOG_ERROR("%s unable to set SO_REUSEADDR: %s", __func__, strerror(errno));
goto cleanup;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(LOCALHOST_);
addr.sin_port = htons(LISTEN_PORT_);
if (bind(listen_socket_, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
LOG_ERROR("%s unable to bind listen socket: %s", __func__, strerror(errno));
goto cleanup;
}
if (listen(listen_socket_, 10) == -1) {
LOG_ERROR("%s unable to listen: %s", __func__, strerror(errno));
goto cleanup;
}
for (;;) {
int client_socket = accept(listen_socket_, NULL, NULL);
if (client_socket == -1) {
if (errno == EINVAL || errno == EBADF) {
break;
}
LOG_WARN("%s error accepting socket: %s", __func__, strerror(errno));
continue;
}
/* When a new client connects, we have to send the btsnoop file header. This allows
a decoder to treat the session as a new, valid btsnoop file. */
pthread_mutex_lock(&client_socket_lock_);
safe_close_(&client_socket_);
client_socket_ = client_socket;
send(client_socket_, "btsnoop\0\0\0\0\1\0\0\x3\xea", 16, 0);
pthread_mutex_unlock(&client_socket_lock_);
}
cleanup:
safe_close_(&listen_socket_);
return NULL;
}
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
|
static void *listen_fn_(UNUSED_ATTR void *context) {
prctl(PR_SET_NAME, (unsigned long)LISTEN_THREAD_NAME_, 0, 0, 0);
listen_socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_socket_ == -1) {
LOG_ERROR("%s socket creation failed: %s", __func__, strerror(errno));
goto cleanup;
}
int enable = 1;
if (setsockopt(listen_socket_, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == -1) {
LOG_ERROR("%s unable to set SO_REUSEADDR: %s", __func__, strerror(errno));
goto cleanup;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(LOCALHOST_);
addr.sin_port = htons(LISTEN_PORT_);
if (bind(listen_socket_, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
LOG_ERROR("%s unable to bind listen socket: %s", __func__, strerror(errno));
goto cleanup;
}
if (listen(listen_socket_, 10) == -1) {
LOG_ERROR("%s unable to listen: %s", __func__, strerror(errno));
goto cleanup;
}
for (;;) {
int client_socket = TEMP_FAILURE_RETRY(accept(listen_socket_, NULL, NULL));
if (client_socket == -1) {
if (errno == EINVAL || errno == EBADF) {
break;
}
LOG_WARN("%s error accepting socket: %s", __func__, strerror(errno));
continue;
}
/* When a new client connects, we have to send the btsnoop file header. This allows
a decoder to treat the session as a new, valid btsnoop file. */
pthread_mutex_lock(&client_socket_lock_);
safe_close_(&client_socket_);
client_socket_ = client_socket;
TEMP_FAILURE_RETRY(send(client_socket_, "btsnoop\0\0\0\0\1\0\0\x3\xea", 16, 0));
pthread_mutex_unlock(&client_socket_lock_);
}
cleanup:
safe_close_(&listen_socket_);
return NULL;
}
| 173,475
|
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 jslTokenAsString(int token, char *str, size_t len) {
if (token>32 && token<128) {
assert(len>=4);
str[0] = '\'';
str[1] = (char)token;
str[2] = '\'';
str[3] = 0;
return;
}
switch (token) {
case LEX_EOF : strncpy(str, "EOF", len); return;
case LEX_ID : strncpy(str, "ID", len); return;
case LEX_INT : strncpy(str, "INT", len); return;
case LEX_FLOAT : strncpy(str, "FLOAT", len); return;
case LEX_STR : strncpy(str, "STRING", len); return;
case LEX_UNFINISHED_STR : strncpy(str, "UNFINISHED STRING", len); return;
case LEX_TEMPLATE_LITERAL : strncpy(str, "TEMPLATE LITERAL", len); return;
case LEX_UNFINISHED_TEMPLATE_LITERAL : strncpy(str, "UNFINISHED TEMPLATE LITERAL", len); return;
case LEX_REGEX : strncpy(str, "REGEX", len); return;
case LEX_UNFINISHED_REGEX : strncpy(str, "UNFINISHED REGEX", len); return;
case LEX_UNFINISHED_COMMENT : strncpy(str, "UNFINISHED COMMENT", len); return;
}
if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) {
const char tokenNames[] =
/* LEX_EQUAL : */ "==\0"
/* LEX_TYPEEQUAL : */ "===\0"
/* LEX_NEQUAL : */ "!=\0"
/* LEX_NTYPEEQUAL : */ "!==\0"
/* LEX_LEQUAL : */ "<=\0"
/* LEX_LSHIFT : */ "<<\0"
/* LEX_LSHIFTEQUAL : */ "<<=\0"
/* LEX_GEQUAL : */ ">=\0"
/* LEX_RSHIFT : */ ">>\0"
/* LEX_RSHIFTUNSIGNED */ ">>>\0"
/* LEX_RSHIFTEQUAL : */ ">>=\0"
/* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=\0"
/* LEX_PLUSEQUAL : */ "+=\0"
/* LEX_MINUSEQUAL : */ "-=\0"
/* LEX_PLUSPLUS : */ "++\0"
/* LEX_MINUSMINUS */ "--\0"
/* LEX_MULEQUAL : */ "*=\0"
/* LEX_DIVEQUAL : */ "/=\0"
/* LEX_MODEQUAL : */ "%=\0"
/* LEX_ANDEQUAL : */ "&=\0"
/* LEX_ANDAND : */ "&&\0"
/* LEX_OREQUAL : */ "|=\0"
/* LEX_OROR : */ "||\0"
/* LEX_XOREQUAL : */ "^=\0"
/* LEX_ARROW_FUNCTION */ "=>\0"
/*LEX_R_IF : */ "if\0"
/*LEX_R_ELSE : */ "else\0"
/*LEX_R_DO : */ "do\0"
/*LEX_R_WHILE : */ "while\0"
/*LEX_R_FOR : */ "for\0"
/*LEX_R_BREAK : */ "return\0"
/*LEX_R_CONTINUE */ "continue\0"
/*LEX_R_FUNCTION */ "function\0"
/*LEX_R_RETURN */ "return\0"
/*LEX_R_VAR : */ "var\0"
/*LEX_R_LET : */ "let\0"
/*LEX_R_CONST : */ "const\0"
/*LEX_R_THIS : */ "this\0"
/*LEX_R_THROW : */ "throw\0"
/*LEX_R_TRY : */ "try\0"
/*LEX_R_CATCH : */ "catch\0"
/*LEX_R_FINALLY : */ "finally\0"
/*LEX_R_TRUE : */ "true\0"
/*LEX_R_FALSE : */ "false\0"
/*LEX_R_NULL : */ "null\0"
/*LEX_R_UNDEFINED */ "undefined\0"
/*LEX_R_NEW : */ "new\0"
/*LEX_R_IN : */ "in\0"
/*LEX_R_INSTANCEOF */ "instanceof\0"
/*LEX_R_SWITCH */ "switch\0"
/*LEX_R_CASE */ "case\0"
/*LEX_R_DEFAULT */ "default\0"
/*LEX_R_DELETE */ "delete\0"
/*LEX_R_TYPEOF : */ "typeof\0"
/*LEX_R_VOID : */ "void\0"
/*LEX_R_DEBUGGER : */ "debugger\0"
/*LEX_R_CLASS : */ "class\0"
/*LEX_R_EXTENDS : */ "extends\0"
/*LEX_R_SUPER : */ "super\0"
/*LEX_R_STATIC : */ "static\0"
;
unsigned int p = 0;
int n = token-_LEX_OPERATOR_START;
while (n>0 && p<sizeof(tokenNames)) {
while (tokenNames[p] && p<sizeof(tokenNames)) p++;
p++; // skip the zero
n--; // next token
}
assert(n==0);
strncpy(str, &tokenNames[p], len);
return;
}
assert(len>=10);
strncpy(str, "?[",len);
itostr(token, &str[2], 10);
strncat(str, "]",len);
}
Commit Message: Fix strncat/cpy bounding issues (fix #1425)
CWE ID: CWE-119
|
void jslTokenAsString(int token, char *str, size_t len) {
if (token>32 && token<128) {
assert(len>=4);
str[0] = '\'';
str[1] = (char)token;
str[2] = '\'';
str[3] = 0;
return;
}
switch (token) {
case LEX_EOF : strncpy(str, "EOF", len); return;
case LEX_ID : strncpy(str, "ID", len); return;
case LEX_INT : strncpy(str, "INT", len); return;
case LEX_FLOAT : strncpy(str, "FLOAT", len); return;
case LEX_STR : strncpy(str, "STRING", len); return;
case LEX_UNFINISHED_STR : strncpy(str, "UNFINISHED STRING", len); return;
case LEX_TEMPLATE_LITERAL : strncpy(str, "TEMPLATE LITERAL", len); return;
case LEX_UNFINISHED_TEMPLATE_LITERAL : strncpy(str, "UNFINISHED TEMPLATE LITERAL", len); return;
case LEX_REGEX : strncpy(str, "REGEX", len); return;
case LEX_UNFINISHED_REGEX : strncpy(str, "UNFINISHED REGEX", len); return;
case LEX_UNFINISHED_COMMENT : strncpy(str, "UNFINISHED COMMENT", len); return;
}
if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) {
const char tokenNames[] =
/* LEX_EQUAL : */ "==\0"
/* LEX_TYPEEQUAL : */ "===\0"
/* LEX_NEQUAL : */ "!=\0"
/* LEX_NTYPEEQUAL : */ "!==\0"
/* LEX_LEQUAL : */ "<=\0"
/* LEX_LSHIFT : */ "<<\0"
/* LEX_LSHIFTEQUAL : */ "<<=\0"
/* LEX_GEQUAL : */ ">=\0"
/* LEX_RSHIFT : */ ">>\0"
/* LEX_RSHIFTUNSIGNED */ ">>>\0"
/* LEX_RSHIFTEQUAL : */ ">>=\0"
/* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=\0"
/* LEX_PLUSEQUAL : */ "+=\0"
/* LEX_MINUSEQUAL : */ "-=\0"
/* LEX_PLUSPLUS : */ "++\0"
/* LEX_MINUSMINUS */ "--\0"
/* LEX_MULEQUAL : */ "*=\0"
/* LEX_DIVEQUAL : */ "/=\0"
/* LEX_MODEQUAL : */ "%=\0"
/* LEX_ANDEQUAL : */ "&=\0"
/* LEX_ANDAND : */ "&&\0"
/* LEX_OREQUAL : */ "|=\0"
/* LEX_OROR : */ "||\0"
/* LEX_XOREQUAL : */ "^=\0"
/* LEX_ARROW_FUNCTION */ "=>\0"
/*LEX_R_IF : */ "if\0"
/*LEX_R_ELSE : */ "else\0"
/*LEX_R_DO : */ "do\0"
/*LEX_R_WHILE : */ "while\0"
/*LEX_R_FOR : */ "for\0"
/*LEX_R_BREAK : */ "return\0"
/*LEX_R_CONTINUE */ "continue\0"
/*LEX_R_FUNCTION */ "function\0"
/*LEX_R_RETURN */ "return\0"
/*LEX_R_VAR : */ "var\0"
/*LEX_R_LET : */ "let\0"
/*LEX_R_CONST : */ "const\0"
/*LEX_R_THIS : */ "this\0"
/*LEX_R_THROW : */ "throw\0"
/*LEX_R_TRY : */ "try\0"
/*LEX_R_CATCH : */ "catch\0"
/*LEX_R_FINALLY : */ "finally\0"
/*LEX_R_TRUE : */ "true\0"
/*LEX_R_FALSE : */ "false\0"
/*LEX_R_NULL : */ "null\0"
/*LEX_R_UNDEFINED */ "undefined\0"
/*LEX_R_NEW : */ "new\0"
/*LEX_R_IN : */ "in\0"
/*LEX_R_INSTANCEOF */ "instanceof\0"
/*LEX_R_SWITCH */ "switch\0"
/*LEX_R_CASE */ "case\0"
/*LEX_R_DEFAULT */ "default\0"
/*LEX_R_DELETE */ "delete\0"
/*LEX_R_TYPEOF : */ "typeof\0"
/*LEX_R_VOID : */ "void\0"
/*LEX_R_DEBUGGER : */ "debugger\0"
/*LEX_R_CLASS : */ "class\0"
/*LEX_R_EXTENDS : */ "extends\0"
/*LEX_R_SUPER : */ "super\0"
/*LEX_R_STATIC : */ "static\0"
;
unsigned int p = 0;
int n = token-_LEX_OPERATOR_START;
while (n>0 && p<sizeof(tokenNames)) {
while (tokenNames[p] && p<sizeof(tokenNames)) p++;
p++; // skip the zero
n--; // next token
}
assert(n==0);
strncpy(str, &tokenNames[p], len);
return;
}
assert(len>=10);
espruino_snprintf(str, len, "?[%d]", token);
}
| 169,212
|
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 pdf_load_xrefs(FILE *fp, pdf_t *pdf)
{
int i, ver, is_linear;
long pos, pos_count;
char x, *c, buf[256];
c = NULL;
/* Count number of xrefs */
pdf->n_xrefs = 0;
fseek(fp, 0, SEEK_SET);
while (get_next_eof(fp) >= 0)
++pdf->n_xrefs;
if (!pdf->n_xrefs)
return 0;
/* Load in the start/end positions */
fseek(fp, 0, SEEK_SET);
pdf->xrefs = calloc(1, sizeof(xref_t) * pdf->n_xrefs);
ver = 1;
for (i=0; i<pdf->n_xrefs; i++)
{
/* Seek to %%EOF */
if ((pos = get_next_eof(fp)) < 0)
break;
/* Set and increment the version */
pdf->xrefs[i].version = ver++;
/* Rewind until we find end of "startxref" */
pos_count = 0;
while (SAFE_F(fp, ((x = fgetc(fp)) != 'f')))
fseek(fp, pos - (++pos_count), SEEK_SET);
/* Suck in end of "startxref" to start of %%EOF */
if (pos_count >= sizeof(buf)) {
ERR("Failed to locate the startxref token. "
"This might be a corrupt PDF.\n");
return -1;
}
memset(buf, 0, sizeof(buf));
SAFE_E(fread(buf, 1, pos_count, fp), pos_count,
"Failed to read startxref.\n");
c = buf;
while (*c == ' ' || *c == '\n' || *c == '\r')
++c;
/* xref start position */
pdf->xrefs[i].start = atol(c);
/* If xref is 0 handle linear xref table */
if (pdf->xrefs[i].start == 0)
get_xref_linear_skipped(fp, &pdf->xrefs[i]);
/* Non-linear, normal operation, so just find the end of the xref */
else
{
/* xref end position */
pos = ftell(fp);
fseek(fp, pdf->xrefs[i].start, SEEK_SET);
pdf->xrefs[i].end = get_next_eof(fp);
/* Look for next EOF and xref data */
fseek(fp, pos, SEEK_SET);
}
/* Check validity */
if (!is_valid_xref(fp, pdf, &pdf->xrefs[i]))
{
is_linear = pdf->xrefs[i].is_linear;
memset(&pdf->xrefs[i], 0, sizeof(xref_t));
pdf->xrefs[i].is_linear = is_linear;
rewind(fp);
get_next_eof(fp);
continue;
}
/* Load the entries from the xref */
load_xref_entries(fp, &pdf->xrefs[i]);
}
/* Now we have all xref tables, if this is linearized, we need
* to make adjustments so that things spit out properly
*/
if (pdf->xrefs[0].is_linear)
resolve_linearized_pdf(pdf);
/* Ok now we have all xref data. Go through those versions of the
* PDF and try to obtain creator information
*/
load_creator(fp, pdf);
return pdf->n_xrefs;
}
Commit Message: Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf
CWE ID: CWE-787
|
int pdf_load_xrefs(FILE *fp, pdf_t *pdf)
{
int i, ver, is_linear;
long pos, pos_count;
char x, *c, buf[256];
c = NULL;
/* Count number of xrefs */
pdf->n_xrefs = 0;
fseek(fp, 0, SEEK_SET);
while (get_next_eof(fp) >= 0)
++pdf->n_xrefs;
if (!pdf->n_xrefs)
return 0;
/* Load in the start/end positions */
fseek(fp, 0, SEEK_SET);
pdf->xrefs = safe_calloc(sizeof(xref_t) * pdf->n_xrefs);
ver = 1;
for (i=0; i<pdf->n_xrefs; i++)
{
/* Seek to %%EOF */
if ((pos = get_next_eof(fp)) < 0)
break;
/* Set and increment the version */
pdf->xrefs[i].version = ver++;
/* Rewind until we find end of "startxref" */
pos_count = 0;
while (SAFE_F(fp, ((x = fgetc(fp)) != 'f')))
fseek(fp, pos - (++pos_count), SEEK_SET);
/* Suck in end of "startxref" to start of %%EOF */
if (pos_count >= sizeof(buf)) {
ERR("Failed to locate the startxref token. "
"This might be a corrupt PDF.\n");
return -1;
}
memset(buf, 0, sizeof(buf));
SAFE_E(fread(buf, 1, pos_count, fp), pos_count,
"Failed to read startxref.\n");
c = buf;
while (*c == ' ' || *c == '\n' || *c == '\r')
++c;
/* xref start position */
pdf->xrefs[i].start = atol(c);
/* If xref is 0 handle linear xref table */
if (pdf->xrefs[i].start == 0)
get_xref_linear_skipped(fp, &pdf->xrefs[i]);
/* Non-linear, normal operation, so just find the end of the xref */
else
{
/* xref end position */
pos = ftell(fp);
fseek(fp, pdf->xrefs[i].start, SEEK_SET);
pdf->xrefs[i].end = get_next_eof(fp);
/* Look for next EOF and xref data */
fseek(fp, pos, SEEK_SET);
}
/* Check validity */
if (!is_valid_xref(fp, pdf, &pdf->xrefs[i]))
{
is_linear = pdf->xrefs[i].is_linear;
memset(&pdf->xrefs[i], 0, sizeof(xref_t));
pdf->xrefs[i].is_linear = is_linear;
rewind(fp);
get_next_eof(fp);
continue;
}
/* Load the entries from the xref */
load_xref_entries(fp, &pdf->xrefs[i]);
}
/* Now we have all xref tables, if this is linearized, we need
* to make adjustments so that things spit out properly
*/
if (pdf->xrefs[0].is_linear)
resolve_linearized_pdf(pdf);
/* Ok now we have all xref data. Go through those versions of the
* PDF and try to obtain creator information
*/
load_creator(fp, pdf);
return pdf->n_xrefs;
}
| 169,572
|
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(xml_parse_into_struct)
{
xml_parser *parser;
zval *pind, **xdata, **info = NULL;
char *data;
int data_len, ret;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsZ|Z", &pind, &data, &data_len, &xdata, &info) == FAILURE) {
return;
}
if (info) {
zval_dtor(*info);
array_init(*info);
}
ZEND_FETCH_RESOURCE(parser,xml_parser *, &pind, -1, "XML Parser", le_xml_parser);
zval_dtor(*xdata);
array_init(*xdata);
parser->data = *xdata;
if (info) {
parser->info = *info;
}
parser->level = 0;
parser->ltags = safe_emalloc(XML_MAXLEVEL, sizeof(char *), 0);
XML_SetDefaultHandler(parser->parser, _xml_defaultHandler);
XML_SetElementHandler(parser->parser, _xml_startElementHandler, _xml_endElementHandler);
XML_SetCharacterDataHandler(parser->parser, _xml_characterDataHandler);
parser->isparsing = 1;
ret = XML_Parse(parser->parser, data, data_len, 1);
parser->isparsing = 0;
RETVAL_LONG(ret);
}
Commit Message:
CWE ID: CWE-119
|
PHP_FUNCTION(xml_parse_into_struct)
{
xml_parser *parser;
zval *pind, **xdata, **info = NULL;
char *data;
int data_len, ret;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsZ|Z", &pind, &data, &data_len, &xdata, &info) == FAILURE) {
return;
}
if (info) {
zval_dtor(*info);
array_init(*info);
}
ZEND_FETCH_RESOURCE(parser,xml_parser *, &pind, -1, "XML Parser", le_xml_parser);
zval_dtor(*xdata);
array_init(*xdata);
parser->data = *xdata;
if (info) {
parser->info = *info;
}
parser->level = 0;
parser->ltags = safe_emalloc(XML_MAXLEVEL, sizeof(char *), 0);
XML_SetDefaultHandler(parser->parser, _xml_defaultHandler);
XML_SetElementHandler(parser->parser, _xml_startElementHandler, _xml_endElementHandler);
XML_SetCharacterDataHandler(parser->parser, _xml_characterDataHandler);
parser->isparsing = 1;
ret = XML_Parse(parser->parser, data, data_len, 1);
parser->isparsing = 0;
RETVAL_LONG(ret);
}
| 165,037
|
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_METHOD(Phar, getSupportedSignatures)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
add_next_index_stringl(return_value, "MD5", 3, 1);
add_next_index_stringl(return_value, "SHA-1", 5, 1);
#ifdef PHAR_HASH_OK
add_next_index_stringl(return_value, "SHA-256", 7, 1);
add_next_index_stringl(return_value, "SHA-512", 7, 1);
#endif
#if PHAR_HAVE_OPENSSL
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
#else
if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) {
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
}
#endif
}
Commit Message:
CWE ID: CWE-20
|
PHP_METHOD(Phar, getSupportedSignatures)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
add_next_index_stringl(return_value, "MD5", 3, 1);
add_next_index_stringl(return_value, "SHA-1", 5, 1);
#ifdef PHAR_HASH_OK
add_next_index_stringl(return_value, "SHA-256", 7, 1);
add_next_index_stringl(return_value, "SHA-512", 7, 1);
#endif
#if PHAR_HAVE_OPENSSL
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
#else
if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) {
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
}
#endif
}
| 165,292
|
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 xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
unsigned int epid, unsigned int streamid)
{
XHCIEPContext *epctx;
assert(slotid >= 1 && slotid <= xhci->numslots);
assert(epid >= 1 && epid <= 31);
if (!xhci->slots[slotid-1].enabled) {
DPRINTF("xhci: xhci_kick_ep for disabled slot %d\n", slotid);
return;
}
epctx = xhci->slots[slotid-1].eps[epid-1];
if (!epctx) {
DPRINTF("xhci: xhci_kick_ep for disabled endpoint %d,%d\n",
epid, slotid);
return;
return;
}
xhci_kick_epctx(epctx, streamid);
}
Commit Message:
CWE ID: CWE-835
|
static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
unsigned int epid, unsigned int streamid)
{
XHCIEPContext *epctx;
assert(slotid >= 1 && slotid <= xhci->numslots);
assert(epid >= 1 && epid <= 31);
if (!xhci->slots[slotid-1].enabled) {
DPRINTF("xhci: xhci_kick_ep for disabled slot %d\n", slotid);
return;
}
epctx = xhci->slots[slotid-1].eps[epid-1];
if (!epctx) {
DPRINTF("xhci: xhci_kick_ep for disabled endpoint %d,%d\n",
epid, slotid);
return;
return;
}
if (epctx->kick_active) {
return;
}
xhci_kick_epctx(epctx, streamid);
}
| 164,795
|
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 SharedWorkerDevToolsAgentHost::WorkerRestarted(
SharedWorkerHost* worker_host) {
DCHECK_EQ(WORKER_TERMINATED, state_);
DCHECK(!worker_host_);
state_ = WORKER_NOT_READY;
worker_host_ = worker_host;
for (DevToolsSession* session : sessions())
session->SetRenderer(GetProcess(), nullptr);
}
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 SharedWorkerDevToolsAgentHost::WorkerRestarted(
SharedWorkerHost* worker_host) {
DCHECK_EQ(WORKER_TERMINATED, state_);
DCHECK(!worker_host_);
state_ = WORKER_NOT_READY;
worker_host_ = worker_host;
for (DevToolsSession* session : sessions())
session->SetRenderer(worker_host_->process_id(), nullptr);
}
| 172,791
|
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: _TIFFmalloc(tsize_t s)
{
return (malloc((size_t) s));
}
Commit Message: * libtiff/tif_{unix,vms,win32}.c (_TIFFmalloc): ANSI C does not
require malloc() to return NULL pointer if requested allocation
size is zero. Assure that _TIFFmalloc does.
CWE ID: CWE-369
|
_TIFFmalloc(tsize_t s)
{
if (s == 0)
return ((void *) NULL);
return (malloc((size_t) s));
}
| 169,460
|
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: pvscsi_convert_sglist(PVSCSIRequest *r)
{
int chunk_size;
uint64_t data_length = r->req.dataLen;
PVSCSISGState sg = r->sg;
while (data_length) {
while (!sg.resid) {
pvscsi_get_next_sg_elem(&sg);
trace_pvscsi_convert_sglist(r->req.context, r->sg.dataAddr,
r->sg.resid);
}
assert(data_length > 0);
chunk_size = MIN((unsigned) data_length, sg.resid);
if (chunk_size) {
qemu_sglist_add(&r->sgl, sg.dataAddr, chunk_size);
}
sg.dataAddr += chunk_size;
data_length -= chunk_size;
sg.resid -= chunk_size;
}
}
Commit Message:
CWE ID: CWE-399
|
pvscsi_convert_sglist(PVSCSIRequest *r)
{
uint32_t chunk_size, elmcnt = 0;
uint64_t data_length = r->req.dataLen;
PVSCSISGState sg = r->sg;
while (data_length && elmcnt < PVSCSI_MAX_SG_ELEM) {
while (!sg.resid && elmcnt++ < PVSCSI_MAX_SG_ELEM) {
pvscsi_get_next_sg_elem(&sg);
trace_pvscsi_convert_sglist(r->req.context, r->sg.dataAddr,
r->sg.resid);
}
chunk_size = MIN(data_length, sg.resid);
if (chunk_size) {
qemu_sglist_add(&r->sgl, sg.dataAddr, chunk_size);
}
sg.dataAddr += chunk_size;
data_length -= chunk_size;
sg.resid -= chunk_size;
}
}
| 164,936
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: read_bytes(FILE *fp, void *buf, size_t bytes_to_read, int fail_on_eof,
char *errbuf)
{
size_t amt_read;
amt_read = fread(buf, 1, bytes_to_read, fp);
if (amt_read != bytes_to_read) {
if (ferror(fp)) {
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "error reading dump file");
} else {
if (amt_read == 0 && !fail_on_eof)
return (0); /* EOF */
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"truncated dump file; tried to read %" PRIsize " bytes, only got %" PRIsize,
bytes_to_read, amt_read);
}
return (-1);
}
return (1);
}
Commit Message: do sanity checks on PHB header length before allocating memory. There was no fault; but doing the check results in a more consistent error
CWE ID: CWE-20
|
read_bytes(FILE *fp, void *buf, size_t bytes_to_read, int fail_on_eof,
char *errbuf)
{
size_t amt_read;
amt_read = fread(buf, 1, bytes_to_read, fp);
if (amt_read != bytes_to_read) {
if (ferror(fp)) {
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "error reading dump file");
} else {
if (amt_read == 0 && !fail_on_eof)
return (0); /* EOF */
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"truncated pcapng dump file; tried to read %" PRIsize " bytes, only got %" PRIsize,
bytes_to_read, amt_read);
}
return (-1);
}
return (1);
}
| 170,188
|
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: struct addr_t* MACH0_(get_entrypoint)(struct MACH0_(obj_t)* bin) {
struct addr_t *entry;
int i;
if (!bin->entry && !bin->sects) {
return NULL;
}
if (!(entry = calloc (1, sizeof (struct addr_t)))) {
return NULL;
}
if (bin->entry) {
entry->addr = entry_to_vaddr (bin);
entry->offset = addr_to_offset (bin, entry->addr);
entry->haddr = sdb_num_get (bin->kv, "mach0.entry.offset", 0);
}
if (!bin->entry || entry->offset == 0) {
for (i = 0; i < bin->nsects; i++) {
if (!strncmp (bin->sects[i].sectname, "__text", 6)) {
entry->offset = (ut64)bin->sects[i].offset;
sdb_num_set (bin->kv, "mach0.entry", entry->offset, 0);
entry->addr = (ut64)bin->sects[i].addr;
if (!entry->addr) { // workaround for object files
entry->addr = entry->offset;
}
break;
}
}
bin->entry = entry->addr;
}
return entry;
}
Commit Message: Fix null deref and uaf in mach0 parser
CWE ID: CWE-416
|
struct addr_t* MACH0_(get_entrypoint)(struct MACH0_(obj_t)* bin) {
struct addr_t *entry;
int i;
if (!bin->entry && !bin->sects) {
return NULL;
}
if (!(entry = calloc (1, sizeof (struct addr_t)))) {
return NULL;
}
if (bin->entry) {
entry->addr = entry_to_vaddr (bin);
entry->offset = addr_to_offset (bin, entry->addr);
entry->haddr = sdb_num_get (bin->kv, "mach0.entry.offset", 0);
}
if (!bin->entry || entry->offset == 0) {
for (i = 0; i < bin->nsects; i++) {
if (!strncmp (bin->sects[i].sectname, "__text", 6)) {
entry->offset = (ut64)bin->sects[i].offset;
sdb_num_set (bin->kv, "mach0.entry", entry->offset, 0);
entry->addr = (ut64)bin->sects[i].addr;
if (!entry->addr) { // workaround for object files
entry->addr = entry->offset;
}
break;
}
}
bin->entry = entry->addr;
}
return entry;
}
| 168,233
|
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 CreatePersistentMemoryAllocator() {
GlobalHistogramAllocator::GetCreateHistogramResultHistogram();
GlobalHistogramAllocator::CreateWithLocalMemory(
kAllocatorMemorySize, 0, "SparseHistogramAllocatorTest");
allocator_ = GlobalHistogramAllocator::Get()->memory_allocator();
}
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
|
void CreatePersistentMemoryAllocator() {
GlobalHistogramAllocator::CreateWithLocalMemory(
kAllocatorMemorySize, 0, "SparseHistogramAllocatorTest");
allocator_ = GlobalHistogramAllocator::Get()->memory_allocator();
}
| 172,138
|
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_get_key_size)
{
char *cipher;
char *module;
int cipher_len, module_len;
char *cipher_dir_string;
char *module_dir_string;
MCRYPT td;
MCRYPT_GET_INI
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
&cipher, &cipher_len, &module, &module_len) == FAILURE) {
return;
}
td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string);
if (td != MCRYPT_FAILED) {
RETVAL_LONG(mcrypt_enc_get_key_size(td));
mcrypt_module_close(td);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
RETURN_FALSE;
}
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
|
PHP_FUNCTION(mcrypt_get_key_size)
{
char *cipher;
char *module;
int cipher_len, module_len;
char *cipher_dir_string;
char *module_dir_string;
MCRYPT td;
MCRYPT_GET_INI
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
&cipher, &cipher_len, &module, &module_len) == FAILURE) {
return;
}
td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string);
if (td != MCRYPT_FAILED) {
RETVAL_LONG(mcrypt_enc_get_key_size(td));
mcrypt_module_close(td);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
RETURN_FALSE;
}
}
| 167,103
|
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_unstringify (MyObject *obj, const char *str, GValue *value, GError **error)
{
if (str[0] == '\0' || !g_ascii_isdigit (str[0])) {
g_value_init (value, G_TYPE_STRING);
g_value_set_string (value, str);
} else {
g_value_init (value, G_TYPE_INT);
g_value_set_int (value, (int) g_ascii_strtoull (str, NULL, 10));
}
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_unstringify (MyObject *obj, const char *str, GValue *value, GError **error)
| 165,125
|
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 qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size,
bool exact_size)
{
BDRVQcowState *s = bs->opaque;
int new_l1_size2, ret, i;
uint64_t *new_l1_table;
int64_t old_l1_table_offset, old_l1_size;
int64_t new_l1_table_offset, new_l1_size;
uint8_t data[12];
if (min_size <= s->l1_size)
return 0;
if (exact_size) {
new_l1_size = min_size;
} else {
/* Bump size up to reduce the number of times we have to grow */
new_l1_size = s->l1_size;
if (new_l1_size == 0) {
new_l1_size = 1;
}
while (min_size > new_l1_size) {
new_l1_size = (new_l1_size * 3 + 1) / 2;
}
}
if (new_l1_size > INT_MAX) {
return -EFBIG;
}
#ifdef DEBUG_ALLOC2
fprintf(stderr, "grow l1_table from %d to %" PRId64 "\n",
s->l1_size, new_l1_size);
#endif
new_l1_size2 = sizeof(uint64_t) * new_l1_size;
new_l1_table = g_malloc0(align_offset(new_l1_size2, 512));
memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
/* write new table (align to cluster) */
BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ALLOC_TABLE);
new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2);
if (new_l1_table_offset < 0) {
g_free(new_l1_table);
return new_l1_table_offset;
}
ret = qcow2_cache_flush(bs, s->refcount_block_cache);
if (ret < 0) {
goto fail;
}
/* the L1 position has not yet been updated, so these clusters must
* indeed be completely free */
ret = qcow2_pre_write_overlap_check(bs, 0, new_l1_table_offset,
new_l1_size2);
if (ret < 0) {
goto fail;
}
BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_WRITE_TABLE);
for(i = 0; i < s->l1_size; i++)
new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
ret = bdrv_pwrite_sync(bs->file, new_l1_table_offset, new_l1_table, new_l1_size2);
if (ret < 0)
goto fail;
for(i = 0; i < s->l1_size; i++)
new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
/* set new table */
BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ACTIVATE_TABLE);
cpu_to_be32w((uint32_t*)data, new_l1_size);
stq_be_p(data + 4, new_l1_table_offset);
ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_size), data,sizeof(data));
if (ret < 0) {
goto fail;
}
g_free(s->l1_table);
old_l1_table_offset = s->l1_table_offset;
s->l1_table_offset = new_l1_table_offset;
s->l1_table = new_l1_table;
old_l1_size = s->l1_size;
s->l1_size = new_l1_size;
qcow2_free_clusters(bs, old_l1_table_offset, old_l1_size * sizeof(uint64_t),
QCOW2_DISCARD_OTHER);
return 0;
fail:
g_free(new_l1_table);
qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2,
QCOW2_DISCARD_OTHER);
return ret;
}
Commit Message:
CWE ID: CWE-190
|
int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size,
bool exact_size)
{
BDRVQcowState *s = bs->opaque;
int new_l1_size2, ret, i;
uint64_t *new_l1_table;
int64_t old_l1_table_offset, old_l1_size;
int64_t new_l1_table_offset, new_l1_size;
uint8_t data[12];
if (min_size <= s->l1_size)
return 0;
if (exact_size) {
new_l1_size = min_size;
} else {
/* Bump size up to reduce the number of times we have to grow */
new_l1_size = s->l1_size;
if (new_l1_size == 0) {
new_l1_size = 1;
}
while (min_size > new_l1_size) {
new_l1_size = (new_l1_size * 3 + 1) / 2;
}
}
if (new_l1_size > INT_MAX / sizeof(uint64_t)) {
return -EFBIG;
}
#ifdef DEBUG_ALLOC2
fprintf(stderr, "grow l1_table from %d to %" PRId64 "\n",
s->l1_size, new_l1_size);
#endif
new_l1_size2 = sizeof(uint64_t) * new_l1_size;
new_l1_table = g_malloc0(align_offset(new_l1_size2, 512));
memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
/* write new table (align to cluster) */
BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ALLOC_TABLE);
new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2);
if (new_l1_table_offset < 0) {
g_free(new_l1_table);
return new_l1_table_offset;
}
ret = qcow2_cache_flush(bs, s->refcount_block_cache);
if (ret < 0) {
goto fail;
}
/* the L1 position has not yet been updated, so these clusters must
* indeed be completely free */
ret = qcow2_pre_write_overlap_check(bs, 0, new_l1_table_offset,
new_l1_size2);
if (ret < 0) {
goto fail;
}
BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_WRITE_TABLE);
for(i = 0; i < s->l1_size; i++)
new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
ret = bdrv_pwrite_sync(bs->file, new_l1_table_offset, new_l1_table, new_l1_size2);
if (ret < 0)
goto fail;
for(i = 0; i < s->l1_size; i++)
new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
/* set new table */
BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ACTIVATE_TABLE);
cpu_to_be32w((uint32_t*)data, new_l1_size);
stq_be_p(data + 4, new_l1_table_offset);
ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_size), data,sizeof(data));
if (ret < 0) {
goto fail;
}
g_free(s->l1_table);
old_l1_table_offset = s->l1_table_offset;
s->l1_table_offset = new_l1_table_offset;
s->l1_table = new_l1_table;
old_l1_size = s->l1_size;
s->l1_size = new_l1_size;
qcow2_free_clusters(bs, old_l1_table_offset, old_l1_size * sizeof(uint64_t),
QCOW2_DISCARD_OTHER);
return 0;
fail:
g_free(new_l1_table);
qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2,
QCOW2_DISCARD_OTHER);
return ret;
}
| 165,409
|
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 SetImePropertyActivated(const char* key, bool activated) {
if (!IBusConnectionsAreAlive()) {
LOG(ERROR) << "SetImePropertyActivated: IBus connection is not alive";
return;
}
if (!key || (key[0] == '\0')) {
return;
}
if (input_context_path_.empty()) {
LOG(ERROR) << "Input context is unknown";
return;
}
IBusInputContext* context = GetInputContext(input_context_path_, ibus_);
if (!context) {
return;
}
ibus_input_context_property_activate(
context, key, (activated ? PROP_STATE_CHECKED : PROP_STATE_UNCHECKED));
g_object_unref(context);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void SetImePropertyActivated(const char* key, bool activated) {
// IBusController override.
virtual void SetImePropertyActivated(const std::string& key,
bool activated) {
if (!IBusConnectionsAreAlive()) {
LOG(ERROR) << "SetImePropertyActivated: IBus connection is not alive";
return;
}
if (key.empty()) {
return;
}
if (input_context_path_.empty()) {
LOG(ERROR) << "Input context is unknown";
return;
}
IBusInputContext* context = GetInputContext(input_context_path_, ibus_);
if (!context) {
return;
}
ibus_input_context_property_activate(
context, key.c_str(),
(activated ? PROP_STATE_CHECKED : PROP_STATE_UNCHECKED));
g_object_unref(context);
}
| 170,548
|
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 WorkerFetchContext::DispatchDidBlockRequest(
const ResourceRequest& resource_request,
const FetchInitiatorInfo& fetch_initiator_info,
ResourceRequestBlockedReason blocked_reason) const {
probe::didBlockRequest(global_scope_, resource_request, nullptr,
fetch_initiator_info, blocked_reason);
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <pfeldman@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119
|
void WorkerFetchContext::DispatchDidBlockRequest(
const ResourceRequest& resource_request,
const FetchInitiatorInfo& fetch_initiator_info,
ResourceRequestBlockedReason blocked_reason,
Resource::Type resource_type) const {
probe::didBlockRequest(global_scope_, resource_request, nullptr,
fetch_initiator_info, blocked_reason, resource_type);
}
| 172,475
|
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 virtio_gpu_set_scanout(VirtIOGPU *g,
struct virtio_gpu_ctrl_command *cmd)
{
struct virtio_gpu_simple_resource *res;
struct virtio_gpu_scanout *scanout;
pixman_format_code_t format;
uint32_t offset;
int bpp;
struct virtio_gpu_set_scanout ss;
VIRTIO_GPU_FILL_CMD(ss);
trace_virtio_gpu_cmd_set_scanout(ss.scanout_id, ss.resource_id,
ss.r.width, ss.r.height, ss.r.x, ss.r.y);
if (ss.scanout_id >= g->conf.max_outputs) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout id specified %d",
__func__, ss.scanout_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID;
return;
}
g->enable = 1;
if (ss.resource_id == 0) {
scanout = &g->scanout[ss.scanout_id];
if (scanout->resource_id) {
res = virtio_gpu_find_resource(g, scanout->resource_id);
if (res) {
res->scanout_bitmask &= ~(1 << ss.scanout_id);
}
}
if (ss.scanout_id == 0) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: illegal scanout id specified %d",
__func__, ss.scanout_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID;
return;
}
dpy_gfx_replace_surface(g->scanout[ss.scanout_id].con, NULL);
scanout->ds = NULL;
scanout->width = 0;
scanout->height = 0;
return;
}
/* create a surface for this scanout */
res = virtio_gpu_find_resource(g, ss.resource_id);
if (!res) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal resource specified %d\n",
__func__, ss.resource_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
return;
}
if (ss.r.x > res->width ||
ss.r.y > res->height ||
ss.r.width > res->width ||
ss.r.height > res->height ||
ss.r.x + ss.r.width > res->width ||
ss.r.y + ss.r.height > res->height) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout %d bounds for"
" resource %d, (%d,%d)+%d,%d vs %d %d\n",
__func__, ss.scanout_id, ss.resource_id, ss.r.x, ss.r.y,
ss.r.width, ss.r.height, res->width, res->height);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
return;
}
scanout = &g->scanout[ss.scanout_id];
format = pixman_image_get_format(res->image);
bpp = (PIXMAN_FORMAT_BPP(format) + 7) / 8;
offset = (ss.r.x * bpp) + ss.r.y * pixman_image_get_stride(res->image);
if (!scanout->ds || surface_data(scanout->ds)
!= ((uint8_t *)pixman_image_get_data(res->image) + offset) ||
scanout->width != ss.r.width ||
scanout->height != ss.r.height) {
pixman_image_t *rect;
void *ptr = (uint8_t *)pixman_image_get_data(res->image) + offset;
rect = pixman_image_create_bits(format, ss.r.width, ss.r.height, ptr,
pixman_image_get_stride(res->image));
pixman_image_ref(res->image);
pixman_image_set_destroy_function(rect, virtio_unref_resource,
res->image);
/* realloc the surface ptr */
scanout->ds = qemu_create_displaysurface_pixman(rect);
if (!scanout->ds) {
cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC;
return;
}
dpy_gfx_replace_surface(g->scanout[ss.scanout_id].con, scanout->ds);
}
scanout->resource_id = ss.resource_id;
scanout->x = ss.r.x;
scanout->y = ss.r.y;
scanout->width = ss.r.width;
scanout->height = ss.r.height;
}
Commit Message:
CWE ID: CWE-772
|
static void virtio_gpu_set_scanout(VirtIOGPU *g,
struct virtio_gpu_ctrl_command *cmd)
{
struct virtio_gpu_simple_resource *res;
struct virtio_gpu_scanout *scanout;
pixman_format_code_t format;
uint32_t offset;
int bpp;
struct virtio_gpu_set_scanout ss;
VIRTIO_GPU_FILL_CMD(ss);
trace_virtio_gpu_cmd_set_scanout(ss.scanout_id, ss.resource_id,
ss.r.width, ss.r.height, ss.r.x, ss.r.y);
if (ss.scanout_id >= g->conf.max_outputs) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout id specified %d",
__func__, ss.scanout_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID;
return;
}
g->enable = 1;
if (ss.resource_id == 0) {
scanout = &g->scanout[ss.scanout_id];
if (scanout->resource_id) {
res = virtio_gpu_find_resource(g, scanout->resource_id);
if (res) {
res->scanout_bitmask &= ~(1 << ss.scanout_id);
}
}
if (ss.scanout_id == 0) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: illegal scanout id specified %d",
__func__, ss.scanout_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID;
return;
}
dpy_gfx_replace_surface(g->scanout[ss.scanout_id].con, NULL);
scanout->ds = NULL;
scanout->width = 0;
scanout->height = 0;
return;
}
/* create a surface for this scanout */
res = virtio_gpu_find_resource(g, ss.resource_id);
if (!res) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal resource specified %d\n",
__func__, ss.resource_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
return;
}
if (ss.r.x > res->width ||
ss.r.y > res->height ||
ss.r.width > res->width ||
ss.r.height > res->height ||
ss.r.x + ss.r.width > res->width ||
ss.r.y + ss.r.height > res->height) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout %d bounds for"
" resource %d, (%d,%d)+%d,%d vs %d %d\n",
__func__, ss.scanout_id, ss.resource_id, ss.r.x, ss.r.y,
ss.r.width, ss.r.height, res->width, res->height);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
return;
}
scanout = &g->scanout[ss.scanout_id];
format = pixman_image_get_format(res->image);
bpp = (PIXMAN_FORMAT_BPP(format) + 7) / 8;
offset = (ss.r.x * bpp) + ss.r.y * pixman_image_get_stride(res->image);
if (!scanout->ds || surface_data(scanout->ds)
!= ((uint8_t *)pixman_image_get_data(res->image) + offset) ||
scanout->width != ss.r.width ||
scanout->height != ss.r.height) {
pixman_image_t *rect;
void *ptr = (uint8_t *)pixman_image_get_data(res->image) + offset;
rect = pixman_image_create_bits(format, ss.r.width, ss.r.height, ptr,
pixman_image_get_stride(res->image));
pixman_image_ref(res->image);
pixman_image_set_destroy_function(rect, virtio_unref_resource,
res->image);
/* realloc the surface ptr */
scanout->ds = qemu_create_displaysurface_pixman(rect);
if (!scanout->ds) {
cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC;
return;
}
pixman_image_unref(rect);
dpy_gfx_replace_surface(g->scanout[ss.scanout_id].con, scanout->ds);
}
scanout->resource_id = ss.resource_id;
scanout->x = ss.r.x;
scanout->y = ss.r.y;
scanout->width = ss.r.width;
scanout->height = ss.r.height;
}
| 164,813
|
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: make_transform_images(png_store *ps)
{
png_byte colour_type = 0;
png_byte bit_depth = 0;
unsigned int palette_number = 0;
/* This is in case of errors. */
safecat(ps->test, sizeof ps->test, 0, "make standard images");
/* Use next_format to enumerate all the combinations we test, including
* generating multiple low bit depth palette images.
*/
while (next_format(&colour_type, &bit_depth, &palette_number, 0))
{
int interlace_type;
for (interlace_type = PNG_INTERLACE_NONE;
interlace_type < INTERLACE_LAST; ++interlace_type)
{
char name[FILE_NAME_SIZE];
standard_name(name, sizeof name, 0, colour_type, bit_depth,
palette_number, interlace_type, 0, 0, 0);
make_transform_image(ps, colour_type, bit_depth, palette_number,
interlace_type, name);
}
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
make_transform_images(png_store *ps)
make_transform_images(png_modifier *pm)
{
png_byte colour_type = 0;
png_byte bit_depth = 0;
unsigned int palette_number = 0;
/* This is in case of errors. */
safecat(pm->this.test, sizeof pm->this.test, 0, "make standard images");
/* Use next_format to enumerate all the combinations we test, including
* generating multiple low bit depth palette images. Non-A images (palette
* and direct) are created with and without tRNS chunks.
*/
while (next_format(&colour_type, &bit_depth, &palette_number, 1, 1))
{
int interlace_type;
for (interlace_type = PNG_INTERLACE_NONE;
interlace_type < INTERLACE_LAST; ++interlace_type)
{
char name[FILE_NAME_SIZE];
standard_name(name, sizeof name, 0, colour_type, bit_depth,
palette_number, interlace_type, 0, 0, do_own_interlace);
make_transform_image(&pm->this, colour_type, bit_depth, palette_number,
interlace_type, name);
}
}
}
| 173,666
|
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: store_image_row(PNG_CONST png_store* ps, png_const_structp pp, int nImage,
png_uint_32 y)
{
png_size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2;
if (ps->image == NULL)
png_error(pp, "no allocated image");
if (coffset + ps->cb_row + 3 > ps->cb_image)
png_error(pp, "image too small");
return ps->image + coffset;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
store_image_row(PNG_CONST png_store* ps, png_const_structp pp, int nImage,
store_image_row(const png_store* ps, png_const_structp pp, int nImage,
png_uint_32 y)
{
png_size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2;
if (ps->image == NULL)
png_error(pp, "no allocated image");
if (coffset + ps->cb_row + 3 > ps->cb_image)
png_error(pp, "image too small");
return ps->image + coffset;
}
| 173,705
|
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 sfgets(void)
{
struct pollfd pfd;
int pollret;
ssize_t readnb;
signed char seen_r = 0;
static size_t scanned;
static size_t readnbd;
if (scanned > (size_t) 0U) { /* support pipelining */
readnbd -= scanned;
memmove(cmd, cmd + scanned, readnbd); /* safe */
scanned = (size_t) 0U;
}
pfd.fd = clientfd;
#ifdef __APPLE_CC__
pfd.events = POLLIN | POLLERR | POLLHUP;
#else
pfd.events = POLLIN | POLLPRI | POLLERR | POLLHUP;
#endif
while (scanned < cmdsize) {
if (scanned >= readnbd) { /* nothing left in the buffer */
pfd.revents = 0;
while ((pollret = poll(&pfd, 1U, idletime * 1000UL)) < 0 &&
errno == EINTR);
if (pollret == 0) {
return -1;
}
if (pollret <= 0 ||
(pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) != 0) {
return -2;
}
if ((pfd.revents & (POLLIN | POLLPRI)) == 0) {
continue;
}
if (readnbd >= cmdsize) {
break;
}
#ifdef WITH_TLS
if (tls_cnx != NULL) {
while ((readnb = SSL_read
(tls_cnx, cmd + readnbd, cmdsize - readnbd))
< (ssize_t) 0 && errno == EINTR);
} else
#endif
{
while ((readnb = read(clientfd, cmd + readnbd,
cmdsize - readnbd)) < (ssize_t) 0 &&
errno == EINTR);
}
if (readnb <= (ssize_t) 0) {
return -2;
}
readnbd += readnb;
if (readnbd > cmdsize) {
return -2;
}
}
#ifdef RFC_CONFORMANT_LINES
if (seen_r != 0) {
#endif
if (cmd[scanned] == '\n') {
#ifndef RFC_CONFORMANT_LINES
if (seen_r != 0) {
#endif
cmd[scanned - 1U] = 0;
#ifndef RFC_CONFORMANT_LINES
} else {
cmd[scanned] = 0;
}
#endif
if (++scanned >= readnbd) { /* non-pipelined command */
scanned = readnbd = (size_t) 0U;
}
return 0;
}
seen_r = 0;
#ifdef RFC_CONFORMANT_LINES
}
#endif
if (ISCTRLCODE(cmd[scanned])) {
if (cmd[scanned] == '\r') {
seen_r = 1;
}
#ifdef RFC_CONFORMANT_PARSER /* disabled by default, intentionnaly */
else if (cmd[scanned] == 0) {
cmd[scanned] = '\n';
}
#else
/* replace control chars with _ */
cmd[scanned] = '_';
#endif
}
scanned++;
}
die(421, LOG_WARNING, MSG_LINE_TOO_LONG); /* don't remove this */
return 0; /* to please GCC */
}
Commit Message: Flush the command buffer after switching to TLS.
Fixes a flaw similar to CVE-2011-0411.
CWE ID: CWE-399
|
int sfgets(void)
{
struct pollfd pfd;
int pollret;
ssize_t readnb;
signed char seen_r = 0;
if (scanned > (size_t) 0U) { /* support pipelining */
readnbd -= scanned;
memmove(cmd, cmd + scanned, readnbd); /* safe */
scanned = (size_t) 0U;
}
pfd.fd = clientfd;
#ifdef __APPLE_CC__
pfd.events = POLLIN | POLLERR | POLLHUP;
#else
pfd.events = POLLIN | POLLPRI | POLLERR | POLLHUP;
#endif
while (scanned < cmdsize) {
if (scanned >= readnbd) { /* nothing left in the buffer */
pfd.revents = 0;
while ((pollret = poll(&pfd, 1U, idletime * 1000UL)) < 0 &&
errno == EINTR);
if (pollret == 0) {
return -1;
}
if (pollret <= 0 ||
(pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) != 0) {
return -2;
}
if ((pfd.revents & (POLLIN | POLLPRI)) == 0) {
continue;
}
if (readnbd >= cmdsize) {
break;
}
#ifdef WITH_TLS
if (tls_cnx != NULL) {
while ((readnb = SSL_read
(tls_cnx, cmd + readnbd, cmdsize - readnbd))
< (ssize_t) 0 && errno == EINTR);
} else
#endif
{
while ((readnb = read(clientfd, cmd + readnbd,
cmdsize - readnbd)) < (ssize_t) 0 &&
errno == EINTR);
}
if (readnb <= (ssize_t) 0) {
return -2;
}
readnbd += readnb;
if (readnbd > cmdsize) {
return -2;
}
}
#ifdef RFC_CONFORMANT_LINES
if (seen_r != 0) {
#endif
if (cmd[scanned] == '\n') {
#ifndef RFC_CONFORMANT_LINES
if (seen_r != 0) {
#endif
cmd[scanned - 1U] = 0;
#ifndef RFC_CONFORMANT_LINES
} else {
cmd[scanned] = 0;
}
#endif
if (++scanned >= readnbd) { /* non-pipelined command */
scanned = readnbd = (size_t) 0U;
}
return 0;
}
seen_r = 0;
#ifdef RFC_CONFORMANT_LINES
}
#endif
if (ISCTRLCODE(cmd[scanned])) {
if (cmd[scanned] == '\r') {
seen_r = 1;
}
#ifdef RFC_CONFORMANT_PARSER /* disabled by default, intentionnaly */
else if (cmd[scanned] == 0) {
cmd[scanned] = '\n';
}
#else
/* replace control chars with _ */
cmd[scanned] = '_';
#endif
}
scanned++;
}
die(421, LOG_WARNING, MSG_LINE_TOO_LONG); /* don't remove this */
return 0; /* to please GCC */
}
| 165,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: ProxyChannelDelegate::ProxyChannelDelegate()
: shutdown_event_(true, false) {
}
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
|
ProxyChannelDelegate::ProxyChannelDelegate()
| 170,737
|
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: DocumentInit& DocumentInit::WithPreviousDocumentCSP(
const ContentSecurityPolicy* previous_csp) {
DCHECK(!previous_csp_);
previous_csp_ = previous_csp;
return *this;
}
Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener
Spec PR: https://github.com/w3c/webappsec-csp/pull/358
Bug: 905301, 894228, 836148
Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a
Reviewed-on: https://chromium-review.googlesource.com/c/1314633
Commit-Queue: Andy Paicu <andypaicu@chromium.org>
Reviewed-by: Mike West <mkwst@chromium.org>
Cr-Commit-Position: refs/heads/master@{#610850}
CWE ID: CWE-20
|
DocumentInit& DocumentInit::WithPreviousDocumentCSP(
| 173,054
|
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 LoadingStatsCollector::CleanupAbandonedStats() {
base::TimeTicks time_now = base::TimeTicks::Now();
for (auto it = preconnect_stats_.begin(); it != preconnect_stats_.end();) {
if (time_now - it->second->start_time > max_stats_age_) {
ReportPreconnectAccuracy(*it->second,
std::map<GURL, OriginRequestSummary>());
it = preconnect_stats_.erase(it);
} else {
++it;
}
}
}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org>
Reviewed-by: Alex Ilin <alexilin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125
|
void LoadingStatsCollector::CleanupAbandonedStats() {
base::TimeTicks time_now = base::TimeTicks::Now();
for (auto it = preconnect_stats_.begin(); it != preconnect_stats_.end();) {
if (time_now - it->second->start_time > max_stats_age_) {
ReportPreconnectAccuracy(*it->second, {});
it = preconnect_stats_.erase(it);
} else {
++it;
}
}
}
| 172,370
|
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 CrosLibrary::TestApi::SetKeyboardLibrary(
KeyboardLibrary* library, bool own) {
library_->keyboard_lib_.SetImpl(library, own);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
|
void CrosLibrary::TestApi::SetKeyboardLibrary(
| 170,639
|
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 fpm_stdio_init_child(struct fpm_worker_pool_s *wp) /* {{{ */
{
#ifdef HAVE_SYSLOG_H
if (fpm_globals.error_log_fd == ZLOG_SYSLOG) {
closelog(); /* ensure to close syslog not to interrupt with PHP syslog code */
} else
#endif
/* Notice: child cannot use master error_log
* because not aware when being reopen
* else, should use if (!fpm_use_error_log())
*/
if (fpm_globals.error_log_fd > 0) {
close(fpm_globals.error_log_fd);
}
fpm_globals.error_log_fd = -1;
zlog_set_fd(-1);
if (wp->listening_socket != STDIN_FILENO) {
if (0 > dup2(wp->listening_socket, STDIN_FILENO)) {
zlog(ZLOG_SYSERROR, "failed to init child stdio: dup2()");
return -1;
}
}
return 0;
}
/* }}} */
Commit Message: Fixed bug #73342
Directly listen on socket, instead of duping it to STDIN and
listening on that.
CWE ID: CWE-400
|
int fpm_stdio_init_child(struct fpm_worker_pool_s *wp) /* {{{ */
{
#ifdef HAVE_SYSLOG_H
if (fpm_globals.error_log_fd == ZLOG_SYSLOG) {
closelog(); /* ensure to close syslog not to interrupt with PHP syslog code */
} else
#endif
/* Notice: child cannot use master error_log
* because not aware when being reopen
* else, should use if (!fpm_use_error_log())
*/
if (fpm_globals.error_log_fd > 0) {
close(fpm_globals.error_log_fd);
}
fpm_globals.error_log_fd = -1;
zlog_set_fd(-1);
return 0;
}
/* }}} */
| 169,452
|
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 rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm,
struct cmsghdr *cmsg)
{
struct page *page = NULL;
struct rds_atomic_args *args;
int ret = 0;
if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args))
|| rm->atomic.op_active)
return -EINVAL;
args = CMSG_DATA(cmsg);
/* Nonmasked & masked cmsg ops converted to masked hw ops */
switch (cmsg->cmsg_type) {
case RDS_CMSG_ATOMIC_FADD:
rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;
rm->atomic.op_m_fadd.add = args->fadd.add;
rm->atomic.op_m_fadd.nocarry_mask = 0;
break;
case RDS_CMSG_MASKED_ATOMIC_FADD:
rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;
rm->atomic.op_m_fadd.add = args->m_fadd.add;
rm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask;
break;
case RDS_CMSG_ATOMIC_CSWP:
rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;
rm->atomic.op_m_cswp.compare = args->cswp.compare;
rm->atomic.op_m_cswp.swap = args->cswp.swap;
rm->atomic.op_m_cswp.compare_mask = ~0;
rm->atomic.op_m_cswp.swap_mask = ~0;
break;
case RDS_CMSG_MASKED_ATOMIC_CSWP:
rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;
rm->atomic.op_m_cswp.compare = args->m_cswp.compare;
rm->atomic.op_m_cswp.swap = args->m_cswp.swap;
rm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask;
rm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask;
break;
default:
BUG(); /* should never happen */
}
rm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);
rm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT);
rm->atomic.op_active = 1;
rm->atomic.op_recverr = rs->rs_recverr;
rm->atomic.op_sg = rds_message_alloc_sgs(rm, 1);
if (!rm->atomic.op_sg) {
ret = -ENOMEM;
goto err;
}
/* verify 8 byte-aligned */
if (args->local_addr & 0x7) {
ret = -EFAULT;
goto err;
}
ret = rds_pin_pages(args->local_addr, 1, &page, 1);
if (ret != 1)
goto err;
ret = 0;
sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr));
if (rm->atomic.op_notify || rm->atomic.op_recverr) {
/* We allocate an uninitialized notifier here, because
* we don't want to do that in the completion handler. We
* would have to use GFP_ATOMIC there, and don't want to deal
* with failed allocations.
*/
rm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL);
if (!rm->atomic.op_notifier) {
ret = -ENOMEM;
goto err;
}
rm->atomic.op_notifier->n_user_token = args->user_token;
rm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS;
}
rm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie);
rm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie);
return ret;
err:
if (page)
put_page(page);
kfree(rm->atomic.op_notifier);
return ret;
}
Commit Message: RDS: null pointer dereference in rds_atomic_free_op
set rm->atomic.op_active to 0 when rds_pin_pages() fails
or the user supplied address is invalid,
this prevents a NULL pointer usage in rds_atomic_free_op()
Signed-off-by: Mohamed Ghannam <simo.ghannam@gmail.com>
Acked-by: Santosh Shilimkar <santosh.shilimkar@oracle.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-476
|
int rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm,
struct cmsghdr *cmsg)
{
struct page *page = NULL;
struct rds_atomic_args *args;
int ret = 0;
if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args))
|| rm->atomic.op_active)
return -EINVAL;
args = CMSG_DATA(cmsg);
/* Nonmasked & masked cmsg ops converted to masked hw ops */
switch (cmsg->cmsg_type) {
case RDS_CMSG_ATOMIC_FADD:
rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;
rm->atomic.op_m_fadd.add = args->fadd.add;
rm->atomic.op_m_fadd.nocarry_mask = 0;
break;
case RDS_CMSG_MASKED_ATOMIC_FADD:
rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;
rm->atomic.op_m_fadd.add = args->m_fadd.add;
rm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask;
break;
case RDS_CMSG_ATOMIC_CSWP:
rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;
rm->atomic.op_m_cswp.compare = args->cswp.compare;
rm->atomic.op_m_cswp.swap = args->cswp.swap;
rm->atomic.op_m_cswp.compare_mask = ~0;
rm->atomic.op_m_cswp.swap_mask = ~0;
break;
case RDS_CMSG_MASKED_ATOMIC_CSWP:
rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;
rm->atomic.op_m_cswp.compare = args->m_cswp.compare;
rm->atomic.op_m_cswp.swap = args->m_cswp.swap;
rm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask;
rm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask;
break;
default:
BUG(); /* should never happen */
}
rm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);
rm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT);
rm->atomic.op_active = 1;
rm->atomic.op_recverr = rs->rs_recverr;
rm->atomic.op_sg = rds_message_alloc_sgs(rm, 1);
if (!rm->atomic.op_sg) {
ret = -ENOMEM;
goto err;
}
/* verify 8 byte-aligned */
if (args->local_addr & 0x7) {
ret = -EFAULT;
goto err;
}
ret = rds_pin_pages(args->local_addr, 1, &page, 1);
if (ret != 1)
goto err;
ret = 0;
sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr));
if (rm->atomic.op_notify || rm->atomic.op_recverr) {
/* We allocate an uninitialized notifier here, because
* we don't want to do that in the completion handler. We
* would have to use GFP_ATOMIC there, and don't want to deal
* with failed allocations.
*/
rm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL);
if (!rm->atomic.op_notifier) {
ret = -ENOMEM;
goto err;
}
rm->atomic.op_notifier->n_user_token = args->user_token;
rm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS;
}
rm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie);
rm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie);
return ret;
err:
if (page)
put_page(page);
rm->atomic.op_active = 0;
kfree(rm->atomic.op_notifier);
return ret;
}
| 169,353
|
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 get_sda(void)
{
return qrio_get_gpio(DEBLOCK_PORT1, DEBLOCK_SDA1);
}
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
|
int get_sda(void)
| 169,630
|
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: write_message( RenderState state )
{
ADisplay adisplay = (ADisplay)state->display.disp;
if ( state->message == NULL )
{
FontFace face = &state->faces[state->face_index];
int idx, total;
idx = face->index;
total = 1;
while ( total + state->face_index < state->num_faces &&
face[total].filepath == face[0].filepath )
total++;
total += idx;
state->message = state->message0;
if ( total > 1 )
sprintf( state->message0, "%s %d/%d @ %5.1fpt",
state->filename, idx + 1, total,
state->char_size );
else
sprintf( state->message0, "%s @ %5.1fpt",
state->filename,
state->char_size );
}
grWriteCellString( adisplay->bitmap, 0, DIM_Y - 10, state->message,
adisplay->fore_color );
state->message = NULL;
}
Commit Message:
CWE ID: CWE-119
|
write_message( RenderState state )
{
ADisplay adisplay = (ADisplay)state->display.disp;
if ( state->message == NULL )
{
FontFace face = &state->faces[state->face_index];
int idx, total;
idx = face->index;
total = 1;
while ( total + state->face_index < state->num_faces &&
face[total].filepath == face[0].filepath )
total++;
total += idx;
state->message = state->message0;
if ( total > 1 )
sprintf( state->message0, "%.100s %d/%d @ %5.1fpt",
state->filename, idx + 1, total,
state->char_size );
else
sprintf( state->message0, "%.100s @ %5.1fpt",
state->filename,
state->char_size );
}
grWriteCellString( adisplay->bitmap, 0, DIM_Y - 10, state->message,
adisplay->fore_color );
state->message = NULL;
}
| 164,997
|
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 UnprivilegedProcessDelegate::LaunchProcess(
IPC::Listener* delegate,
ScopedHandle* process_exit_event_out) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
std::string channel_name = GenerateIpcChannelName(this);
ScopedHandle client;
scoped_ptr<IPC::ChannelProxy> server;
if (!CreateConnectedIpcChannel(channel_name, delegate, &client, &server))
return false;
std::string pipe_handle = base::StringPrintf(
"%d", reinterpret_cast<ULONG_PTR>(client.Get()));
CommandLine command_line(binary_path_);
command_line.AppendSwitchASCII(kDaemonPipeSwitchName, pipe_handle);
command_line.CopySwitchesFrom(*CommandLine::ForCurrentProcess(),
kCopiedSwitchNames,
arraysize(kCopiedSwitchNames));
ScopedHandle worker_thread;
worker_process_.Close();
if (!LaunchProcessWithToken(command_line.GetProgram(),
command_line.GetCommandLineString(),
NULL,
true,
0,
&worker_process_,
&worker_thread)) {
return false;
}
ScopedHandle process_exit_event;
if (!DuplicateHandle(GetCurrentProcess(),
worker_process_,
GetCurrentProcess(),
process_exit_event.Receive(),
SYNCHRONIZE,
FALSE,
0)) {
LOG_GETLASTERROR(ERROR) << "Failed to duplicate a handle";
KillProcess(CONTROL_C_EXIT);
return false;
}
channel_ = server.Pass();
*process_exit_event_out = process_exit_event.Pass();
return true;
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool UnprivilegedProcessDelegate::LaunchProcess(
IPC::Listener* delegate,
ScopedHandle* process_exit_event_out) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
std::string channel_name = GenerateIpcChannelName(this);
ScopedHandle client;
scoped_ptr<IPC::ChannelProxy> server;
ScopedHandle pipe;
if (!CreateConnectedIpcChannel(channel_name, io_task_runner_, delegate,
&client, &server, &pipe)) {
return false;
}
std::string pipe_handle = base::StringPrintf(
"%d", reinterpret_cast<ULONG_PTR>(client.Get()));
CommandLine command_line(binary_path_);
command_line.AppendSwitchASCII(kDaemonPipeSwitchName, pipe_handle);
command_line.CopySwitchesFrom(*CommandLine::ForCurrentProcess(),
kCopiedSwitchNames,
arraysize(kCopiedSwitchNames));
ScopedHandle worker_thread;
worker_process_.Close();
if (!LaunchProcessWithToken(command_line.GetProgram(),
command_line.GetCommandLineString(),
NULL,
true,
0,
&worker_process_,
&worker_thread)) {
return false;
}
ScopedHandle process_exit_event;
if (!DuplicateHandle(GetCurrentProcess(),
worker_process_,
GetCurrentProcess(),
process_exit_event.Receive(),
SYNCHRONIZE,
FALSE,
0)) {
LOG_GETLASTERROR(ERROR) << "Failed to duplicate a handle";
KillProcess(CONTROL_C_EXIT);
return false;
}
channel_ = server.Pass();
*process_exit_event_out = process_exit_event.Pass();
return true;
}
| 171,546
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void InputHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
if (frame_host == host_)
return;
ClearInputState();
if (host_) {
host_->GetRenderWidgetHost()->RemoveInputEventObserver(this);
if (ignore_input_events_)
host_->GetRenderWidgetHost()->SetIgnoreInputEvents(false);
}
host_ = frame_host;
if (host_) {
host_->GetRenderWidgetHost()->AddInputEventObserver(this);
if (ignore_input_events_)
host_->GetRenderWidgetHost()->SetIgnoreInputEvents(true);
}
}
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 InputHandler::SetRenderer(RenderProcessHost* process_host,
void InputHandler::SetRenderer(int process_host_id,
RenderFrameHostImpl* frame_host) {
if (frame_host == host_)
return;
ClearInputState();
if (host_) {
host_->GetRenderWidgetHost()->RemoveInputEventObserver(this);
if (ignore_input_events_)
host_->GetRenderWidgetHost()->SetIgnoreInputEvents(false);
}
host_ = frame_host;
if (host_) {
host_->GetRenderWidgetHost()->AddInputEventObserver(this);
if (ignore_input_events_)
host_->GetRenderWidgetHost()->SetIgnoreInputEvents(true);
}
}
| 172,747
|
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 skel(const char *homedir, uid_t u, gid_t g) {
char *fname;
if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) {
if (asprintf(&fname, "%s/.zshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.zshrc", &s) == 0) {
copy_file("/etc/skel/.zshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.zshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) {
if (asprintf(&fname, "%s/.cshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.cshrc", &s) == 0) {
copy_file("/etc/skel/.cshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.cshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
else {
if (asprintf(&fname, "%s/.bashrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (stat("/etc/skel/.bashrc", &s) == 0) {
copy_file("/etc/skel/.bashrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.bashrc");
}
free(fname);
}
}
Commit Message: security fix
CWE ID: CWE-269
|
static void skel(const char *homedir, uid_t u, gid_t g) {
char *fname;
if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) {
if (asprintf(&fname, "%s/.zshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat
fprintf(stderr, "Error: invalid %s file\n", fname);
exit(1);
}
if (stat("/etc/skel/.zshrc", &s) == 0) {
copy_file_as_user("/etc/skel/.zshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.zshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) {
if (asprintf(&fname, "%s/.cshrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat
fprintf(stderr, "Error: invalid %s file\n", fname);
exit(1);
}
if (stat("/etc/skel/.cshrc", &s) == 0) {
copy_file_as_user("/etc/skel/.cshrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.cshrc");
}
else {
touch_file_as_user(fname, u, g, 0644);
fs_logger2("touch", fname);
}
free(fname);
}
else {
if (asprintf(&fname, "%s/.bashrc", homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(fname, &s) == 0)
return;
if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat
fprintf(stderr, "Error: invalid %s file\n", fname);
exit(1);
}
if (stat("/etc/skel/.bashrc", &s) == 0) {
copy_file_as_user("/etc/skel/.bashrc", fname, u, g, 0644);
fs_logger("clone /etc/skel/.bashrc");
}
free(fname);
}
}
| 168,371
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: INST_HANDLER (cpse) { // CPSE Rd, Rr
int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3);
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
RAnalOp next_op;
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
Commit Message: Fix #9943 - Invalid free on RAnal.avr
CWE ID: CWE-416
|
INST_HANDLER (cpse) { // CPSE Rd, Rr
int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3);
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
RAnalOp next_op = {0};
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
| 169,222
|
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 reactor_status_t run_reactor(reactor_t *reactor, int iterations) {
assert(reactor != NULL);
reactor->run_thread = pthread_self();
reactor->is_running = true;
struct epoll_event events[MAX_EVENTS];
for (int i = 0; iterations == 0 || i < iterations; ++i) {
pthread_mutex_lock(&reactor->list_lock);
list_clear(reactor->invalidation_list);
pthread_mutex_unlock(&reactor->list_lock);
int ret;
do {
ret = epoll_wait(reactor->epoll_fd, events, MAX_EVENTS, -1);
} while (ret == -1 && errno == EINTR);
if (ret == -1) {
LOG_ERROR("%s error in epoll_wait: %s", __func__, strerror(errno));
reactor->is_running = false;
return REACTOR_STATUS_ERROR;
}
for (int j = 0; j < ret; ++j) {
if (events[j].data.ptr == NULL) {
eventfd_t value;
eventfd_read(reactor->event_fd, &value);
reactor->is_running = false;
return REACTOR_STATUS_STOP;
}
reactor_object_t *object = (reactor_object_t *)events[j].data.ptr;
pthread_mutex_lock(&reactor->list_lock);
if (list_contains(reactor->invalidation_list, object)) {
pthread_mutex_unlock(&reactor->list_lock);
continue;
}
pthread_mutex_lock(&object->lock);
pthread_mutex_unlock(&reactor->list_lock);
reactor->object_removed = false;
if (events[j].events & (EPOLLIN | EPOLLHUP | EPOLLRDHUP | EPOLLERR) && object->read_ready)
object->read_ready(object->context);
if (!reactor->object_removed && events[j].events & EPOLLOUT && object->write_ready)
object->write_ready(object->context);
pthread_mutex_unlock(&object->lock);
if (reactor->object_removed) {
pthread_mutex_destroy(&object->lock);
osi_free(object);
}
}
}
reactor->is_running = false;
return REACTOR_STATUS_DONE;
}
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
|
static reactor_status_t run_reactor(reactor_t *reactor, int iterations) {
assert(reactor != NULL);
reactor->run_thread = pthread_self();
reactor->is_running = true;
struct epoll_event events[MAX_EVENTS];
for (int i = 0; iterations == 0 || i < iterations; ++i) {
pthread_mutex_lock(&reactor->list_lock);
list_clear(reactor->invalidation_list);
pthread_mutex_unlock(&reactor->list_lock);
int ret;
do {
ret = TEMP_FAILURE_RETRY(epoll_wait(reactor->epoll_fd, events, MAX_EVENTS, -1));
} while (ret == -1 && errno == EINTR);
if (ret == -1) {
LOG_ERROR("%s error in epoll_wait: %s", __func__, strerror(errno));
reactor->is_running = false;
return REACTOR_STATUS_ERROR;
}
for (int j = 0; j < ret; ++j) {
if (events[j].data.ptr == NULL) {
eventfd_t value;
eventfd_read(reactor->event_fd, &value);
reactor->is_running = false;
return REACTOR_STATUS_STOP;
}
reactor_object_t *object = (reactor_object_t *)events[j].data.ptr;
pthread_mutex_lock(&reactor->list_lock);
if (list_contains(reactor->invalidation_list, object)) {
pthread_mutex_unlock(&reactor->list_lock);
continue;
}
pthread_mutex_lock(&object->lock);
pthread_mutex_unlock(&reactor->list_lock);
reactor->object_removed = false;
if (events[j].events & (EPOLLIN | EPOLLHUP | EPOLLRDHUP | EPOLLERR) && object->read_ready)
object->read_ready(object->context);
if (!reactor->object_removed && events[j].events & EPOLLOUT && object->write_ready)
object->write_ready(object->context);
pthread_mutex_unlock(&object->lock);
if (reactor->object_removed) {
pthread_mutex_destroy(&object->lock);
osi_free(object);
}
}
}
reactor->is_running = false;
return REACTOR_STATUS_DONE;
}
| 173,482
|
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 P2PQuicStreamImpl::OnStreamReset(const quic::QuicRstStreamFrame& frame) {
quic::QuicStream::OnStreamReset(frame);
delegate_->OnRemoteReset();
}
Commit Message: P2PQuicStream write functionality.
This adds the P2PQuicStream::WriteData function and adds tests. It also
adds the concept of a write buffered amount, enforcing this at the
P2PQuicStreamImpl.
Bug: 874296
Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131
Reviewed-on: https://chromium-review.googlesource.com/c/1315534
Commit-Queue: Seth Hampson <shampson@chromium.org>
Reviewed-by: Henrik Boström <hbos@chromium.org>
Cr-Commit-Position: refs/heads/master@{#605766}
CWE ID: CWE-284
|
void P2PQuicStreamImpl::OnStreamReset(const quic::QuicRstStreamFrame& frame) {
quic::QuicStream::OnStreamReset(frame);
delegate_->OnRemoteReset();
}
| 172,262
|
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 grubfs_free (GrubFS *gf) {
if (gf) {
if (gf->file && gf->file->device)
free (gf->file->device->disk);
free (gf->file);
free (gf);
}
}
Commit Message: Fix #7723 - crash in ext2 GRUB code because of variable size array in stack
CWE ID: CWE-119
|
void grubfs_free (GrubFS *gf) {
if (gf) {
if (gf->file && gf->file->device) {
free (gf->file->device->disk);
}
free (gf->file);
free (gf);
}
}
| 168,090
|
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: WORD32 ih264d_end_of_pic(dec_struct_t *ps_dec,
UWORD8 u1_is_idr_slice,
UWORD16 u2_frame_num)
{
dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice;
WORD32 ret;
ps_dec->u2_mbx = 0xffff;
ps_dec->u2_mby = 0;
{
dec_err_status_t * ps_err = ps_dec->ps_dec_err_status;
if(ps_err->u1_err_flag & REJECT_CUR_PIC)
{
ih264d_err_pic_dispbuf_mgr(ps_dec);
return ERROR_NEW_FRAME_EXPECTED;
}
}
H264_MUTEX_LOCK(&ps_dec->process_disp_mutex);
ret = ih264d_end_of_pic_processing(ps_dec);
if(ret != OK)
return ret;
ps_dec->u2_total_mbs_coded = 0;
/*--------------------------------------------------------------------*/
/* ih264d_decode_pic_order_cnt - calculate the Pic Order Cnt */
/* Needed to detect end of picture */
/*--------------------------------------------------------------------*/
{
pocstruct_t *ps_prev_poc = &ps_dec->s_prev_pic_poc;
pocstruct_t *ps_cur_poc = &ps_dec->s_cur_pic_poc;
if((0 == u1_is_idr_slice) && ps_cur_slice->u1_nal_ref_idc)
ps_dec->u2_prev_ref_frame_num = ps_cur_slice->u2_frame_num;
if(u1_is_idr_slice || ps_cur_slice->u1_mmco_equalto5)
ps_dec->u2_prev_ref_frame_num = 0;
if(ps_dec->ps_cur_sps->u1_gaps_in_frame_num_value_allowed_flag)
{
ret = ih264d_decode_gaps_in_frame_num(ps_dec, u2_frame_num);
if(ret != OK)
return ret;
}
ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst;
ps_prev_poc->u2_frame_num = ps_cur_poc->u2_frame_num;
ps_prev_poc->u1_mmco_equalto5 = ps_cur_slice->u1_mmco_equalto5;
if(ps_cur_slice->u1_nal_ref_idc)
{
ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb;
ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb;
ps_prev_poc->i4_delta_pic_order_cnt_bottom =
ps_cur_poc->i4_delta_pic_order_cnt_bottom;
ps_prev_poc->i4_delta_pic_order_cnt[0] =
ps_cur_poc->i4_delta_pic_order_cnt[0];
ps_prev_poc->i4_delta_pic_order_cnt[1] =
ps_cur_poc->i4_delta_pic_order_cnt[1];
ps_prev_poc->u1_bot_field = ps_cur_poc->u1_bot_field;
}
}
H264_MUTEX_UNLOCK(&ps_dec->process_disp_mutex);
return OK;
}
Commit Message: Decoder: Moved end of pic processing to end of decode call
ih264d_end_of_pic() was called after parsing slice of a new picture.
This is now being done at the end of decode of the current picture.
decode_gaps_in_frame_num which needs frame_num of new slice is now
done after decoding frame_num in new slice.
This helps in handling errors in picaff streams with gaps in frames
Bug: 33588051
Bug: 33641588
Bug: 34097231
Change-Id: I1a26e611aaa2c19e2043e05a210849bd21b22220
CWE ID: CWE-119
|
WORD32 ih264d_end_of_pic(dec_struct_t *ps_dec,
WORD32 ih264d_end_of_pic(dec_struct_t *ps_dec)
{
dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice;
WORD32 ret;
{
dec_err_status_t * ps_err = ps_dec->ps_dec_err_status;
if(ps_err->u1_err_flag & REJECT_CUR_PIC)
{
ih264d_err_pic_dispbuf_mgr(ps_dec);
return ERROR_NEW_FRAME_EXPECTED;
}
}
H264_MUTEX_LOCK(&ps_dec->process_disp_mutex);
ret = ih264d_end_of_pic_processing(ps_dec);
if(ret != OK)
return ret;
/*--------------------------------------------------------------------*/
/* ih264d_decode_pic_order_cnt - calculate the Pic Order Cnt */
/* Needed to detect end of picture */
/*--------------------------------------------------------------------*/
H264_MUTEX_UNLOCK(&ps_dec->process_disp_mutex);
return OK;
}
| 174,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 InitCallbacks(struct mg_context* ctx, Dispatcher* dispatcher,
base::WaitableEvent* shutdown_event,
bool forbid_other_requests) {
dispatcher->AddShutdown("/shutdown", shutdown_event);
dispatcher->AddStatus("/healthz");
dispatcher->Add<CreateSession>("/session");
dispatcher->Add<FindOneElementCommand>( "/session/*/element");
dispatcher->Add<FindManyElementsCommand>("/session/*/elements");
dispatcher->Add<ActiveElementCommand>( "/session/*/element/active");
dispatcher->Add<FindOneElementCommand>( "/session/*/element/*/element");
dispatcher->Add<FindManyElementsCommand>("/session/*/elements/*/elements");
dispatcher->Add<ElementAttributeCommand>("/session/*/element/*/attribute/*");
dispatcher->Add<ElementCssCommand>( "/session/*/element/*/css/*");
dispatcher->Add<ElementClearCommand>( "/session/*/element/*/clear");
dispatcher->Add<ElementDisplayedCommand>("/session/*/element/*/displayed");
dispatcher->Add<ElementEnabledCommand>( "/session/*/element/*/enabled");
dispatcher->Add<ElementEqualsCommand>( "/session/*/element/*/equals/*");
dispatcher->Add<ElementLocationCommand>( "/session/*/element/*/location");
dispatcher->Add<ElementLocationInViewCommand>(
"/session/*/element/*/location_in_view");
dispatcher->Add<ElementNameCommand>( "/session/*/element/*/name");
dispatcher->Add<ElementSelectedCommand>("/session/*/element/*/selected");
dispatcher->Add<ElementSizeCommand>( "/session/*/element/*/size");
dispatcher->Add<ElementSubmitCommand>( "/session/*/element/*/submit");
dispatcher->Add<ElementTextCommand>( "/session/*/element/*/text");
dispatcher->Add<ElementToggleCommand>( "/session/*/element/*/toggle");
dispatcher->Add<ElementValueCommand>( "/session/*/element/*/value");
dispatcher->Add<ScreenshotCommand>("/session/*/screenshot");
dispatcher->Add<MoveAndClickCommand>("/session/*/element/*/click");
dispatcher->Add<DragCommand>( "/session/*/element/*/drag");
dispatcher->Add<HoverCommand>( "/session/*/element/*/hover");
dispatcher->Add<MoveToCommand>( "/session/*/moveto");
dispatcher->Add<ClickCommand>( "/session/*/click");
dispatcher->Add<ButtonDownCommand>( "/session/*/buttondown");
dispatcher->Add<ButtonUpCommand>( "/session/*/buttonup");
dispatcher->Add<DoubleClickCommand>("/session/*/doubleclick");
dispatcher->Add<AcceptAlertCommand>( "/session/*/accept_alert");
dispatcher->Add<AlertTextCommand>( "/session/*/alert_text");
dispatcher->Add<BackCommand>( "/session/*/back");
dispatcher->Add<DismissAlertCommand>( "/session/*/dismiss_alert");
dispatcher->Add<ExecuteCommand>( "/session/*/execute");
dispatcher->Add<ExecuteAsyncScriptCommand>(
"/session/*/execute_async");
dispatcher->Add<ForwardCommand>( "/session/*/forward");
dispatcher->Add<SwitchFrameCommand>( "/session/*/frame");
dispatcher->Add<RefreshCommand>( "/session/*/refresh");
dispatcher->Add<SourceCommand>( "/session/*/source");
dispatcher->Add<TitleCommand>( "/session/*/title");
dispatcher->Add<URLCommand>( "/session/*/url");
dispatcher->Add<WindowCommand>( "/session/*/window");
dispatcher->Add<WindowHandleCommand>( "/session/*/window_handle");
dispatcher->Add<WindowHandlesCommand>("/session/*/window_handles");
dispatcher->Add<SetAsyncScriptTimeoutCommand>(
"/session/*/timeouts/async_script");
dispatcher->Add<ImplicitWaitCommand>( "/session/*/timeouts/implicit_wait");
dispatcher->Add<CookieCommand>( "/session/*/cookie");
dispatcher->Add<NamedCookieCommand>("/session/*/cookie/*");
dispatcher->Add<SessionWithID>("/session/*");
if (forbid_other_requests)
dispatcher->ForbidAllOtherRequests();
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void InitCallbacks(struct mg_context* ctx, Dispatcher* dispatcher,
base::WaitableEvent* shutdown_event,
bool forbid_other_requests) {
dispatcher->AddShutdown("/shutdown", shutdown_event);
dispatcher->AddHealthz("/healthz");
dispatcher->AddLog("/log");
dispatcher->Add<CreateSession>("/session");
dispatcher->Add<FindOneElementCommand>( "/session/*/element");
dispatcher->Add<FindManyElementsCommand>("/session/*/elements");
dispatcher->Add<ActiveElementCommand>( "/session/*/element/active");
dispatcher->Add<FindOneElementCommand>( "/session/*/element/*/element");
dispatcher->Add<FindManyElementsCommand>("/session/*/elements/*/elements");
dispatcher->Add<ElementAttributeCommand>("/session/*/element/*/attribute/*");
dispatcher->Add<ElementCssCommand>( "/session/*/element/*/css/*");
dispatcher->Add<ElementClearCommand>( "/session/*/element/*/clear");
dispatcher->Add<ElementDisplayedCommand>("/session/*/element/*/displayed");
dispatcher->Add<ElementEnabledCommand>( "/session/*/element/*/enabled");
dispatcher->Add<ElementEqualsCommand>( "/session/*/element/*/equals/*");
dispatcher->Add<ElementLocationCommand>( "/session/*/element/*/location");
dispatcher->Add<ElementLocationInViewCommand>(
"/session/*/element/*/location_in_view");
dispatcher->Add<ElementNameCommand>( "/session/*/element/*/name");
dispatcher->Add<ElementSelectedCommand>("/session/*/element/*/selected");
dispatcher->Add<ElementSizeCommand>( "/session/*/element/*/size");
dispatcher->Add<ElementSubmitCommand>( "/session/*/element/*/submit");
dispatcher->Add<ElementTextCommand>( "/session/*/element/*/text");
dispatcher->Add<ElementToggleCommand>( "/session/*/element/*/toggle");
dispatcher->Add<ElementValueCommand>( "/session/*/element/*/value");
dispatcher->Add<ScreenshotCommand>("/session/*/screenshot");
dispatcher->Add<MoveAndClickCommand>("/session/*/element/*/click");
dispatcher->Add<DragCommand>( "/session/*/element/*/drag");
dispatcher->Add<HoverCommand>( "/session/*/element/*/hover");
dispatcher->Add<MoveToCommand>( "/session/*/moveto");
dispatcher->Add<ClickCommand>( "/session/*/click");
dispatcher->Add<ButtonDownCommand>( "/session/*/buttondown");
dispatcher->Add<ButtonUpCommand>( "/session/*/buttonup");
dispatcher->Add<DoubleClickCommand>("/session/*/doubleclick");
dispatcher->Add<AcceptAlertCommand>( "/session/*/accept_alert");
dispatcher->Add<AlertTextCommand>( "/session/*/alert_text");
dispatcher->Add<BackCommand>( "/session/*/back");
dispatcher->Add<DismissAlertCommand>( "/session/*/dismiss_alert");
dispatcher->Add<ExecuteCommand>( "/session/*/execute");
dispatcher->Add<ExecuteAsyncScriptCommand>(
"/session/*/execute_async");
dispatcher->Add<ForwardCommand>( "/session/*/forward");
dispatcher->Add<SwitchFrameCommand>( "/session/*/frame");
dispatcher->Add<RefreshCommand>( "/session/*/refresh");
dispatcher->Add<SourceCommand>( "/session/*/source");
dispatcher->Add<TitleCommand>( "/session/*/title");
dispatcher->Add<URLCommand>( "/session/*/url");
dispatcher->Add<WindowCommand>( "/session/*/window");
dispatcher->Add<WindowHandleCommand>( "/session/*/window_handle");
dispatcher->Add<WindowHandlesCommand>("/session/*/window_handles");
dispatcher->Add<SetAsyncScriptTimeoutCommand>(
"/session/*/timeouts/async_script");
dispatcher->Add<ImplicitWaitCommand>( "/session/*/timeouts/implicit_wait");
dispatcher->Add<CookieCommand>( "/session/*/cookie");
dispatcher->Add<NamedCookieCommand>("/session/*/cookie/*");
dispatcher->Add<SessionWithID>("/session/*");
if (forbid_other_requests)
dispatcher->ForbidAllOtherRequests();
}
| 170,460
|
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: int32_t DownmixLib_Create(const effect_uuid_t *uuid,
int32_t sessionId,
int32_t ioId,
effect_handle_t *pHandle) {
int ret;
int i;
downmix_module_t *module;
const effect_descriptor_t *desc;
ALOGV("DownmixLib_Create()");
#ifdef DOWNMIX_TEST_CHANNEL_INDEX
ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should work:");
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT |
AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_CENTER);
Downmix_testIndexComputation(CHANNEL_MASK_QUAD_SIDE | CHANNEL_MASK_QUAD_BACK);
Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_SIDE | AUDIO_CHANNEL_OUT_BACK_CENTER);
Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_BACK | AUDIO_CHANNEL_OUT_BACK_CENTER);
ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should NOT work:");
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT |
AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_LEFT);
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT |
AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_SIDE_LEFT);
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT |
AUDIO_CHANNEL_OUT_BACK_LEFT | AUDIO_CHANNEL_OUT_BACK_RIGHT);
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT |
AUDIO_CHANNEL_OUT_SIDE_LEFT | AUDIO_CHANNEL_OUT_SIDE_RIGHT);
#endif
if (pHandle == NULL || uuid == NULL) {
return -EINVAL;
}
for (i = 0 ; i < kNbEffects ; i++) {
desc = gDescriptors[i];
if (memcmp(uuid, &desc->uuid, sizeof(effect_uuid_t)) == 0) {
break;
}
}
if (i == kNbEffects) {
return -ENOENT;
}
module = malloc(sizeof(downmix_module_t));
module->itfe = &gDownmixInterface;
module->context.state = DOWNMIX_STATE_UNINITIALIZED;
ret = Downmix_Init(module);
if (ret < 0) {
ALOGW("DownmixLib_Create() init failed");
free(module);
return ret;
}
*pHandle = (effect_handle_t) module;
ALOGV("DownmixLib_Create() %p , size %zu", module, sizeof(downmix_module_t));
return 0;
}
Commit Message: audio effects: fix heap overflow
Check consistency of effect command reply sizes before
copying to reply address.
Also add null pointer check on reply size.
Also remove unused parameter warning.
Bug: 21953516.
Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4
(cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844)
CWE ID: CWE-119
|
int32_t DownmixLib_Create(const effect_uuid_t *uuid,
int32_t sessionId __unused,
int32_t ioId __unused,
effect_handle_t *pHandle) {
int ret;
int i;
downmix_module_t *module;
const effect_descriptor_t *desc;
ALOGV("DownmixLib_Create()");
#ifdef DOWNMIX_TEST_CHANNEL_INDEX
ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should work:");
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT |
AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_CENTER);
Downmix_testIndexComputation(CHANNEL_MASK_QUAD_SIDE | CHANNEL_MASK_QUAD_BACK);
Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_SIDE | AUDIO_CHANNEL_OUT_BACK_CENTER);
Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_BACK | AUDIO_CHANNEL_OUT_BACK_CENTER);
ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should NOT work:");
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT |
AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_LEFT);
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT |
AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_SIDE_LEFT);
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT |
AUDIO_CHANNEL_OUT_BACK_LEFT | AUDIO_CHANNEL_OUT_BACK_RIGHT);
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT |
AUDIO_CHANNEL_OUT_SIDE_LEFT | AUDIO_CHANNEL_OUT_SIDE_RIGHT);
#endif
if (pHandle == NULL || uuid == NULL) {
return -EINVAL;
}
for (i = 0 ; i < kNbEffects ; i++) {
desc = gDescriptors[i];
if (memcmp(uuid, &desc->uuid, sizeof(effect_uuid_t)) == 0) {
break;
}
}
if (i == kNbEffects) {
return -ENOENT;
}
module = malloc(sizeof(downmix_module_t));
module->itfe = &gDownmixInterface;
module->context.state = DOWNMIX_STATE_UNINITIALIZED;
ret = Downmix_Init(module);
if (ret < 0) {
ALOGW("DownmixLib_Create() init failed");
free(module);
return ret;
}
*pHandle = (effect_handle_t) module;
ALOGV("DownmixLib_Create() %p , size %zu", module, sizeof(downmix_module_t));
return 0;
}
| 173,343
|
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: SYSCALL_DEFINE1(inotify_init1, int, flags)
{
struct fsnotify_group *group;
struct user_struct *user;
int ret;
/* Check the IN_* constants for consistency. */
BUILD_BUG_ON(IN_CLOEXEC != O_CLOEXEC);
BUILD_BUG_ON(IN_NONBLOCK != O_NONBLOCK);
if (flags & ~(IN_CLOEXEC | IN_NONBLOCK))
return -EINVAL;
user = get_current_user();
if (unlikely(atomic_read(&user->inotify_devs) >=
inotify_max_user_instances)) {
ret = -EMFILE;
goto out_free_uid;
}
/* fsnotify_obtain_group took a reference to group, we put this when we kill the file in the end */
group = inotify_new_group(user, inotify_max_queued_events);
if (IS_ERR(group)) {
ret = PTR_ERR(group);
goto out_free_uid;
}
atomic_inc(&user->inotify_devs);
ret = anon_inode_getfd("inotify", &inotify_fops, group,
O_RDONLY | flags);
if (ret >= 0)
return ret;
atomic_dec(&user->inotify_devs);
out_free_uid:
free_uid(user);
return ret;
}
Commit Message: inotify: stop kernel memory leak on file creation failure
If inotify_init is unable to allocate a new file for the new inotify
group we leak the new group. This patch drops the reference on the
group on file allocation failure.
Reported-by: Vegard Nossum <vegard.nossum@gmail.com>
cc: stable@kernel.org
Signed-off-by: Eric Paris <eparis@redhat.com>
CWE ID: CWE-399
|
SYSCALL_DEFINE1(inotify_init1, int, flags)
{
struct fsnotify_group *group;
struct user_struct *user;
int ret;
/* Check the IN_* constants for consistency. */
BUILD_BUG_ON(IN_CLOEXEC != O_CLOEXEC);
BUILD_BUG_ON(IN_NONBLOCK != O_NONBLOCK);
if (flags & ~(IN_CLOEXEC | IN_NONBLOCK))
return -EINVAL;
user = get_current_user();
if (unlikely(atomic_read(&user->inotify_devs) >=
inotify_max_user_instances)) {
ret = -EMFILE;
goto out_free_uid;
}
/* fsnotify_obtain_group took a reference to group, we put this when we kill the file in the end */
group = inotify_new_group(user, inotify_max_queued_events);
if (IS_ERR(group)) {
ret = PTR_ERR(group);
goto out_free_uid;
}
atomic_inc(&user->inotify_devs);
ret = anon_inode_getfd("inotify", &inotify_fops, group,
O_RDONLY | flags);
if (ret >= 0)
return ret;
fsnotify_put_group(group);
atomic_dec(&user->inotify_devs);
out_free_uid:
free_uid(user);
return ret;
}
| 165,908
|
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: auth_read_binary(struct sc_card *card, unsigned int offset,
unsigned char *buf, size_t count, unsigned long flags)
{
int rv;
struct sc_pkcs15_bignum bn[2];
unsigned char *out = NULL;
bn[0].data = NULL;
bn[1].data = NULL;
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx,
"offset %i; size %"SC_FORMAT_LEN_SIZE_T"u; flags 0x%lX",
offset, count, flags);
sc_log(card->ctx,"last selected : magic %X; ef %X",
auth_current_ef->magic, auth_current_ef->ef_structure);
if (offset & ~0x7FFF)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid file offset");
if (auth_current_ef->magic==SC_FILE_MAGIC &&
auth_current_ef->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC) {
int jj;
unsigned char resp[256];
size_t resp_len, out_len;
struct sc_pkcs15_pubkey_rsa key;
resp_len = sizeof(resp);
rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC,
2, resp, resp_len);
LOG_TEST_RET(card->ctx, rv, "read component failed");
for (jj=0; jj<rv && *(resp+jj)==0; jj++)
;
bn[0].data = calloc(1, rv - jj);
if (!bn[0].data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
bn[0].len = rv - jj;
memcpy(bn[0].data, resp + jj, rv - jj);
rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC,
1, resp, resp_len);
LOG_TEST_GOTO_ERR(card->ctx, rv, "Cannot read RSA public key component");
bn[1].data = calloc(1, rv);
if (!bn[1].data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
bn[1].len = rv;
memcpy(bn[1].data, resp, rv);
key.exponent = bn[0];
key.modulus = bn[1];
if (sc_pkcs15_encode_pubkey_rsa(card->ctx, &key, &out, &out_len)) {
rv = SC_ERROR_INVALID_ASN1_OBJECT;
LOG_TEST_GOTO_ERR(card->ctx, rv, "cannot encode RSA public key");
}
else {
rv = out_len - offset > count ? count : out_len - offset;
memcpy(buf, out + offset, rv);
sc_log_hex(card->ctx, "write_publickey", buf, rv);
}
}
else {
rv = iso_ops->read_binary(card, offset, buf, count, 0);
}
err:
free(bn[0].data);
free(bn[1].data);
free(out);
LOG_FUNC_RETURN(card->ctx, rv);
}
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
|
auth_read_binary(struct sc_card *card, unsigned int offset,
unsigned char *buf, size_t count, unsigned long flags)
{
int rv;
struct sc_pkcs15_bignum bn[2];
unsigned char *out = NULL;
bn[0].data = NULL;
bn[1].data = NULL;
LOG_FUNC_CALLED(card->ctx);
if (!auth_current_ef)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid auth_current_ef");
sc_log(card->ctx,
"offset %i; size %"SC_FORMAT_LEN_SIZE_T"u; flags 0x%lX",
offset, count, flags);
sc_log(card->ctx,"last selected : magic %X; ef %X",
auth_current_ef->magic, auth_current_ef->ef_structure);
if (offset & ~0x7FFF)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid file offset");
if (auth_current_ef->magic==SC_FILE_MAGIC &&
auth_current_ef->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC) {
int jj;
unsigned char resp[256];
size_t resp_len, out_len;
struct sc_pkcs15_pubkey_rsa key;
resp_len = sizeof(resp);
rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC,
2, resp, resp_len);
LOG_TEST_RET(card->ctx, rv, "read component failed");
for (jj=0; jj<rv && *(resp+jj)==0; jj++)
;
bn[0].data = calloc(1, rv - jj);
if (!bn[0].data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
bn[0].len = rv - jj;
memcpy(bn[0].data, resp + jj, rv - jj);
rv = auth_read_component(card, SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC,
1, resp, resp_len);
LOG_TEST_GOTO_ERR(card->ctx, rv, "Cannot read RSA public key component");
bn[1].data = calloc(1, rv);
if (!bn[1].data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
bn[1].len = rv;
memcpy(bn[1].data, resp, rv);
key.exponent = bn[0];
key.modulus = bn[1];
if (sc_pkcs15_encode_pubkey_rsa(card->ctx, &key, &out, &out_len)) {
rv = SC_ERROR_INVALID_ASN1_OBJECT;
LOG_TEST_GOTO_ERR(card->ctx, rv, "cannot encode RSA public key");
}
else {
rv = out_len - offset > count ? count : out_len - offset;
memcpy(buf, out + offset, rv);
sc_log_hex(card->ctx, "write_publickey", buf, rv);
}
}
else {
rv = iso_ops->read_binary(card, offset, buf, count, 0);
}
err:
free(bn[0].data);
free(bn[1].data);
free(out);
LOG_FUNC_RETURN(card->ctx, rv);
}
| 169,058
|
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 FrameFetchContext::AddResourceTiming(const ResourceTimingInfo& info) {
if (!document_)
return;
LocalFrame* frame = document_->GetFrame();
if (!frame)
return;
if (info.IsMainResource()) {
DCHECK(frame->Owner());
frame->Owner()->AddResourceTiming(info);
frame->DidSendResourceTimingInfoToParent();
return;
}
DOMWindowPerformance::performance(*document_->domWindow())
->GenerateAndAddResourceTiming(info);
}
Commit Message: Do not forward resource timing to parent frame after back-forward navigation
LocalFrame has |should_send_resource_timing_info_to_parent_| flag not to
send timing info to parent except for the first navigation. This flag is
cleared when the first timing is sent to parent, however this does not happen
if iframe's first navigation was by back-forward navigation. For such
iframes, we shouldn't send timings to parent at all.
Bug: 876822
Change-Id: I128b51a82ef278c439548afc8283ae63abdef5c5
Reviewed-on: https://chromium-review.googlesource.com/1186215
Reviewed-by: Kinuko Yasuda <kinuko@chromium.org>
Commit-Queue: Kunihiko Sakamoto <ksakamoto@chromium.org>
Cr-Commit-Position: refs/heads/master@{#585736}
CWE ID: CWE-200
|
void FrameFetchContext::AddResourceTiming(const ResourceTimingInfo& info) {
if (!document_)
return;
LocalFrame* frame = document_->GetFrame();
if (!frame)
return;
if (info.IsMainResource()) {
DCHECK(frame->Owner());
frame->Owner()->AddResourceTiming(info);
frame->SetShouldSendResourceTimingInfoToParent(false);
return;
}
DOMWindowPerformance::performance(*document_->domWindow())
->GenerateAndAddResourceTiming(info);
}
| 172,656
|
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: BIGNUM *SRP_Calc_u(BIGNUM *A, BIGNUM *B, BIGNUM *N)
{
/* k = SHA1(PAD(A) || PAD(B) ) -- tls-srp draft 8 */
BIGNUM *u;
unsigned char cu[SHA_DIGEST_LENGTH];
unsigned char *cAB;
EVP_MD_CTX ctxt;
int longN;
if ((A == NULL) ||(B == NULL) || (N == NULL))
return NULL;
if ((A == NULL) ||(B == NULL) || (N == NULL))
return NULL;
longN= BN_num_bytes(N);
if ((cAB = OPENSSL_malloc(2*longN)) == NULL)
EVP_DigestUpdate(&ctxt, cAB + BN_bn2bin(A,cAB+longN), longN);
EVP_DigestUpdate(&ctxt, cAB + BN_bn2bin(B,cAB+longN), longN);
OPENSSL_free(cAB);
EVP_DigestFinal_ex(&ctxt, cu, NULL);
EVP_MD_CTX_cleanup(&ctxt);
if (!(u = BN_bin2bn(cu, sizeof(cu), NULL)))
return NULL;
if (!BN_is_zero(u))
return u;
BN_free(u);
return NULL;
}
Commit Message:
CWE ID: CWE-119
|
BIGNUM *SRP_Calc_u(BIGNUM *A, BIGNUM *B, BIGNUM *N)
{
/* k = SHA1(PAD(A) || PAD(B) ) -- tls-srp draft 8 */
BIGNUM *u;
unsigned char cu[SHA_DIGEST_LENGTH];
unsigned char *cAB;
EVP_MD_CTX ctxt;
int longN;
if ((A == NULL) ||(B == NULL) || (N == NULL))
return NULL;
if ((A == NULL) ||(B == NULL) || (N == NULL))
return NULL;
if (BN_ucmp(A, N) >= 0 || BN_ucmp(B, N) >= 0)
return NULL;
longN= BN_num_bytes(N);
if ((cAB = OPENSSL_malloc(2*longN)) == NULL)
EVP_DigestUpdate(&ctxt, cAB + BN_bn2bin(A,cAB+longN), longN);
EVP_DigestUpdate(&ctxt, cAB + BN_bn2bin(B,cAB+longN), longN);
OPENSSL_free(cAB);
EVP_DigestFinal_ex(&ctxt, cu, NULL);
EVP_MD_CTX_cleanup(&ctxt);
if (!(u = BN_bin2bn(cu, sizeof(cu), NULL)))
return NULL;
if (!BN_is_zero(u))
return u;
BN_free(u);
return NULL;
}
| 165,172
|
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: cff_charset_load( CFF_Charset charset,
FT_UInt num_glyphs,
FT_Stream stream,
FT_ULong base_offset,
FT_ULong offset,
FT_Bool invert )
{
FT_Memory memory = stream->memory;
FT_Error error = CFF_Err_Ok;
FT_UShort glyph_sid;
/* If the the offset is greater than 2, we have to parse the */
/* charset table. */
if ( offset > 2 )
{
FT_UInt j;
charset->offset = base_offset + offset;
/* Get the format of the table. */
if ( FT_STREAM_SEEK( charset->offset ) ||
FT_READ_BYTE( charset->format ) )
goto Exit;
/* Allocate memory for sids. */
if ( FT_NEW_ARRAY( charset->sids, num_glyphs ) )
goto Exit;
/* assign the .notdef glyph */
charset->sids[0] = 0;
switch ( charset->format )
{
case 0:
if ( num_glyphs > 0 )
{
if ( FT_FRAME_ENTER( ( num_glyphs - 1 ) * 2 ) )
goto Exit;
for ( j = 1; j < num_glyphs; j++ )
charset->sids[j] = FT_GET_USHORT();
FT_FRAME_EXIT();
}
/* Read the first glyph sid of the range. */
if ( FT_READ_USHORT( glyph_sid ) )
goto Exit;
/* Read the number of glyphs in the range. */
if ( charset->format == 2 )
{
if ( FT_READ_USHORT( nleft ) )
goto Exit;
}
else
{
if ( FT_READ_BYTE( nleft ) )
goto Exit;
}
/* Fill in the range of sids -- `nleft + 1' glyphs. */
for ( i = 0; j < num_glyphs && i <= nleft; i++, j++, glyph_sid++ )
charset->sids[j] = glyph_sid;
}
}
break;
default:
FT_ERROR(( "cff_charset_load: invalid table format!\n" ));
error = CFF_Err_Invalid_File_Format;
goto Exit;
}
Commit Message:
CWE ID: CWE-189
|
cff_charset_load( CFF_Charset charset,
FT_UInt num_glyphs,
FT_Stream stream,
FT_ULong base_offset,
FT_ULong offset,
FT_Bool invert )
{
FT_Memory memory = stream->memory;
FT_Error error = CFF_Err_Ok;
FT_UShort glyph_sid;
/* If the the offset is greater than 2, we have to parse the */
/* charset table. */
if ( offset > 2 )
{
FT_UInt j;
charset->offset = base_offset + offset;
/* Get the format of the table. */
if ( FT_STREAM_SEEK( charset->offset ) ||
FT_READ_BYTE( charset->format ) )
goto Exit;
/* Allocate memory for sids. */
if ( FT_NEW_ARRAY( charset->sids, num_glyphs ) )
goto Exit;
/* assign the .notdef glyph */
charset->sids[0] = 0;
switch ( charset->format )
{
case 0:
if ( num_glyphs > 0 )
{
if ( FT_FRAME_ENTER( ( num_glyphs - 1 ) * 2 ) )
goto Exit;
for ( j = 1; j < num_glyphs; j++ )
{
FT_UShort sid = FT_GET_USHORT();
/* this constant is given in the CFF specification */
if ( sid < 65000 )
charset->sids[j] = sid;
else
{
FT_ERROR(( "cff_charset_load:"
" invalid SID value %d set to zero\n", sid ));
charset->sids[j] = 0;
}
}
FT_FRAME_EXIT();
}
/* Read the first glyph sid of the range. */
if ( FT_READ_USHORT( glyph_sid ) )
goto Exit;
/* Read the number of glyphs in the range. */
if ( charset->format == 2 )
{
if ( FT_READ_USHORT( nleft ) )
goto Exit;
}
else
{
if ( FT_READ_BYTE( nleft ) )
goto Exit;
}
/* Fill in the range of sids -- `nleft + 1' glyphs. */
for ( i = 0; j < num_glyphs && i <= nleft; i++, j++, glyph_sid++ )
charset->sids[j] = glyph_sid;
}
}
break;
default:
FT_ERROR(( "cff_charset_load: invalid table format!\n" ));
error = CFF_Err_Invalid_File_Format;
goto Exit;
}
| 164,743
|
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 Reset() {
events_.clear();
tap_ = false;
tap_down_ = false;
tap_cancel_ = false;
begin_ = false;
end_ = false;
scroll_begin_ = false;
scroll_update_ = false;
scroll_end_ = false;
pinch_begin_ = false;
pinch_update_ = false;
pinch_end_ = false;
long_press_ = false;
fling_ = false;
two_finger_tap_ = false;
show_press_ = false;
swipe_left_ = false;
swipe_right_ = false;
swipe_up_ = false;
swipe_down_ = false;
scroll_begin_position_.SetPoint(0, 0);
tap_location_.SetPoint(0, 0);
gesture_end_location_.SetPoint(0, 0);
scroll_x_ = 0;
scroll_y_ = 0;
scroll_velocity_x_ = 0;
scroll_velocity_y_ = 0;
velocity_x_ = 0;
velocity_y_ = 0;
scroll_x_hint_ = 0;
scroll_y_hint_ = 0;
tap_count_ = 0;
scale_ = 0;
flags_ = 0;
}
Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura.
BUG=379812
TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent
Review URL: https://codereview.chromium.org/309823002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void Reset() {
events_.clear();
tap_ = false;
tap_down_ = false;
tap_cancel_ = false;
begin_ = false;
end_ = false;
scroll_begin_ = false;
scroll_update_ = false;
scroll_end_ = false;
pinch_begin_ = false;
pinch_update_ = false;
pinch_end_ = false;
long_press_ = false;
fling_ = false;
two_finger_tap_ = false;
show_press_ = false;
swipe_left_ = false;
swipe_right_ = false;
swipe_up_ = false;
swipe_down_ = false;
scroll_begin_position_.SetPoint(0, 0);
tap_location_.SetPoint(0, 0);
gesture_end_location_.SetPoint(0, 0);
scroll_x_ = 0;
scroll_y_ = 0;
scroll_velocity_x_ = 0;
scroll_velocity_y_ = 0;
velocity_x_ = 0;
velocity_y_ = 0;
scroll_x_hint_ = 0;
scroll_y_hint_ = 0;
tap_count_ = 0;
scale_ = 0;
flags_ = 0;
latency_info_.Clear();
}
| 171,203
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.