instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t MediaPlayer::setDataSource(const sp<IStreamSource> &source)
{
ALOGV("setDataSource");
status_t err = UNKNOWN_ERROR;
const sp<IMediaPlayerService>& service(getMediaPlayerService());
if (service != 0) {
sp<IMediaPlayer> player(service->create(this, mAudioSessionId));
if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
(NO_ERROR != player->setDataSource(source))) {
player.clear();
}
err = attachNewPlayer(player);
}
return err;
}
Commit Message: Don't use sp<>&
because they may end up pointing to NULL after a NULL check was performed.
Bug: 28166152
Change-Id: Iab2ea30395b620628cc6f3d067dd4f6fcda824fe
CWE ID: CWE-476 | status_t MediaPlayer::setDataSource(const sp<IStreamSource> &source)
{
ALOGV("setDataSource");
status_t err = UNKNOWN_ERROR;
const sp<IMediaPlayerService> service(getMediaPlayerService());
if (service != 0) {
sp<IMediaPlayer> player(service->create(this, mAudioSessionId));
if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
(NO_ERROR != player->setDataSource(source))) {
player.clear();
}
err = attachNewPlayer(player);
}
return err;
}
| 173,539 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 snd_timer_start_slave(struct snd_timer_instance *timeri)
{
unsigned long flags;
spin_lock_irqsave(&slave_active_lock, flags);
timeri->flags |= SNDRV_TIMER_IFLG_RUNNING;
if (timeri->master)
list_add_tail(&timeri->active_list,
&timeri->master->slave_active_head);
spin_unlock_irqrestore(&slave_active_lock, flags);
return 1; /* delayed start */
}
Commit Message: ALSA: timer: Harden slave timer list handling
A slave timer instance might be still accessible in a racy way while
operating the master instance as it lacks of locking. Since the
master operation is mostly protected with timer->lock, we should cope
with it while changing the slave instance, too. Also, some linked
lists (active_list and ack_list) of slave instances aren't unlinked
immediately at stopping or closing, and this may lead to unexpected
accesses.
This patch tries to address these issues. It adds spin lock of
timer->lock (either from master or slave, which is equivalent) in a
few places. For avoiding a deadlock, we ensure that the global
slave_active_lock is always locked at first before each timer lock.
Also, ack and active_list of slave instances are properly unlinked at
snd_timer_stop() and snd_timer_close().
Last but not least, remove the superfluous call of _snd_timer_stop()
at removing slave links. This is a noop, and calling it may confuse
readers wrt locking. Further cleanup will follow in a later patch.
Actually we've got reports of use-after-free by syzkaller fuzzer, and
this hopefully fixes these issues.
Reported-by: Dmitry Vyukov <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-20 | static int snd_timer_start_slave(struct snd_timer_instance *timeri)
{
unsigned long flags;
spin_lock_irqsave(&slave_active_lock, flags);
timeri->flags |= SNDRV_TIMER_IFLG_RUNNING;
if (timeri->master && timeri->timer) {
spin_lock(&timeri->timer->lock);
list_add_tail(&timeri->active_list,
&timeri->master->slave_active_head);
spin_unlock(&timeri->timer->lock);
}
spin_unlock_irqrestore(&slave_active_lock, flags);
return 1; /* delayed start */
}
| 167,403 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GIOChannel *net_connect_ip_ssl(IPADDR *ip, int port, IPADDR *my_ip, const char *cert, const char *pkey, const char *cafile, const char *capath, gboolean verify)
{
GIOChannel *handle, *ssl_handle;
handle = net_connect_ip(ip, port, my_ip);
if (handle == NULL)
return NULL;
ssl_handle = irssi_ssl_get_iochannel(handle, cert, pkey, cafile, capath, verify);
if (ssl_handle == NULL)
g_io_channel_unref(handle);
return ssl_handle;
}
Commit Message: Check if an SSL certificate matches the hostname of the server we are connecting to
git-svn-id: http://svn.irssi.org/repos/irssi/trunk@5104 dbcabf3a-b0e7-0310-adc4-f8d773084564
CWE ID: CWE-20 | GIOChannel *net_connect_ip_ssl(IPADDR *ip, int port, IPADDR *my_ip, const char *cert, const char *pkey, const char *cafile, const char *capath, gboolean verify)
GIOChannel *net_connect_ip_ssl(IPADDR *ip, int port, const char* hostname, IPADDR *my_ip, const char *cert, const char *pkey, const char *cafile, const char *capath, gboolean verify)
{
GIOChannel *handle, *ssl_handle;
handle = net_connect_ip(ip, port, my_ip);
if (handle == NULL)
return NULL;
ssl_handle = irssi_ssl_get_iochannel(handle, hostname, cert, pkey, cafile, capath, verify);
if (ssl_handle == NULL)
g_io_channel_unref(handle);
return ssl_handle;
}
| 165,519 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *__dma_alloc_coherent(struct device *dev, size_t size,
dma_addr_t *dma_handle, gfp_t flags,
struct dma_attrs *attrs)
{
if (dev == NULL) {
WARN_ONCE(1, "Use an actual device structure for DMA allocation\n");
return NULL;
}
if (IS_ENABLED(CONFIG_ZONE_DMA) &&
dev->coherent_dma_mask <= DMA_BIT_MASK(32))
flags |= GFP_DMA;
if (IS_ENABLED(CONFIG_DMA_CMA) && (flags & __GFP_WAIT)) {
struct page *page;
void *addr;
size = PAGE_ALIGN(size);
page = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT,
get_order(size));
if (!page)
return NULL;
*dma_handle = phys_to_dma(dev, page_to_phys(page));
addr = page_address(page);
if (flags & __GFP_ZERO)
memset(addr, 0, size);
return addr;
} else {
return swiotlb_alloc_coherent(dev, size, dma_handle, flags);
}
}
Commit Message: arm64: dma-mapping: always clear allocated buffers
Buffers allocated by dma_alloc_coherent() are always zeroed on Alpha,
ARM (32bit), MIPS, PowerPC, x86/x86_64 and probably other architectures.
It turned out that some drivers rely on this 'feature'. Allocated buffer
might be also exposed to userspace with dma_mmap() call, so clearing it
is desired from security point of view to avoid exposing random memory
to userspace. This patch unifies dma_alloc_coherent() behavior on ARM64
architecture with other implementations by unconditionally zeroing
allocated buffer.
Cc: <[email protected]> # v3.14+
Signed-off-by: Marek Szyprowski <[email protected]>
Signed-off-by: Will Deacon <[email protected]>
CWE ID: CWE-200 | static void *__dma_alloc_coherent(struct device *dev, size_t size,
dma_addr_t *dma_handle, gfp_t flags,
struct dma_attrs *attrs)
{
if (dev == NULL) {
WARN_ONCE(1, "Use an actual device structure for DMA allocation\n");
return NULL;
}
if (IS_ENABLED(CONFIG_ZONE_DMA) &&
dev->coherent_dma_mask <= DMA_BIT_MASK(32))
flags |= GFP_DMA;
if (IS_ENABLED(CONFIG_DMA_CMA) && (flags & __GFP_WAIT)) {
struct page *page;
void *addr;
size = PAGE_ALIGN(size);
page = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT,
get_order(size));
if (!page)
return NULL;
*dma_handle = phys_to_dma(dev, page_to_phys(page));
addr = page_address(page);
memset(addr, 0, size);
return addr;
} else {
return swiotlb_alloc_coherent(dev, size, dma_handle, flags);
}
}
| 167,471 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)
{
struct super_block *sb = inode->i_sb;
handle_t *handle;
struct ext4_ext_path *path;
struct ext4_extent *extent;
ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
unsigned int credits, ee_len;
int ret = 0, depth, split_flag = 0;
loff_t ioffset;
/*
* We need to test this early because xfstests assumes that an
* insert range of (0, 1) will return EOPNOTSUPP if the file
* system does not support insert range.
*/
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
return -EOPNOTSUPP;
/* Insert range works only on fs block size aligned offsets. */
if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
len & (EXT4_CLUSTER_SIZE(sb) - 1))
return -EINVAL;
if (!S_ISREG(inode->i_mode))
return -EOPNOTSUPP;
trace_ext4_insert_range(inode, offset, len);
offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
/* Call ext4_force_commit to flush all data in case of data=journal */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
/*
* Need to round down to align start offset to page size boundary
* for page size > block size.
*/
ioffset = round_down(offset, PAGE_SIZE);
/* Write out all dirty pages */
ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
LLONG_MAX);
if (ret)
return ret;
/* Take mutex lock */
mutex_lock(&inode->i_mutex);
/* Currently just for extent based files */
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
/* Check for wrap through zero */
if (inode->i_size + len > inode->i_sb->s_maxbytes) {
ret = -EFBIG;
goto out_mutex;
}
/* Offset should be less than i_size */
if (offset >= i_size_read(inode)) {
ret = -EINVAL;
goto out_mutex;
}
truncate_pagecache(inode, ioffset);
/* Wait for existing dio to complete */
ext4_inode_block_unlocked_dio(inode);
inode_dio_wait(inode);
credits = ext4_writepage_trans_blocks(inode);
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out_dio;
}
/* Expand file to avoid data loss if there is error while shifting */
inode->i_size += len;
EXT4_I(inode)->i_disksize += len;
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
ret = ext4_mark_inode_dirty(handle, inode);
if (ret)
goto out_stop;
down_write(&EXT4_I(inode)->i_data_sem);
ext4_discard_preallocations(inode);
path = ext4_find_extent(inode, offset_lblk, NULL, 0);
if (IS_ERR(path)) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
depth = ext_depth(inode);
extent = path[depth].p_ext;
if (extent) {
ee_start_lblk = le32_to_cpu(extent->ee_block);
ee_len = ext4_ext_get_actual_len(extent);
/*
* If offset_lblk is not the starting block of extent, split
* the extent @offset_lblk
*/
if ((offset_lblk > ee_start_lblk) &&
(offset_lblk < (ee_start_lblk + ee_len))) {
if (ext4_ext_is_unwritten(extent))
split_flag = EXT4_EXT_MARK_UNWRIT1 |
EXT4_EXT_MARK_UNWRIT2;
ret = ext4_split_extent_at(handle, inode, &path,
offset_lblk, split_flag,
EXT4_EX_NOCACHE |
EXT4_GET_BLOCKS_PRE_IO |
EXT4_GET_BLOCKS_METADATA_NOFAIL);
}
ext4_ext_drop_refs(path);
kfree(path);
if (ret < 0) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
}
ret = ext4_es_remove_extent(inode, offset_lblk,
EXT_MAX_BLOCKS - offset_lblk);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
/*
* if offset_lblk lies in a hole which is at start of file, use
* ee_start_lblk to shift extents
*/
ret = ext4_ext_shift_extents(inode, handle,
ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
len_lblk, SHIFT_RIGHT);
up_write(&EXT4_I(inode)->i_data_sem);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
out_stop:
ext4_journal_stop(handle);
out_dio:
ext4_inode_resume_unlocked_dio(inode);
out_mutex:
mutex_unlock(&inode->i_mutex);
return ret;
}
Commit Message: ext4: fix races between page faults and hole punching
Currently, page faults and hole punching are completely unsynchronized.
This can result in page fault faulting in a page into a range that we
are punching after truncate_pagecache_range() has been called and thus
we can end up with a page mapped to disk blocks that will be shortly
freed. Filesystem corruption will shortly follow. Note that the same
race is avoided for truncate by checking page fault offset against
i_size but there isn't similar mechanism available for punching holes.
Fix the problem by creating new rw semaphore i_mmap_sem in inode and
grab it for writing over truncate, hole punching, and other functions
removing blocks from extent tree and for read over page faults. We
cannot easily use i_data_sem for this since that ranks below transaction
start and we need something ranking above it so that it can be held over
the whole truncate / hole punching operation. Also remove various
workarounds we had in the code to reduce race window when page fault
could have created pages with stale mapping information.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-362 | int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len)
{
struct super_block *sb = inode->i_sb;
handle_t *handle;
struct ext4_ext_path *path;
struct ext4_extent *extent;
ext4_lblk_t offset_lblk, len_lblk, ee_start_lblk = 0;
unsigned int credits, ee_len;
int ret = 0, depth, split_flag = 0;
loff_t ioffset;
/*
* We need to test this early because xfstests assumes that an
* insert range of (0, 1) will return EOPNOTSUPP if the file
* system does not support insert range.
*/
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
return -EOPNOTSUPP;
/* Insert range works only on fs block size aligned offsets. */
if (offset & (EXT4_CLUSTER_SIZE(sb) - 1) ||
len & (EXT4_CLUSTER_SIZE(sb) - 1))
return -EINVAL;
if (!S_ISREG(inode->i_mode))
return -EOPNOTSUPP;
trace_ext4_insert_range(inode, offset, len);
offset_lblk = offset >> EXT4_BLOCK_SIZE_BITS(sb);
len_lblk = len >> EXT4_BLOCK_SIZE_BITS(sb);
/* Call ext4_force_commit to flush all data in case of data=journal */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
/*
* Need to round down to align start offset to page size boundary
* for page size > block size.
*/
ioffset = round_down(offset, PAGE_SIZE);
/* Write out all dirty pages */
ret = filemap_write_and_wait_range(inode->i_mapping, ioffset,
LLONG_MAX);
if (ret)
return ret;
/* Take mutex lock */
mutex_lock(&inode->i_mutex);
/* Currently just for extent based files */
if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
/* Check for wrap through zero */
if (inode->i_size + len > inode->i_sb->s_maxbytes) {
ret = -EFBIG;
goto out_mutex;
}
/* Offset should be less than i_size */
if (offset >= i_size_read(inode)) {
ret = -EINVAL;
goto out_mutex;
}
/* Wait for existing dio to complete */
ext4_inode_block_unlocked_dio(inode);
inode_dio_wait(inode);
/*
* Prevent page faults from reinstantiating pages we have released from
* page cache.
*/
down_write(&EXT4_I(inode)->i_mmap_sem);
truncate_pagecache(inode, ioffset);
credits = ext4_writepage_trans_blocks(inode);
handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out_mmap;
}
/* Expand file to avoid data loss if there is error while shifting */
inode->i_size += len;
EXT4_I(inode)->i_disksize += len;
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
ret = ext4_mark_inode_dirty(handle, inode);
if (ret)
goto out_stop;
down_write(&EXT4_I(inode)->i_data_sem);
ext4_discard_preallocations(inode);
path = ext4_find_extent(inode, offset_lblk, NULL, 0);
if (IS_ERR(path)) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
depth = ext_depth(inode);
extent = path[depth].p_ext;
if (extent) {
ee_start_lblk = le32_to_cpu(extent->ee_block);
ee_len = ext4_ext_get_actual_len(extent);
/*
* If offset_lblk is not the starting block of extent, split
* the extent @offset_lblk
*/
if ((offset_lblk > ee_start_lblk) &&
(offset_lblk < (ee_start_lblk + ee_len))) {
if (ext4_ext_is_unwritten(extent))
split_flag = EXT4_EXT_MARK_UNWRIT1 |
EXT4_EXT_MARK_UNWRIT2;
ret = ext4_split_extent_at(handle, inode, &path,
offset_lblk, split_flag,
EXT4_EX_NOCACHE |
EXT4_GET_BLOCKS_PRE_IO |
EXT4_GET_BLOCKS_METADATA_NOFAIL);
}
ext4_ext_drop_refs(path);
kfree(path);
if (ret < 0) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
}
ret = ext4_es_remove_extent(inode, offset_lblk,
EXT_MAX_BLOCKS - offset_lblk);
if (ret) {
up_write(&EXT4_I(inode)->i_data_sem);
goto out_stop;
}
/*
* if offset_lblk lies in a hole which is at start of file, use
* ee_start_lblk to shift extents
*/
ret = ext4_ext_shift_extents(inode, handle,
ee_start_lblk > offset_lblk ? ee_start_lblk : offset_lblk,
len_lblk, SHIFT_RIGHT);
up_write(&EXT4_I(inode)->i_data_sem);
if (IS_SYNC(inode))
ext4_handle_sync(handle);
out_stop:
ext4_journal_stop(handle);
out_mmap:
up_write(&EXT4_I(inode)->i_mmap_sem);
ext4_inode_resume_unlocked_dio(inode);
out_mutex:
mutex_unlock(&inode->i_mutex);
return ret;
}
| 167,484 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Chapters::Atom::ExpandDisplaysArray()
{
if (m_displays_size > m_displays_count)
return true; // nothing else to do
const int size = (m_displays_size == 0) ? 1 : 2 * m_displays_size;
Display* const displays = new (std::nothrow) Display[size];
if (displays == NULL)
return false;
for (int idx = 0; idx < m_displays_count; ++idx)
{
m_displays[idx].ShallowCopy(displays[idx]);
}
delete[] m_displays;
m_displays = displays;
m_displays_size = size;
return true;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | bool Chapters::Atom::ExpandDisplaysArray()
| 174,275 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped");
base::ScopedClosureRunner scoped_completion_runner(
base::Bind(&AcceleratedSurfaceBuffersSwappedCompleted,
host_id_, params.route_id, params.surface_id,
true, base::TimeTicks(), base::TimeDelta()));
gfx::PluginWindowHandle handle =
GpuSurfaceTracker::Get()->GetSurfaceWindowHandle(params.surface_id);
if (!handle) {
TRACE_EVENT1("gpu", "SurfaceIDNotFound_RoutingToUI",
"surface_id", params.surface_id);
#if defined(USE_AURA)
scoped_completion_runner.Release();
RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
#endif
return;
}
scoped_refptr<AcceleratedPresenter> presenter(
AcceleratedPresenter::GetForWindow(handle));
if (!presenter) {
TRACE_EVENT1("gpu", "EarlyOut_NativeWindowNotFound", "handle", handle);
return;
}
scoped_completion_runner.Release();
presenter->AsyncPresentAndAcknowledge(
params.size,
params.surface_handle,
base::Bind(&AcceleratedSurfaceBuffersSwappedCompleted,
host_id_,
params.route_id,
params.surface_id));
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped");
base::ScopedClosureRunner scoped_completion_runner(
base::Bind(&AcceleratedSurfaceBuffersSwappedCompleted,
host_id_, params.route_id, params.surface_id, params.surface_handle,
true, base::TimeTicks(), base::TimeDelta()));
gfx::PluginWindowHandle handle =
GpuSurfaceTracker::Get()->GetSurfaceWindowHandle(params.surface_id);
if (!handle) {
TRACE_EVENT1("gpu", "SurfaceIDNotFound_RoutingToUI",
"surface_id", params.surface_id);
#if defined(USE_AURA)
scoped_completion_runner.Release();
RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
#endif
return;
}
scoped_refptr<AcceleratedPresenter> presenter(
AcceleratedPresenter::GetForWindow(handle));
if (!presenter) {
TRACE_EVENT1("gpu", "EarlyOut_NativeWindowNotFound", "handle", handle);
return;
}
scoped_completion_runner.Release();
presenter->AsyncPresentAndAcknowledge(
params.size,
params.surface_handle,
base::Bind(&AcceleratedSurfaceBuffersSwappedCompleted,
host_id_,
params.route_id,
params.surface_id,
params.surface_handle));
}
| 171,356 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
{
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Start of interlace block */
int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
/* Offset to next interlace block */
int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
png_debug(1, "in png_do_write_interlace");
/* We don't have to do anything on the last pass (6) */
#ifdef PNG_USELESS_TESTS_SUPPORTED
if (row != NULL && row_info != NULL && pass < 6)
#else
if (pass < 6)
#endif
{
/* Each pixel depth is handled separately */
switch (row_info->pixel_depth)
{
case 1:
{
png_bytep sp;
png_bytep dp;
int shift;
int d;
int value;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
dp = row;
d = 0;
shift = 7;
for (i = png_pass_start[pass]; i < row_width;
i += png_pass_inc[pass])
{
sp = row + (png_size_t)(i >> 3);
value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
d |= (value << shift);
if (shift == 0)
{
shift = 7;
*dp++ = (png_byte)d;
d = 0;
}
else
shift--;
}
if (shift != 7)
*dp = (png_byte)d;
break;
}
case 2:
{
png_bytep sp;
png_bytep dp;
int shift;
int d;
int value;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
dp = row;
shift = 6;
d = 0;
for (i = png_pass_start[pass]; i < row_width;
i += png_pass_inc[pass])
{
sp = row + (png_size_t)(i >> 2);
value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
d |= (value << shift);
if (shift == 0)
{
shift = 6;
*dp++ = (png_byte)d;
d = 0;
}
else
shift -= 2;
}
if (shift != 6)
*dp = (png_byte)d;
break;
}
case 4:
{
png_bytep sp;
png_bytep dp;
int shift;
int d;
int value;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
dp = row;
shift = 4;
d = 0;
for (i = png_pass_start[pass]; i < row_width;
i += png_pass_inc[pass])
{
sp = row + (png_size_t)(i >> 1);
value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
d |= (value << shift);
if (shift == 0)
{
shift = 4;
*dp++ = (png_byte)d;
d = 0;
}
else
shift -= 4;
}
if (shift != 4)
*dp = (png_byte)d;
break;
}
default:
{
png_bytep sp;
png_bytep dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
png_size_t pixel_bytes;
/* Start at the beginning */
dp = row;
/* Find out how many bytes each pixel takes up */
pixel_bytes = (row_info->pixel_depth >> 3);
/* Loop through the row, only looking at the pixels that
matter */
for (i = png_pass_start[pass]; i < row_width;
i += png_pass_inc[pass])
{
/* Find out where the original pixel is */
sp = row + (png_size_t)i * pixel_bytes;
/* Move the pixel */
if (dp != sp)
png_memcpy(dp, sp, pixel_bytes);
/* Next pixel */
dp += pixel_bytes;
}
break;
}
}
/* Set new row width */
row_info->width = (row_info->width +
png_pass_inc[pass] - 1 -
png_pass_start[pass]) /
png_pass_inc[pass];
row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
row_info->width);
}
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
{
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
#ifndef PNG_USE_GLOBAL_ARRAYS
/* Start of interlace block */
int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
/* Offset to next interlace block */
int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
#endif
png_debug(1, "in png_do_write_interlace");
/* We don't have to do anything on the last pass (6) */
#ifdef PNG_USELESS_TESTS_SUPPORTED
if (row != NULL && row_info != NULL && pass < 6)
#else
if (pass < 6)
#endif
{
/* Each pixel depth is handled separately */
switch (row_info->pixel_depth)
{
case 1:
{
png_bytep sp;
png_bytep dp;
int shift;
int d;
int value;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
dp = row;
d = 0;
shift = 7;
for (i = png_pass_start[pass]; i < row_width;
i += png_pass_inc[pass])
{
sp = row + (png_size_t)(i >> 3);
value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
d |= (value << shift);
if (shift == 0)
{
shift = 7;
*dp++ = (png_byte)d;
d = 0;
}
else
shift--;
}
if (shift != 7)
*dp = (png_byte)d;
break;
}
case 2:
{
png_bytep sp;
png_bytep dp;
int shift;
int d;
int value;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
dp = row;
shift = 6;
d = 0;
for (i = png_pass_start[pass]; i < row_width;
i += png_pass_inc[pass])
{
sp = row + (png_size_t)(i >> 2);
value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
d |= (value << shift);
if (shift == 0)
{
shift = 6;
*dp++ = (png_byte)d;
d = 0;
}
else
shift -= 2;
}
if (shift != 6)
*dp = (png_byte)d;
break;
}
case 4:
{
png_bytep sp;
png_bytep dp;
int shift;
int d;
int value;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
dp = row;
shift = 4;
d = 0;
for (i = png_pass_start[pass]; i < row_width;
i += png_pass_inc[pass])
{
sp = row + (png_size_t)(i >> 1);
value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
d |= (value << shift);
if (shift == 0)
{
shift = 4;
*dp++ = (png_byte)d;
d = 0;
}
else
shift -= 4;
}
if (shift != 4)
*dp = (png_byte)d;
break;
}
default:
{
png_bytep sp;
png_bytep dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
png_size_t pixel_bytes;
/* Start at the beginning */
dp = row;
/* Find out how many bytes each pixel takes up */
pixel_bytes = (row_info->pixel_depth >> 3);
/* Loop through the row, only looking at the pixels that
matter */
for (i = png_pass_start[pass]; i < row_width;
i += png_pass_inc[pass])
{
/* Find out where the original pixel is */
sp = row + (png_size_t)i * pixel_bytes;
/* Move the pixel */
if (dp != sp)
png_memcpy(dp, sp, pixel_bytes);
/* Next pixel */
dp += pixel_bytes;
}
break;
}
}
/* Set new row width */
row_info->width = (row_info->width +
png_pass_inc[pass] - 1 -
png_pass_start[pass]) /
png_pass_inc[pass];
row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
row_info->width);
}
}
| 172,191 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 m_authenticate(struct Client* cptr, struct Client* sptr, int parc, char* parv[])
{
struct Client* acptr;
int first = 0;
char realhost[HOSTLEN + 3];
char *hoststr = (cli_sockhost(cptr) ? cli_sockhost(cptr) : cli_sock_ip(cptr));
if (!CapActive(cptr, CAP_SASL))
return 0;
if (parc < 2) /* have enough parameters? */
return need_more_params(cptr, "AUTHENTICATE");
if (strlen(parv[1]) > 400)
return send_reply(cptr, ERR_SASLTOOLONG);
if (IsSASLComplete(cptr))
return send_reply(cptr, ERR_SASLALREADY);
/* Look up the target server */
if (!(acptr = cli_saslagent(cptr))) {
if (strcmp(feature_str(FEAT_SASL_SERVER), "*"))
acptr = find_match_server((char *)feature_str(FEAT_SASL_SERVER));
else
acptr = NULL;
}
if (!acptr && strcmp(feature_str(FEAT_SASL_SERVER), "*"))
return send_reply(cptr, ERR_SASLFAIL, ": service unavailable");
/* If it's to us, do nothing; otherwise, forward the query */
if (acptr && IsMe(acptr))
return 0;
/* Generate an SASL session cookie if not already generated */
if (!cli_saslcookie(cptr)) {
do {
cli_saslcookie(cptr) = ircrandom() & 0x7fffffff;
} while (!cli_saslcookie(cptr));
first = 1;
}
if (strchr(hoststr, ':') != NULL)
ircd_snprintf(0, realhost, sizeof(realhost), "[%s]", hoststr);
else
ircd_strncpy(realhost, hoststr, sizeof(realhost));
if (acptr) {
if (first) {
if (!EmptyString(cli_sslclifp(cptr)))
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u S %s :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr),
parv[1], cli_sslclifp(cptr));
else
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u S :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
if (feature_bool(FEAT_SASL_SENDHOST))
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u H :%s@%s:%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), cli_username(cptr),
realhost, cli_sock_ip(cptr));
} else {
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u C :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
}
} else {
if (first) {
if (!EmptyString(cli_sslclifp(cptr)))
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u S %s :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr),
parv[1], cli_sslclifp(cptr));
else
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u S :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
if (feature_bool(FEAT_SASL_SENDHOST))
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u H :%s@%s:%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), cli_username(cptr),
realhost, cli_sock_ip(cptr));
} else {
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u C :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
}
}
if (!t_active(&cli_sasltimeout(cptr)))
timer_add(timer_init(&cli_sasltimeout(cptr)), sasl_timeout_callback, (void*) cptr,
TT_RELATIVE, feature_int(FEAT_SASL_TIMEOUT));
return 0;
}
Commit Message: Fix to prevent SASL security vulnerability
CWE ID: CWE-287 | int m_authenticate(struct Client* cptr, struct Client* sptr, int parc, char* parv[])
{
struct Client* acptr;
int first = 0;
char realhost[HOSTLEN + 3];
char *hoststr = (cli_sockhost(cptr) ? cli_sockhost(cptr) : cli_sock_ip(cptr));
if (!CapActive(cptr, CAP_SASL))
return 0;
if (parc < 2) /* have enough parameters? */
return need_more_params(cptr, "AUTHENTICATE");
if (strlen(parv[1]) > 400)
return send_reply(cptr, ERR_SASLTOOLONG);
if (IsSASLComplete(cptr))
return send_reply(cptr, ERR_SASLALREADY);
/* Look up the target server */
if (!(acptr = cli_saslagent(cptr))) {
if (strcmp(feature_str(FEAT_SASL_SERVER), "*"))
acptr = find_match_server((char *)feature_str(FEAT_SASL_SERVER));
else
acptr = NULL;
}
if (!acptr && strcmp(feature_str(FEAT_SASL_SERVER), "*"))
return send_reply(cptr, ERR_SASLFAIL, ": service unavailable");
/* If it's to us, do nothing; otherwise, forward the query */
if (acptr && IsMe(acptr))
return 0;
/* Generate an SASL session cookie if not already generated */
if (!cli_saslcookie(cptr)) {
do {
cli_saslcookie(cptr) = ircrandom() & 0x7fffffff;
} while (!cli_saslcookie(cptr));
first = 1;
}
if (strchr(hoststr, ':') != NULL)
ircd_snprintf(0, realhost, sizeof(realhost), "[%s]", hoststr);
else
ircd_strncpy(realhost, hoststr, sizeof(realhost));
if (acptr) {
if (first) {
if (*parv[1] == ':' || strchr(parv[1], ' '))
return exit_client(cptr, sptr, sptr, "Malformed AUTHENTICATE");
if (!EmptyString(cli_sslclifp(cptr)))
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u S %s :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr),
parv[1], cli_sslclifp(cptr));
else
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u S :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
if (feature_bool(FEAT_SASL_SENDHOST))
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u H :%s@%s:%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), cli_username(cptr),
realhost, cli_sock_ip(cptr));
} else {
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u C :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
}
} else {
if (first) {
if (*parv[1] == ':' || strchr(parv[1], ' '))
return exit_client(cptr, sptr, sptr, "Malformed AUTHENTICATE");
if (!EmptyString(cli_sslclifp(cptr)))
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u S %s :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr),
parv[1], cli_sslclifp(cptr));
else
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u S :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
if (feature_bool(FEAT_SASL_SENDHOST))
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u H :%s@%s:%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), cli_username(cptr),
realhost, cli_sock_ip(cptr));
} else {
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u C :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
}
}
if (!t_active(&cli_sasltimeout(cptr)))
timer_add(timer_init(&cli_sasltimeout(cptr)), sasl_timeout_callback, (void*) cptr,
TT_RELATIVE, feature_int(FEAT_SASL_TIMEOUT));
return 0;
}
| 168,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: static int gtco_probe(struct usb_interface *usbinterface,
const struct usb_device_id *id)
{
struct gtco *gtco;
struct input_dev *input_dev;
struct hid_descriptor *hid_desc;
char *report;
int result = 0, retry;
int error;
struct usb_endpoint_descriptor *endpoint;
/* Allocate memory for device structure */
gtco = kzalloc(sizeof(struct gtco), GFP_KERNEL);
input_dev = input_allocate_device();
if (!gtco || !input_dev) {
dev_err(&usbinterface->dev, "No more memory\n");
error = -ENOMEM;
goto err_free_devs;
}
/* Set pointer to the input device */
gtco->inputdevice = input_dev;
/* Save interface information */
gtco->usbdev = interface_to_usbdev(usbinterface);
gtco->intf = usbinterface;
/* Allocate some data for incoming reports */
gtco->buffer = usb_alloc_coherent(gtco->usbdev, REPORT_MAX_SIZE,
GFP_KERNEL, >co->buf_dma);
if (!gtco->buffer) {
dev_err(&usbinterface->dev, "No more memory for us buffers\n");
error = -ENOMEM;
goto err_free_devs;
}
/* Allocate URB for reports */
gtco->urbinfo = usb_alloc_urb(0, GFP_KERNEL);
if (!gtco->urbinfo) {
dev_err(&usbinterface->dev, "Failed to allocate URB\n");
error = -ENOMEM;
goto err_free_buf;
}
/*
* The endpoint is always altsetting 0, we know this since we know
* this device only has one interrupt endpoint
*/
endpoint = &usbinterface->altsetting[0].endpoint[0].desc;
/* Some debug */
dev_dbg(&usbinterface->dev, "gtco # interfaces: %d\n", usbinterface->num_altsetting);
dev_dbg(&usbinterface->dev, "num endpoints: %d\n", usbinterface->cur_altsetting->desc.bNumEndpoints);
dev_dbg(&usbinterface->dev, "interface class: %d\n", usbinterface->cur_altsetting->desc.bInterfaceClass);
dev_dbg(&usbinterface->dev, "endpoint: attribute:0x%x type:0x%x\n", endpoint->bmAttributes, endpoint->bDescriptorType);
if (usb_endpoint_xfer_int(endpoint))
dev_dbg(&usbinterface->dev, "endpoint: we have interrupt endpoint\n");
dev_dbg(&usbinterface->dev, "endpoint extra len:%d\n", usbinterface->altsetting[0].extralen);
/*
* Find the HID descriptor so we can find out the size of the
* HID report descriptor
*/
if (usb_get_extra_descriptor(usbinterface->cur_altsetting,
HID_DEVICE_TYPE, &hid_desc) != 0){
dev_err(&usbinterface->dev,
"Can't retrieve exta USB descriptor to get hid report descriptor length\n");
error = -EIO;
goto err_free_urb;
}
dev_dbg(&usbinterface->dev,
"Extra descriptor success: type:%d len:%d\n",
hid_desc->bDescriptorType, hid_desc->wDescriptorLength);
report = kzalloc(le16_to_cpu(hid_desc->wDescriptorLength), GFP_KERNEL);
if (!report) {
dev_err(&usbinterface->dev, "No more memory for report\n");
error = -ENOMEM;
goto err_free_urb;
}
/* Couple of tries to get reply */
for (retry = 0; retry < 3; retry++) {
result = usb_control_msg(gtco->usbdev,
usb_rcvctrlpipe(gtco->usbdev, 0),
USB_REQ_GET_DESCRIPTOR,
USB_RECIP_INTERFACE | USB_DIR_IN,
REPORT_DEVICE_TYPE << 8,
0, /* interface */
report,
le16_to_cpu(hid_desc->wDescriptorLength),
5000); /* 5 secs */
dev_dbg(&usbinterface->dev, "usb_control_msg result: %d\n", result);
if (result == le16_to_cpu(hid_desc->wDescriptorLength)) {
parse_hid_report_descriptor(gtco, report, result);
break;
}
}
kfree(report);
/* If we didn't get the report, fail */
if (result != le16_to_cpu(hid_desc->wDescriptorLength)) {
dev_err(&usbinterface->dev,
"Failed to get HID Report Descriptor of size: %d\n",
hid_desc->wDescriptorLength);
error = -EIO;
goto err_free_urb;
}
/* Create a device file node */
usb_make_path(gtco->usbdev, gtco->usbpath, sizeof(gtco->usbpath));
strlcat(gtco->usbpath, "/input0", sizeof(gtco->usbpath));
/* Set Input device functions */
input_dev->open = gtco_input_open;
input_dev->close = gtco_input_close;
/* Set input device information */
input_dev->name = "GTCO_CalComp";
input_dev->phys = gtco->usbpath;
input_set_drvdata(input_dev, gtco);
/* Now set up all the input device capabilities */
gtco_setup_caps(input_dev);
/* Set input device required ID information */
usb_to_input_id(gtco->usbdev, &input_dev->id);
input_dev->dev.parent = &usbinterface->dev;
/* Setup the URB, it will be posted later on open of input device */
endpoint = &usbinterface->altsetting[0].endpoint[0].desc;
usb_fill_int_urb(gtco->urbinfo,
gtco->usbdev,
usb_rcvintpipe(gtco->usbdev,
endpoint->bEndpointAddress),
gtco->buffer,
REPORT_MAX_SIZE,
gtco_urb_callback,
gtco,
endpoint->bInterval);
gtco->urbinfo->transfer_dma = gtco->buf_dma;
gtco->urbinfo->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
/* Save gtco pointer in USB interface gtco */
usb_set_intfdata(usbinterface, gtco);
/* All done, now register the input device */
error = input_register_device(input_dev);
if (error)
goto err_free_urb;
return 0;
err_free_urb:
usb_free_urb(gtco->urbinfo);
err_free_buf:
usb_free_coherent(gtco->usbdev, REPORT_MAX_SIZE,
gtco->buffer, gtco->buf_dma);
err_free_devs:
input_free_device(input_dev);
kfree(gtco);
return error;
}
Commit Message: Input: gtco - fix crash on detecting device without endpoints
The gtco driver expects at least one valid endpoint. If given malicious
descriptors that specify 0 for the number of endpoints, it will crash in
the probe function. Ensure there is at least one endpoint on the interface
before using it.
Also let's fix a minor coding style issue.
The full correct report of this issue can be found in the public
Red Hat Bugzilla:
https://bugzilla.redhat.com/show_bug.cgi?id=1283385
Reported-by: Ralf Spenneberg <[email protected]>
Signed-off-by: Vladis Dronov <[email protected]>
Cc: [email protected]
Signed-off-by: Dmitry Torokhov <[email protected]>
CWE ID: | static int gtco_probe(struct usb_interface *usbinterface,
const struct usb_device_id *id)
{
struct gtco *gtco;
struct input_dev *input_dev;
struct hid_descriptor *hid_desc;
char *report;
int result = 0, retry;
int error;
struct usb_endpoint_descriptor *endpoint;
/* Allocate memory for device structure */
gtco = kzalloc(sizeof(struct gtco), GFP_KERNEL);
input_dev = input_allocate_device();
if (!gtco || !input_dev) {
dev_err(&usbinterface->dev, "No more memory\n");
error = -ENOMEM;
goto err_free_devs;
}
/* Set pointer to the input device */
gtco->inputdevice = input_dev;
/* Save interface information */
gtco->usbdev = interface_to_usbdev(usbinterface);
gtco->intf = usbinterface;
/* Allocate some data for incoming reports */
gtco->buffer = usb_alloc_coherent(gtco->usbdev, REPORT_MAX_SIZE,
GFP_KERNEL, >co->buf_dma);
if (!gtco->buffer) {
dev_err(&usbinterface->dev, "No more memory for us buffers\n");
error = -ENOMEM;
goto err_free_devs;
}
/* Allocate URB for reports */
gtco->urbinfo = usb_alloc_urb(0, GFP_KERNEL);
if (!gtco->urbinfo) {
dev_err(&usbinterface->dev, "Failed to allocate URB\n");
error = -ENOMEM;
goto err_free_buf;
}
/* Sanity check that a device has an endpoint */
if (usbinterface->altsetting[0].desc.bNumEndpoints < 1) {
dev_err(&usbinterface->dev,
"Invalid number of endpoints\n");
error = -EINVAL;
goto err_free_urb;
}
/*
* The endpoint is always altsetting 0, we know this since we know
* this device only has one interrupt endpoint
*/
endpoint = &usbinterface->altsetting[0].endpoint[0].desc;
/* Some debug */
dev_dbg(&usbinterface->dev, "gtco # interfaces: %d\n", usbinterface->num_altsetting);
dev_dbg(&usbinterface->dev, "num endpoints: %d\n", usbinterface->cur_altsetting->desc.bNumEndpoints);
dev_dbg(&usbinterface->dev, "interface class: %d\n", usbinterface->cur_altsetting->desc.bInterfaceClass);
dev_dbg(&usbinterface->dev, "endpoint: attribute:0x%x type:0x%x\n", endpoint->bmAttributes, endpoint->bDescriptorType);
if (usb_endpoint_xfer_int(endpoint))
dev_dbg(&usbinterface->dev, "endpoint: we have interrupt endpoint\n");
dev_dbg(&usbinterface->dev, "endpoint extra len:%d\n", usbinterface->altsetting[0].extralen);
/*
* Find the HID descriptor so we can find out the size of the
* HID report descriptor
*/
if (usb_get_extra_descriptor(usbinterface->cur_altsetting,
HID_DEVICE_TYPE, &hid_desc) != 0) {
dev_err(&usbinterface->dev,
"Can't retrieve exta USB descriptor to get hid report descriptor length\n");
error = -EIO;
goto err_free_urb;
}
dev_dbg(&usbinterface->dev,
"Extra descriptor success: type:%d len:%d\n",
hid_desc->bDescriptorType, hid_desc->wDescriptorLength);
report = kzalloc(le16_to_cpu(hid_desc->wDescriptorLength), GFP_KERNEL);
if (!report) {
dev_err(&usbinterface->dev, "No more memory for report\n");
error = -ENOMEM;
goto err_free_urb;
}
/* Couple of tries to get reply */
for (retry = 0; retry < 3; retry++) {
result = usb_control_msg(gtco->usbdev,
usb_rcvctrlpipe(gtco->usbdev, 0),
USB_REQ_GET_DESCRIPTOR,
USB_RECIP_INTERFACE | USB_DIR_IN,
REPORT_DEVICE_TYPE << 8,
0, /* interface */
report,
le16_to_cpu(hid_desc->wDescriptorLength),
5000); /* 5 secs */
dev_dbg(&usbinterface->dev, "usb_control_msg result: %d\n", result);
if (result == le16_to_cpu(hid_desc->wDescriptorLength)) {
parse_hid_report_descriptor(gtco, report, result);
break;
}
}
kfree(report);
/* If we didn't get the report, fail */
if (result != le16_to_cpu(hid_desc->wDescriptorLength)) {
dev_err(&usbinterface->dev,
"Failed to get HID Report Descriptor of size: %d\n",
hid_desc->wDescriptorLength);
error = -EIO;
goto err_free_urb;
}
/* Create a device file node */
usb_make_path(gtco->usbdev, gtco->usbpath, sizeof(gtco->usbpath));
strlcat(gtco->usbpath, "/input0", sizeof(gtco->usbpath));
/* Set Input device functions */
input_dev->open = gtco_input_open;
input_dev->close = gtco_input_close;
/* Set input device information */
input_dev->name = "GTCO_CalComp";
input_dev->phys = gtco->usbpath;
input_set_drvdata(input_dev, gtco);
/* Now set up all the input device capabilities */
gtco_setup_caps(input_dev);
/* Set input device required ID information */
usb_to_input_id(gtco->usbdev, &input_dev->id);
input_dev->dev.parent = &usbinterface->dev;
/* Setup the URB, it will be posted later on open of input device */
endpoint = &usbinterface->altsetting[0].endpoint[0].desc;
usb_fill_int_urb(gtco->urbinfo,
gtco->usbdev,
usb_rcvintpipe(gtco->usbdev,
endpoint->bEndpointAddress),
gtco->buffer,
REPORT_MAX_SIZE,
gtco_urb_callback,
gtco,
endpoint->bInterval);
gtco->urbinfo->transfer_dma = gtco->buf_dma;
gtco->urbinfo->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
/* Save gtco pointer in USB interface gtco */
usb_set_intfdata(usbinterface, gtco);
/* All done, now register the input device */
error = input_register_device(input_dev);
if (error)
goto err_free_urb;
return 0;
err_free_urb:
usb_free_urb(gtco->urbinfo);
err_free_buf:
usb_free_coherent(gtco->usbdev, REPORT_MAX_SIZE,
gtco->buffer, gtco->buf_dma);
err_free_devs:
input_free_device(input_dev);
kfree(gtco);
return error;
}
| 167,431 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BGD_DECLARE(void) gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality)
{
uint8_t *argb;
int x, y;
uint8_t *p;
uint8_t *out;
size_t out_size;
if (im == NULL) {
return;
}
if (!gdImageTrueColor(im)) {
gd_error("Paletter image not supported by webp");
return;
}
if (quality == -1) {
quality = 80;
}
argb = (uint8_t *)gdMalloc(gdImageSX(im) * 4 * gdImageSY(im));
if (!argb) {
return;
}
p = argb;
for (y = 0; y < gdImageSY(im); y++) {
for (x = 0; x < gdImageSX(im); x++) {
register int c;
register char a;
c = im->tpixels[y][x];
a = gdTrueColorGetAlpha(c);
if (a == 127) {
a = 0;
} else {
a = 255 - ((a << 1) + (a >> 6));
}
*(p++) = gdTrueColorGetRed(c);
*(p++) = gdTrueColorGetGreen(c);
*(p++) = gdTrueColorGetBlue(c);
*(p++) = a;
}
}
out_size = WebPEncodeRGBA(argb, gdImageSX(im), gdImageSY(im), gdImageSX(im) * 4, quality, &out);
if (out_size == 0) {
gd_error("gd-webp encoding failed");
goto freeargb;
}
gdPutBuf(out, out_size, outfile);
free(out);
freeargb:
gdFree(argb);
}
Commit Message: Merge branch 'pull-request/296'
CWE ID: CWE-190 | BGD_DECLARE(void) gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality)
{
uint8_t *argb;
int x, y;
uint8_t *p;
uint8_t *out;
size_t out_size;
if (im == NULL) {
return;
}
if (!gdImageTrueColor(im)) {
gd_error("Paletter image not supported by webp");
return;
}
if (quality == -1) {
quality = 80;
}
if (overflow2(gdImageSX(im), 4)) {
return;
}
if (overflow2(gdImageSX(im) * 4, gdImageSY(im))) {
return;
}
argb = (uint8_t *)gdMalloc(gdImageSX(im) * 4 * gdImageSY(im));
if (!argb) {
return;
}
p = argb;
for (y = 0; y < gdImageSY(im); y++) {
for (x = 0; x < gdImageSX(im); x++) {
register int c;
register char a;
c = im->tpixels[y][x];
a = gdTrueColorGetAlpha(c);
if (a == 127) {
a = 0;
} else {
a = 255 - ((a << 1) + (a >> 6));
}
*(p++) = gdTrueColorGetRed(c);
*(p++) = gdTrueColorGetGreen(c);
*(p++) = gdTrueColorGetBlue(c);
*(p++) = a;
}
}
out_size = WebPEncodeRGBA(argb, gdImageSX(im), gdImageSY(im), gdImageSX(im) * 4, quality, &out);
if (out_size == 0) {
gd_error("gd-webp encoding failed");
goto freeargb;
}
gdPutBuf(out, out_size, outfile);
free(out);
freeargb:
gdFree(argb);
}
| 166,927 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ExtensionNavigationThrottle::WillStartOrRedirectRequest() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::WebContents* web_contents = navigation_handle()->GetWebContents();
ExtensionRegistry* registry =
ExtensionRegistry::Get(web_contents->GetBrowserContext());
const GURL& url = navigation_handle()->GetURL();
bool url_has_extension_scheme = url.SchemeIs(kExtensionScheme);
url::Origin target_origin = url::Origin::Create(url);
const Extension* target_extension = nullptr;
if (url_has_extension_scheme) {
target_extension =
registry->enabled_extensions().GetExtensionOrAppByURL(url);
} else if (target_origin.scheme() == kExtensionScheme) {
DCHECK(url.SchemeIsFileSystem() || url.SchemeIsBlob());
target_extension =
registry->enabled_extensions().GetByID(target_origin.host());
} else {
return content::NavigationThrottle::PROCEED;
}
if (!target_extension) {
return content::NavigationThrottle::BLOCK_REQUEST;
}
if (target_extension->is_hosted_app()) {
base::StringPiece resource_root_relative_path =
url.path_piece().empty() ? base::StringPiece()
: url.path_piece().substr(1);
if (!IconsInfo::GetIcons(target_extension)
.ContainsPath(resource_root_relative_path)) {
return content::NavigationThrottle::BLOCK_REQUEST;
}
}
if (navigation_handle()->IsInMainFrame()) {
bool current_frame_is_extension_process =
!!registry->enabled_extensions().GetExtensionOrAppByURL(
navigation_handle()->GetStartingSiteInstance()->GetSiteURL());
if (!url_has_extension_scheme && !current_frame_is_extension_process) {
if (target_origin.scheme() == kExtensionScheme &&
navigation_handle()->GetSuggestedFilename().has_value()) {
return content::NavigationThrottle::PROCEED;
}
bool has_webview_permission =
target_extension->permissions_data()->HasAPIPermission(
APIPermission::kWebView);
if (!has_webview_permission)
return content::NavigationThrottle::CANCEL;
}
guest_view::GuestViewBase* guest =
guest_view::GuestViewBase::FromWebContents(web_contents);
if (url_has_extension_scheme && guest) {
const std::string& owner_extension_id = guest->owner_host();
const Extension* owner_extension =
registry->enabled_extensions().GetByID(owner_extension_id);
std::string partition_domain;
std::string partition_id;
bool in_memory = false;
bool is_guest = WebViewGuest::GetGuestPartitionConfigForSite(
navigation_handle()->GetStartingSiteInstance()->GetSiteURL(),
&partition_domain, &partition_id, &in_memory);
bool allowed = true;
url_request_util::AllowCrossRendererResourceLoadHelper(
is_guest, target_extension, owner_extension, partition_id, url.path(),
navigation_handle()->GetPageTransition(), &allowed);
if (!allowed)
return content::NavigationThrottle::BLOCK_REQUEST;
}
return content::NavigationThrottle::PROCEED;
}
content::RenderFrameHost* parent = navigation_handle()->GetParentFrame();
bool external_ancestor = false;
for (auto* ancestor = parent; ancestor; ancestor = ancestor->GetParent()) {
if (ancestor->GetLastCommittedOrigin() == target_origin)
continue;
if (url::Origin::Create(ancestor->GetLastCommittedURL()) == target_origin)
continue;
if (ancestor->GetLastCommittedURL().SchemeIs(
content::kChromeDevToolsScheme))
continue;
external_ancestor = true;
break;
}
if (external_ancestor) {
if (!url_has_extension_scheme)
return content::NavigationThrottle::CANCEL;
if (!WebAccessibleResourcesInfo::IsResourceWebAccessible(target_extension,
url.path()))
return content::NavigationThrottle::BLOCK_REQUEST;
if (target_extension->is_platform_app())
return content::NavigationThrottle::CANCEL;
const Extension* parent_extension =
registry->enabled_extensions().GetExtensionOrAppByURL(
parent->GetSiteInstance()->GetSiteURL());
if (parent_extension && parent_extension->is_platform_app())
return content::NavigationThrottle::BLOCK_REQUEST;
}
return content::NavigationThrottle::PROCEED;
}
Commit Message: Apply ExtensionNavigationThrottle filesystem/blob checks to all frames.
BUG=836858
Change-Id: I34333a72501129fd40b5a9aa6378c9f35f1e7fc2
Reviewed-on: https://chromium-review.googlesource.com/1028511
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Alex Moshchuk <[email protected]>
Reviewed-by: Nick Carter <[email protected]>
Commit-Queue: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#553867}
CWE ID: CWE-20 | ExtensionNavigationThrottle::WillStartOrRedirectRequest() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::WebContents* web_contents = navigation_handle()->GetWebContents();
ExtensionRegistry* registry =
ExtensionRegistry::Get(web_contents->GetBrowserContext());
const GURL& url = navigation_handle()->GetURL();
bool url_has_extension_scheme = url.SchemeIs(kExtensionScheme);
url::Origin target_origin = url::Origin::Create(url);
const Extension* target_extension = nullptr;
if (url_has_extension_scheme) {
target_extension =
registry->enabled_extensions().GetExtensionOrAppByURL(url);
} else if (target_origin.scheme() == kExtensionScheme) {
DCHECK(url.SchemeIsFileSystem() || url.SchemeIsBlob());
target_extension =
registry->enabled_extensions().GetByID(target_origin.host());
} else {
return content::NavigationThrottle::PROCEED;
}
if (!target_extension) {
return content::NavigationThrottle::BLOCK_REQUEST;
}
if (target_extension->is_hosted_app()) {
base::StringPiece resource_root_relative_path =
url.path_piece().empty() ? base::StringPiece()
: url.path_piece().substr(1);
if (!IconsInfo::GetIcons(target_extension)
.ContainsPath(resource_root_relative_path)) {
return content::NavigationThrottle::BLOCK_REQUEST;
}
}
// Block all navigations to blob: or filesystem: URLs with extension
// origin from non-extension processes. See https://crbug.com/645028 and
// https://crbug.com/836858.
bool current_frame_is_extension_process =
!!registry->enabled_extensions().GetExtensionOrAppByURL(
navigation_handle()->GetStartingSiteInstance()->GetSiteURL());
if (!url_has_extension_scheme && !current_frame_is_extension_process) {
// Relax this restriction for navigations that will result in downloads.
// See https://crbug.com/714373.
if (target_origin.scheme() == kExtensionScheme &&
navigation_handle()->GetSuggestedFilename().has_value()) {
return content::NavigationThrottle::PROCEED;
}
// Relax this restriction for apps that use <webview>. See
// https://crbug.com/652077.
bool has_webview_permission =
target_extension->permissions_data()->HasAPIPermission(
APIPermission::kWebView);
if (!has_webview_permission)
return content::NavigationThrottle::CANCEL;
}
if (navigation_handle()->IsInMainFrame()) {
guest_view::GuestViewBase* guest =
guest_view::GuestViewBase::FromWebContents(web_contents);
if (url_has_extension_scheme && guest) {
const std::string& owner_extension_id = guest->owner_host();
const Extension* owner_extension =
registry->enabled_extensions().GetByID(owner_extension_id);
std::string partition_domain;
std::string partition_id;
bool in_memory = false;
bool is_guest = WebViewGuest::GetGuestPartitionConfigForSite(
navigation_handle()->GetStartingSiteInstance()->GetSiteURL(),
&partition_domain, &partition_id, &in_memory);
bool allowed = true;
url_request_util::AllowCrossRendererResourceLoadHelper(
is_guest, target_extension, owner_extension, partition_id, url.path(),
navigation_handle()->GetPageTransition(), &allowed);
if (!allowed)
return content::NavigationThrottle::BLOCK_REQUEST;
}
return content::NavigationThrottle::PROCEED;
}
content::RenderFrameHost* parent = navigation_handle()->GetParentFrame();
bool external_ancestor = false;
for (auto* ancestor = parent; ancestor; ancestor = ancestor->GetParent()) {
if (ancestor->GetLastCommittedOrigin() == target_origin)
continue;
if (url::Origin::Create(ancestor->GetLastCommittedURL()) == target_origin)
continue;
if (ancestor->GetLastCommittedURL().SchemeIs(
content::kChromeDevToolsScheme))
continue;
external_ancestor = true;
break;
}
if (external_ancestor) {
if (!url_has_extension_scheme)
return content::NavigationThrottle::CANCEL;
if (!WebAccessibleResourcesInfo::IsResourceWebAccessible(target_extension,
url.path()))
return content::NavigationThrottle::BLOCK_REQUEST;
if (target_extension->is_platform_app())
return content::NavigationThrottle::CANCEL;
const Extension* parent_extension =
registry->enabled_extensions().GetExtensionOrAppByURL(
parent->GetSiteInstance()->GetSiteURL());
if (parent_extension && parent_extension->is_platform_app())
return content::NavigationThrottle::BLOCK_REQUEST;
}
return content::NavigationThrottle::PROCEED;
}
| 173,256 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: psf_asciiheader_printf (SF_PRIVATE *psf, const char *format, ...)
{ va_list argptr ;
int maxlen ;
char *start ;
maxlen = strlen ((char*) psf->header) ;
start = ((char*) psf->header) + maxlen ;
maxlen = sizeof (psf->header) - maxlen ;
va_start (argptr, format) ;
vsnprintf (start, maxlen, format, argptr) ;
va_end (argptr) ;
/* Make sure the string is properly terminated. */
start [maxlen - 1] = 0 ;
psf->headindex = strlen ((char*) psf->header) ;
return ;
} /* psf_asciiheader_printf */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119 | psf_asciiheader_printf (SF_PRIVATE *psf, const char *format, ...)
{ va_list argptr ;
int maxlen ;
char *start ;
maxlen = strlen ((char*) psf->header.ptr) ;
start = ((char*) psf->header.ptr) + maxlen ;
maxlen = psf->header.len - maxlen ;
va_start (argptr, format) ;
vsnprintf (start, maxlen, format, argptr) ;
va_end (argptr) ;
/* Make sure the string is properly terminated. */
start [maxlen - 1] = 0 ;
psf->header.indx = strlen ((char*) psf->header.ptr) ;
return ;
} /* psf_asciiheader_printf */
| 170,063 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: error::Error GLES2DecoderImpl::HandleGetMultipleIntegervCHROMIUM(
uint32 immediate_data_size, const gles2::GetMultipleIntegervCHROMIUM& c) {
GLuint count = c.count;
uint32 pnames_size;
if (!SafeMultiplyUint32(count, sizeof(GLenum), &pnames_size)) {
return error::kOutOfBounds;
}
const GLenum* pnames = GetSharedMemoryAs<const GLenum*>(
c.pnames_shm_id, c.pnames_shm_offset, pnames_size);
if (pnames == NULL) {
return error::kOutOfBounds;
}
scoped_array<GLenum> enums(new GLenum[count]);
memcpy(enums.get(), pnames, pnames_size);
uint32 num_results = 0;
for (GLuint ii = 0; ii < count; ++ii) {
uint32 num = util_.GLGetNumValuesReturned(enums[ii]);
if (num == 0) {
SetGLErrorInvalidEnum("glGetMulitpleCHROMIUM", enums[ii], "pname");
return error::kNoError;
}
DCHECK_LE(num, 4u);
if (!SafeAdd(num_results, num, &num_results)) {
return error::kOutOfBounds;
}
}
uint32 result_size = 0;
if (!SafeMultiplyUint32(num_results, sizeof(GLint), &result_size)) {
return error::kOutOfBounds;
}
if (result_size != static_cast<uint32>(c.size)) {
SetGLError(GL_INVALID_VALUE,
"glGetMulitpleCHROMIUM", "bad size GL_INVALID_VALUE");
return error::kNoError;
}
GLint* results = GetSharedMemoryAs<GLint*>(
c.results_shm_id, c.results_shm_offset, result_size);
if (results == NULL) {
return error::kOutOfBounds;
}
for (uint32 ii = 0; ii < num_results; ++ii) {
if (results[ii]) {
return error::kInvalidArguments;
}
}
GLint* start = results;
for (GLuint ii = 0; ii < count; ++ii) {
GLsizei num_written = 0;
if (!GetHelper(enums[ii], results, &num_written)) {
glGetIntegerv(enums[ii], results);
}
results += num_written;
}
if (static_cast<uint32>(results - start) != num_results) {
return error::kOutOfBounds;
}
return error::kNoError;
}
Commit Message: Fix SafeAdd and SafeMultiply
BUG=145648,145544
Review URL: https://chromiumcodereview.appspot.com/10916165
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | error::Error GLES2DecoderImpl::HandleGetMultipleIntegervCHROMIUM(
uint32 immediate_data_size, const gles2::GetMultipleIntegervCHROMIUM& c) {
GLuint count = c.count;
uint32 pnames_size;
if (!SafeMultiplyUint32(count, sizeof(GLenum), &pnames_size)) {
return error::kOutOfBounds;
}
const GLenum* pnames = GetSharedMemoryAs<const GLenum*>(
c.pnames_shm_id, c.pnames_shm_offset, pnames_size);
if (pnames == NULL) {
return error::kOutOfBounds;
}
scoped_array<GLenum> enums(new GLenum[count]);
memcpy(enums.get(), pnames, pnames_size);
uint32 num_results = 0;
for (GLuint ii = 0; ii < count; ++ii) {
uint32 num = util_.GLGetNumValuesReturned(enums[ii]);
if (num == 0) {
SetGLErrorInvalidEnum("glGetMulitpleCHROMIUM", enums[ii], "pname");
return error::kNoError;
}
DCHECK_LE(num, 4u);
if (!SafeAddUint32(num_results, num, &num_results)) {
return error::kOutOfBounds;
}
}
uint32 result_size = 0;
if (!SafeMultiplyUint32(num_results, sizeof(GLint), &result_size)) {
return error::kOutOfBounds;
}
if (result_size != static_cast<uint32>(c.size)) {
SetGLError(GL_INVALID_VALUE,
"glGetMulitpleCHROMIUM", "bad size GL_INVALID_VALUE");
return error::kNoError;
}
GLint* results = GetSharedMemoryAs<GLint*>(
c.results_shm_id, c.results_shm_offset, result_size);
if (results == NULL) {
return error::kOutOfBounds;
}
for (uint32 ii = 0; ii < num_results; ++ii) {
if (results[ii]) {
return error::kInvalidArguments;
}
}
GLint* start = results;
for (GLuint ii = 0; ii < count; ++ii) {
GLsizei num_written = 0;
if (!GetHelper(enums[ii], results, &num_written)) {
glGetIntegerv(enums[ii], results);
}
results += num_written;
}
if (static_cast<uint32>(results - start) != num_results) {
return error::kOutOfBounds;
}
return error::kNoError;
}
| 170,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: static void get_nb10(ut8* dbg_data, SCV_NB10_HEADER* res) {
const int nb10sz = 16;
memcpy (res, dbg_data, nb10sz);
res->file_name = (ut8*) strdup ((const char*) dbg_data + nb10sz);
}
Commit Message: Fix crash in pe
CWE ID: CWE-125 | static void get_nb10(ut8* dbg_data, SCV_NB10_HEADER* res) {
const int nb10sz = 16;
// memcpy (res, dbg_data, nb10sz);
// res->file_name = (ut8*) strdup ((const char*) dbg_data + nb10sz);
}
| 169,229 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ieee802_11_print(netdissect_options *ndo,
const u_char *p, u_int length, u_int orig_caplen, int pad,
u_int fcslen)
{
uint16_t fc;
u_int caplen, hdrlen, meshdrlen;
struct lladdr_info src, dst;
int llc_hdrlen;
caplen = orig_caplen;
/* Remove FCS, if present */
if (length < fcslen) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
length -= fcslen;
if (caplen > length) {
/* Amount of FCS in actual packet data, if any */
fcslen = caplen - length;
caplen -= fcslen;
ndo->ndo_snapend -= fcslen;
}
if (caplen < IEEE802_11_FC_LEN) {
ND_PRINT((ndo, "%s", tstr));
return orig_caplen;
}
fc = EXTRACT_LE_16BITS(p);
hdrlen = extract_header_length(ndo, fc);
if (hdrlen == 0) {
/* Unknown frame type or control frame subtype; quit. */
return (0);
}
if (pad)
hdrlen = roundup2(hdrlen, 4);
if (ndo->ndo_Hflag && FC_TYPE(fc) == T_DATA &&
DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) {
meshdrlen = extract_mesh_header_length(p+hdrlen);
hdrlen += meshdrlen;
} else
meshdrlen = 0;
if (caplen < hdrlen) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
if (ndo->ndo_eflag)
ieee_802_11_hdr_print(ndo, fc, p, hdrlen, meshdrlen);
/*
* Go past the 802.11 header.
*/
length -= hdrlen;
caplen -= hdrlen;
p += hdrlen;
src.addr_string = etheraddr_string;
dst.addr_string = etheraddr_string;
switch (FC_TYPE(fc)) {
case T_MGMT:
get_mgmt_src_dst_mac(p - hdrlen, &src.addr, &dst.addr);
if (!mgmt_body_print(ndo, fc, src.addr, p, length)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
break;
case T_CTRL:
if (!ctrl_body_print(ndo, fc, p - hdrlen)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
break;
case T_DATA:
if (DATA_FRAME_IS_NULL(FC_SUBTYPE(fc)))
return hdrlen; /* no-data frame */
/* There may be a problem w/ AP not having this bit set */
if (FC_PROTECTED(fc)) {
ND_PRINT((ndo, "Data"));
if (!wep_print(ndo, p)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
} else {
get_data_src_dst_mac(fc, p - hdrlen, &src.addr, &dst.addr);
llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst);
if (llc_hdrlen < 0) {
/*
* Some kinds of LLC packet we cannot
* handle intelligently
*/
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
llc_hdrlen = -llc_hdrlen;
}
hdrlen += llc_hdrlen;
}
break;
default:
/* We shouldn't get here - we should already have quit */
break;
}
return hdrlen;
}
Commit Message: (for 4.9.3) CVE-2018-16227/IEEE 802.11: add a missing bounds check
ieee802_11_print() tried to access the Mesh Flags subfield of the Mesh
Control field to find the size of the latter and increment the expected
802.11 header length before checking it is fully present in the input
buffer. Add an intermediate bounds check to make it safe.
This fixes a buffer over-read discovered by Ryan Ackroyd.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | ieee802_11_print(netdissect_options *ndo,
const u_char *p, u_int length, u_int orig_caplen, int pad,
u_int fcslen)
{
uint16_t fc;
u_int caplen, hdrlen, meshdrlen;
struct lladdr_info src, dst;
int llc_hdrlen;
caplen = orig_caplen;
/* Remove FCS, if present */
if (length < fcslen) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
length -= fcslen;
if (caplen > length) {
/* Amount of FCS in actual packet data, if any */
fcslen = caplen - length;
caplen -= fcslen;
ndo->ndo_snapend -= fcslen;
}
if (caplen < IEEE802_11_FC_LEN) {
ND_PRINT((ndo, "%s", tstr));
return orig_caplen;
}
fc = EXTRACT_LE_16BITS(p);
hdrlen = extract_header_length(ndo, fc);
if (hdrlen == 0) {
/* Unknown frame type or control frame subtype; quit. */
return (0);
}
if (pad)
hdrlen = roundup2(hdrlen, 4);
if (ndo->ndo_Hflag && FC_TYPE(fc) == T_DATA &&
DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) {
if (caplen < hdrlen + 1) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
meshdrlen = extract_mesh_header_length(p+hdrlen);
hdrlen += meshdrlen;
} else
meshdrlen = 0;
if (caplen < hdrlen) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
if (ndo->ndo_eflag)
ieee_802_11_hdr_print(ndo, fc, p, hdrlen, meshdrlen);
/*
* Go past the 802.11 header.
*/
length -= hdrlen;
caplen -= hdrlen;
p += hdrlen;
src.addr_string = etheraddr_string;
dst.addr_string = etheraddr_string;
switch (FC_TYPE(fc)) {
case T_MGMT:
get_mgmt_src_dst_mac(p - hdrlen, &src.addr, &dst.addr);
if (!mgmt_body_print(ndo, fc, src.addr, p, length)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
break;
case T_CTRL:
if (!ctrl_body_print(ndo, fc, p - hdrlen)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
break;
case T_DATA:
if (DATA_FRAME_IS_NULL(FC_SUBTYPE(fc)))
return hdrlen; /* no-data frame */
/* There may be a problem w/ AP not having this bit set */
if (FC_PROTECTED(fc)) {
ND_PRINT((ndo, "Data"));
if (!wep_print(ndo, p)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
} else {
get_data_src_dst_mac(fc, p - hdrlen, &src.addr, &dst.addr);
llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst);
if (llc_hdrlen < 0) {
/*
* Some kinds of LLC packet we cannot
* handle intelligently
*/
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
llc_hdrlen = -llc_hdrlen;
}
hdrlen += llc_hdrlen;
}
break;
default:
/* We shouldn't get here - we should already have quit */
break;
}
return hdrlen;
}
| 169,821 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 rng_egd_request_entropy(RngBackend *b, size_t size,
EntropyReceiveFunc *receive_entropy,
void *opaque)
{
RngEgd *s = RNG_EGD(b);
RngRequest *req;
req = g_malloc(sizeof(*req));
req->offset = 0;
req->size = size;
req->receive_entropy = receive_entropy;
req->opaque = opaque;
req->data = g_malloc(req->size);
while (size > 0) {
uint8_t header[2];
req = g_malloc(sizeof(*req));
req->offset = 0;
req->size = size;
req->receive_entropy = receive_entropy;
req->opaque = opaque;
req->data = g_malloc(req->size);
size -= len;
}
s->parent.requests = g_slist_append(s->parent.requests, req);
}
Commit Message:
CWE ID: CWE-119 | static void rng_egd_request_entropy(RngBackend *b, size_t size,
static void rng_egd_request_entropy(RngBackend *b, RngRequest *req)
{
RngEgd *s = RNG_EGD(b);
size_t size = req->size;
while (size > 0) {
uint8_t header[2];
req = g_malloc(sizeof(*req));
req->offset = 0;
req->size = size;
req->receive_entropy = receive_entropy;
req->opaque = opaque;
req->data = g_malloc(req->size);
size -= len;
}
}
| 165,180 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RenderProcessHostImpl::OnCompositorSurfaceBuffersSwappedNoHost(
int32 surface_id,
uint64 surface_handle,
int32 route_id,
const gfx::Size& size,
int32 gpu_process_host_id) {
TRACE_EVENT0("renderer_host",
"RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwappedNoHost");
RenderWidgetHostImpl::AcknowledgeBufferPresent(route_id,
gpu_process_host_id,
false,
0);
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void RenderProcessHostImpl::OnCompositorSurfaceBuffersSwappedNoHost(
int32 surface_id,
uint64 surface_handle,
int32 route_id,
const gfx::Size& size,
int32 gpu_process_host_id) {
TRACE_EVENT0("renderer_host",
"RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwappedNoHost");
RenderWidgetHostImpl::AcknowledgeBufferPresent(route_id,
gpu_process_host_id,
surface_handle,
0);
}
| 171,365 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: pimv1_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
register const u_char *ep;
register u_char type;
ep = (const u_char *)ndo->ndo_snapend;
if (bp >= ep)
return;
ND_TCHECK(bp[1]);
type = bp[1];
ND_PRINT((ndo, " %s", tok2str(pimv1_type_str, "[type %u]", type)));
switch (type) {
case PIMV1_TYPE_QUERY:
if (ND_TTEST(bp[8])) {
switch (bp[8] >> 4) {
case 0:
ND_PRINT((ndo, " Dense-mode"));
break;
case 1:
ND_PRINT((ndo, " Sparse-mode"));
break;
case 2:
ND_PRINT((ndo, " Sparse-Dense-mode"));
break;
default:
ND_PRINT((ndo, " mode-%d", bp[8] >> 4));
break;
}
}
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[10],2);
ND_PRINT((ndo, " (Hold-time "));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[10]));
ND_PRINT((ndo, ")"));
}
break;
case PIMV1_TYPE_REGISTER:
ND_TCHECK2(bp[8], 20); /* ip header */
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[20]),
ipaddr_string(ndo, &bp[24])));
break;
case PIMV1_TYPE_REGISTER_STOP:
ND_TCHECK2(bp[12], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[8]),
ipaddr_string(ndo, &bp[12])));
break;
case PIMV1_TYPE_RP_REACHABILITY:
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[22], 2);
ND_PRINT((ndo, " group %s", ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_PRINT((ndo, " RP %s hold ", ipaddr_string(ndo, &bp[16])));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[22]));
}
break;
case PIMV1_TYPE_ASSERT:
ND_TCHECK2(bp[16], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[16]),
ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_TCHECK2(bp[24], 4);
ND_PRINT((ndo, " %s pref %d metric %d",
(bp[20] & 0x80) ? "RP-tree" : "SPT",
EXTRACT_32BITS(&bp[20]) & 0x7fffffff,
EXTRACT_32BITS(&bp[24])));
break;
case PIMV1_TYPE_JOIN_PRUNE:
case PIMV1_TYPE_GRAFT:
case PIMV1_TYPE_GRAFT_ACK:
if (ndo->ndo_vflag)
pimv1_join_prune_print(ndo, &bp[8], len - 8);
break;
}
ND_TCHECK(bp[4]);
if ((bp[4] >> 4) != 1)
ND_PRINT((ndo, " [v%d]", bp[4] >> 4));
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
return;
}
Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks.
Use ND_TCHECK macros to do bounds checking, and add length checks before
the bounds checks.
Add a bounds check that the review process found was missing.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
Update one test output file to reflect the changes.
CWE ID: CWE-125 | pimv1_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
register u_char type;
ND_TCHECK(bp[1]);
type = bp[1];
ND_PRINT((ndo, " %s", tok2str(pimv1_type_str, "[type %u]", type)));
switch (type) {
case PIMV1_TYPE_QUERY:
if (ND_TTEST(bp[8])) {
switch (bp[8] >> 4) {
case 0:
ND_PRINT((ndo, " Dense-mode"));
break;
case 1:
ND_PRINT((ndo, " Sparse-mode"));
break;
case 2:
ND_PRINT((ndo, " Sparse-Dense-mode"));
break;
default:
ND_PRINT((ndo, " mode-%d", bp[8] >> 4));
break;
}
}
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[10],2);
ND_PRINT((ndo, " (Hold-time "));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[10]));
ND_PRINT((ndo, ")"));
}
break;
case PIMV1_TYPE_REGISTER:
ND_TCHECK2(bp[8], 20); /* ip header */
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[20]),
ipaddr_string(ndo, &bp[24])));
break;
case PIMV1_TYPE_REGISTER_STOP:
ND_TCHECK2(bp[12], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[8]),
ipaddr_string(ndo, &bp[12])));
break;
case PIMV1_TYPE_RP_REACHABILITY:
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[22], 2);
ND_PRINT((ndo, " group %s", ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_PRINT((ndo, " RP %s hold ", ipaddr_string(ndo, &bp[16])));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[22]));
}
break;
case PIMV1_TYPE_ASSERT:
ND_TCHECK2(bp[16], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[16]),
ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_TCHECK2(bp[24], 4);
ND_PRINT((ndo, " %s pref %d metric %d",
(bp[20] & 0x80) ? "RP-tree" : "SPT",
EXTRACT_32BITS(&bp[20]) & 0x7fffffff,
EXTRACT_32BITS(&bp[24])));
break;
case PIMV1_TYPE_JOIN_PRUNE:
case PIMV1_TYPE_GRAFT:
case PIMV1_TYPE_GRAFT_ACK:
if (ndo->ndo_vflag) {
if (len < 8)
goto trunc;
pimv1_join_prune_print(ndo, &bp[8], len - 8);
}
break;
}
ND_TCHECK(bp[4]);
if ((bp[4] >> 4) != 1)
ND_PRINT((ndo, " [v%d]", bp[4] >> 4));
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
return;
}
| 167,856 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len,
const cdf_header_t *h, cdf_secid_t id)
{
assert((size_t)CDF_SEC_SIZE(h) == len);
return cdf_read(info, (off_t)CDF_SEC_POS(h, id),
((char *)buf) + offs, len);
}
Commit Message: add more check found by cert's fuzzer.
CWE ID: CWE-119 | cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len,
const cdf_header_t *h, cdf_secid_t id)
{
size_t ss = CDF_SEC_SIZE(h);
size_t pos = CDF_SEC_POS(h, id);
assert(ss == len);
return cdf_read(info, (off_t)pos, ((char *)buf) + offs, len);
}
| 169,883 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DownloadManagerImpl::InterceptDownload(
const download::DownloadCreateInfo& info) {
WebContents* web_contents = WebContentsImpl::FromRenderFrameHostID(
info.render_process_id, info.render_frame_id);
if (info.is_new_download &&
info.result ==
download::DOWNLOAD_INTERRUPT_REASON_SERVER_CROSS_ORIGIN_REDIRECT) {
if (web_contents) {
std::vector<GURL> url_chain(info.url_chain);
GURL url = url_chain.back();
url_chain.pop_back();
NavigationController::LoadURLParams params(url);
params.has_user_gesture = info.has_user_gesture;
params.referrer = Referrer(
info.referrer_url, Referrer::NetReferrerPolicyToBlinkReferrerPolicy(
info.referrer_policy));
params.redirect_chain = url_chain;
web_contents->GetController().LoadURLWithParams(params);
}
if (info.request_handle)
info.request_handle->CancelRequest(false);
return true;
}
if (!delegate_ ||
!delegate_->InterceptDownloadIfApplicable(
info.url(), info.mime_type, info.request_origin, web_contents)) {
return false;
}
if (info.request_handle)
info.request_handle->CancelRequest(false);
return true;
}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <[email protected]>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629547}
CWE ID: CWE-284 | bool DownloadManagerImpl::InterceptDownload(
const download::DownloadCreateInfo& info) {
WebContents* web_contents = WebContentsImpl::FromRenderFrameHostID(
info.render_process_id, info.render_frame_id);
if (info.is_new_download &&
info.result ==
download::DOWNLOAD_INTERRUPT_REASON_SERVER_CROSS_ORIGIN_REDIRECT) {
if (web_contents) {
std::vector<GURL> url_chain(info.url_chain);
GURL url = url_chain.back();
url_chain.pop_back();
NavigationController::LoadURLParams params(url);
params.has_user_gesture = info.has_user_gesture;
params.referrer = Referrer(
info.referrer_url, Referrer::NetReferrerPolicyToBlinkReferrerPolicy(
info.referrer_policy));
params.redirect_chain = url_chain;
params.frame_tree_node_id =
RenderFrameHost::GetFrameTreeNodeIdForRoutingId(
info.render_process_id, info.render_frame_id);
web_contents->GetController().LoadURLWithParams(params);
}
if (info.request_handle)
info.request_handle->CancelRequest(false);
return true;
}
if (!delegate_ ||
!delegate_->InterceptDownloadIfApplicable(
info.url(), info.mime_type, info.request_origin, web_contents)) {
return false;
}
if (info.request_handle)
info.request_handle->CancelRequest(false);
return true;
}
| 173,023 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 hwsim_new_radio_nl(struct sk_buff *msg, struct genl_info *info)
{
struct hwsim_new_radio_params param = { 0 };
const char *hwname = NULL;
int ret;
param.reg_strict = info->attrs[HWSIM_ATTR_REG_STRICT_REG];
param.p2p_device = info->attrs[HWSIM_ATTR_SUPPORT_P2P_DEVICE];
param.channels = channels;
param.destroy_on_close =
info->attrs[HWSIM_ATTR_DESTROY_RADIO_ON_CLOSE];
if (info->attrs[HWSIM_ATTR_CHANNELS])
param.channels = nla_get_u32(info->attrs[HWSIM_ATTR_CHANNELS]);
if (info->attrs[HWSIM_ATTR_NO_VIF])
param.no_vif = true;
if (info->attrs[HWSIM_ATTR_RADIO_NAME]) {
hwname = kasprintf(GFP_KERNEL, "%.*s",
nla_len(info->attrs[HWSIM_ATTR_RADIO_NAME]),
(char *)nla_data(info->attrs[HWSIM_ATTR_RADIO_NAME]));
if (!hwname)
return -ENOMEM;
param.hwname = hwname;
}
if (info->attrs[HWSIM_ATTR_USE_CHANCTX])
param.use_chanctx = true;
else
param.use_chanctx = (param.channels > 1);
if (info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2])
param.reg_alpha2 =
nla_data(info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2]);
if (info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]) {
u32 idx = nla_get_u32(info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]);
if (idx >= ARRAY_SIZE(hwsim_world_regdom_custom))
return -EINVAL;
param.regd = hwsim_world_regdom_custom[idx];
}
ret = mac80211_hwsim_new_radio(info, ¶m);
kfree(hwname);
return ret;
}
Commit Message: mac80211_hwsim: fix possible memory leak in hwsim_new_radio_nl()
'hwname' is malloced in hwsim_new_radio_nl() and should be freed
before leaving from the error handling cases, otherwise it will cause
memory leak.
Fixes: ff4dd73dd2b4 ("mac80211_hwsim: check HWSIM_ATTR_RADIO_NAME length")
Signed-off-by: Wei Yongjun <[email protected]>
Reviewed-by: Ben Hutchings <[email protected]>
Signed-off-by: Johannes Berg <[email protected]>
CWE ID: CWE-772 | static int hwsim_new_radio_nl(struct sk_buff *msg, struct genl_info *info)
{
struct hwsim_new_radio_params param = { 0 };
const char *hwname = NULL;
int ret;
param.reg_strict = info->attrs[HWSIM_ATTR_REG_STRICT_REG];
param.p2p_device = info->attrs[HWSIM_ATTR_SUPPORT_P2P_DEVICE];
param.channels = channels;
param.destroy_on_close =
info->attrs[HWSIM_ATTR_DESTROY_RADIO_ON_CLOSE];
if (info->attrs[HWSIM_ATTR_CHANNELS])
param.channels = nla_get_u32(info->attrs[HWSIM_ATTR_CHANNELS]);
if (info->attrs[HWSIM_ATTR_NO_VIF])
param.no_vif = true;
if (info->attrs[HWSIM_ATTR_RADIO_NAME]) {
hwname = kasprintf(GFP_KERNEL, "%.*s",
nla_len(info->attrs[HWSIM_ATTR_RADIO_NAME]),
(char *)nla_data(info->attrs[HWSIM_ATTR_RADIO_NAME]));
if (!hwname)
return -ENOMEM;
param.hwname = hwname;
}
if (info->attrs[HWSIM_ATTR_USE_CHANCTX])
param.use_chanctx = true;
else
param.use_chanctx = (param.channels > 1);
if (info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2])
param.reg_alpha2 =
nla_data(info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2]);
if (info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]) {
u32 idx = nla_get_u32(info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]);
if (idx >= ARRAY_SIZE(hwsim_world_regdom_custom)) {
kfree(hwname);
return -EINVAL;
}
param.regd = hwsim_world_regdom_custom[idx];
}
ret = mac80211_hwsim_new_radio(info, ¶m);
kfree(hwname);
return ret;
}
| 169,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: virtual void SetUp() {
UUT_ = GET_PARAM(2);
/* Set up guard blocks for an inner block centered in the outer block */
for (int i = 0; i < kOutputBufferSize; ++i) {
if (IsIndexInBorder(i))
output_[i] = 255;
else
output_[i] = 0;
}
::libvpx_test::ACMRandom prng;
for (int i = 0; i < kInputBufferSize; ++i)
input_[i] = prng.Rand8Extremes();
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | virtual void SetUp() {
UUT_ = GET_PARAM(2);
#if CONFIG_VP9_HIGHBITDEPTH
if (UUT_->use_highbd_ != 0)
mask_ = (1 << UUT_->use_highbd_) - 1;
else
mask_ = 255;
#endif
/* Set up guard blocks for an inner block centered in the outer block */
for (int i = 0; i < kOutputBufferSize; ++i) {
if (IsIndexInBorder(i))
output_[i] = 255;
else
output_[i] = 0;
}
::libvpx_test::ACMRandom prng;
for (int i = 0; i < kInputBufferSize; ++i) {
if (i & 1) {
input_[i] = 255;
#if CONFIG_VP9_HIGHBITDEPTH
input16_[i] = mask_;
#endif
} else {
input_[i] = prng.Rand8Extremes();
#if CONFIG_VP9_HIGHBITDEPTH
input16_[i] = prng.Rand16() & mask_;
#endif
}
}
}
| 174,505 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::setParameter(
OMX_INDEXTYPE index, const void *params, size_t size) {
Mutex::Autolock autoLock(mLock);
OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index;
CLOG_CONFIG(setParameter, "%s(%#x), %zu@%p)", asString(extIndex), index, size, params);
OMX_ERRORTYPE err = OMX_SetParameter(
mHandle, index, const_cast<void *>(params));
CLOG_IF_ERROR(setParameter, err, "%s(%#x)", asString(extIndex), index);
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200 | status_t OMXNodeInstance::setParameter(
OMX_INDEXTYPE index, const void *params, size_t size) {
Mutex::Autolock autoLock(mLock);
OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index;
CLOG_CONFIG(setParameter, "%s(%#x), %zu@%p)", asString(extIndex), index, size, params);
if (isProhibitedIndex_l(index)) {
android_errorWriteLog(0x534e4554, "29422020");
return BAD_INDEX;
}
OMX_ERRORTYPE err = OMX_SetParameter(
mHandle, index, const_cast<void *>(params));
CLOG_IF_ERROR(setParameter, err, "%s(%#x)", asString(extIndex), index);
return StatusFromOMXError(err);
}
| 174,139 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: vhost_scsi_send_evt(struct vhost_scsi *vs,
struct vhost_scsi_tpg *tpg,
struct se_lun *lun,
u32 event,
u32 reason)
{
struct vhost_scsi_evt *evt;
evt = vhost_scsi_allocate_evt(vs, event, reason);
if (!evt)
return;
if (tpg && lun) {
/* TODO: share lun setup code with virtio-scsi.ko */
/*
* Note: evt->event is zeroed when we allocate it and
* lun[4-7] need to be zero according to virtio-scsi spec.
*/
evt->event.lun[0] = 0x01;
evt->event.lun[1] = tpg->tport_tpgt & 0xFF;
if (lun->unpacked_lun >= 256)
evt->event.lun[2] = lun->unpacked_lun >> 8 | 0x40 ;
evt->event.lun[3] = lun->unpacked_lun & 0xFF;
}
llist_add(&evt->list, &vs->vs_event_list);
vhost_work_queue(&vs->dev, &vs->vs_event_work);
}
Commit Message: vhost/scsi: potential memory corruption
This code in vhost_scsi_make_tpg() is confusing because we limit "tpgt"
to UINT_MAX but the data type of "tpg->tport_tpgt" and that is a u16.
I looked at the context and it turns out that in
vhost_scsi_set_endpoint(), "tpg->tport_tpgt" is used as an offset into
the vs_tpg[] array which has VHOST_SCSI_MAX_TARGET (256) elements so
anything higher than 255 then it is invalid. I have made that the limit
now.
In vhost_scsi_send_evt() we mask away values higher than 255, but now
that the limit has changed, we don't need the mask.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Nicholas Bellinger <[email protected]>
CWE ID: CWE-119 | vhost_scsi_send_evt(struct vhost_scsi *vs,
struct vhost_scsi_tpg *tpg,
struct se_lun *lun,
u32 event,
u32 reason)
{
struct vhost_scsi_evt *evt;
evt = vhost_scsi_allocate_evt(vs, event, reason);
if (!evt)
return;
if (tpg && lun) {
/* TODO: share lun setup code with virtio-scsi.ko */
/*
* Note: evt->event is zeroed when we allocate it and
* lun[4-7] need to be zero according to virtio-scsi spec.
*/
evt->event.lun[0] = 0x01;
evt->event.lun[1] = tpg->tport_tpgt;
if (lun->unpacked_lun >= 256)
evt->event.lun[2] = lun->unpacked_lun >> 8 | 0x40 ;
evt->event.lun[3] = lun->unpacked_lun & 0xFF;
}
llist_add(&evt->list, &vs->vs_event_list);
vhost_work_queue(&vs->dev, &vs->vs_event_work);
}
| 166,616 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebURLLoaderImpl::Context::OnReceivedResponse(
const ResourceResponseInfo& info) {
if (!client_)
return;
WebURLResponse response;
response.initialize();
PopulateURLResponse(request_.url(), info, &response);
bool show_raw_listing = (GURL(request_.url()).query() == "raw");
if (info.mime_type == "text/vnd.chromium.ftp-dir") {
if (show_raw_listing) {
response.setMIMEType("text/plain");
} else {
response.setMIMEType("text/html");
}
}
client_->didReceiveResponse(loader_, response);
if (!client_)
return;
DCHECK(!ftp_listing_delegate_.get());
DCHECK(!multipart_delegate_.get());
if (info.headers && info.mime_type == "multipart/x-mixed-replace") {
std::string content_type;
info.headers->EnumerateHeader(NULL, "content-type", &content_type);
std::string mime_type;
std::string charset;
bool had_charset = false;
std::string boundary;
net::HttpUtil::ParseContentType(content_type, &mime_type, &charset,
&had_charset, &boundary);
TrimString(boundary, " \"", &boundary);
if (!boundary.empty()) {
multipart_delegate_.reset(
new MultipartResponseDelegate(client_, loader_, response, boundary));
}
} else if (info.mime_type == "text/vnd.chromium.ftp-dir" &&
!show_raw_listing) {
ftp_listing_delegate_.reset(
new FtpDirectoryListingResponseDelegate(client_, loader_, response));
}
}
Commit Message: Protect WebURLLoaderImpl::Context while receiving responses.
A client's didReceiveResponse can cancel a request; by protecting the
Context we avoid a use after free in this case.
Interestingly, we really had very good warning about this problem, see
https://codereview.chromium.org/11900002/ back in January.
R=darin
BUG=241139
Review URL: https://chromiumcodereview.appspot.com/15738007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@202821 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416 | void WebURLLoaderImpl::Context::OnReceivedResponse(
const ResourceResponseInfo& info) {
if (!client_)
return;
WebURLResponse response;
response.initialize();
PopulateURLResponse(request_.url(), info, &response);
bool show_raw_listing = (GURL(request_.url()).query() == "raw");
if (info.mime_type == "text/vnd.chromium.ftp-dir") {
if (show_raw_listing) {
response.setMIMEType("text/plain");
} else {
response.setMIMEType("text/html");
}
}
scoped_refptr<Context> protect(this);
client_->didReceiveResponse(loader_, response);
if (!client_)
return;
DCHECK(!ftp_listing_delegate_.get());
DCHECK(!multipart_delegate_.get());
if (info.headers && info.mime_type == "multipart/x-mixed-replace") {
std::string content_type;
info.headers->EnumerateHeader(NULL, "content-type", &content_type);
std::string mime_type;
std::string charset;
bool had_charset = false;
std::string boundary;
net::HttpUtil::ParseContentType(content_type, &mime_type, &charset,
&had_charset, &boundary);
TrimString(boundary, " \"", &boundary);
if (!boundary.empty()) {
multipart_delegate_.reset(
new MultipartResponseDelegate(client_, loader_, response, boundary));
}
} else if (info.mime_type == "text/vnd.chromium.ftp-dir" &&
!show_raw_listing) {
ftp_listing_delegate_.reset(
new FtpDirectoryListingResponseDelegate(client_, loader_, response));
}
}
| 171,266 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 su3000_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[],
int num)
{
struct dvb_usb_device *d = i2c_get_adapdata(adap);
u8 obuf[0x40], ibuf[0x40];
if (!d)
return -ENODEV;
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
return -EAGAIN;
switch (num) {
case 1:
switch (msg[0].addr) {
case SU3000_STREAM_CTRL:
obuf[0] = msg[0].buf[0] + 0x36;
obuf[1] = 3;
obuf[2] = 0;
if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 0, 0) < 0)
err("i2c transfer failed.");
break;
case DW2102_RC_QUERY:
obuf[0] = 0x10;
if (dvb_usb_generic_rw(d, obuf, 1, ibuf, 2, 0) < 0)
err("i2c transfer failed.");
msg[0].buf[1] = ibuf[0];
msg[0].buf[0] = ibuf[1];
break;
default:
/* always i2c write*/
obuf[0] = 0x08;
obuf[1] = msg[0].addr;
obuf[2] = msg[0].len;
memcpy(&obuf[3], msg[0].buf, msg[0].len);
if (dvb_usb_generic_rw(d, obuf, msg[0].len + 3,
ibuf, 1, 0) < 0)
err("i2c transfer failed.");
}
break;
case 2:
/* always i2c read */
obuf[0] = 0x09;
obuf[1] = msg[0].len;
obuf[2] = msg[1].len;
obuf[3] = msg[0].addr;
memcpy(&obuf[4], msg[0].buf, msg[0].len);
if (dvb_usb_generic_rw(d, obuf, msg[0].len + 4,
ibuf, msg[1].len + 1, 0) < 0)
err("i2c transfer failed.");
memcpy(msg[1].buf, &ibuf[1], msg[1].len);
break;
default:
warn("more than 2 i2c messages at a time is not handled yet.");
break;
}
mutex_unlock(&d->i2c_mutex);
return num;
}
Commit Message: [media] dw2102: don't do DMA on stack
On Kernel 4.9, WARNINGs about doing DMA on stack are hit at
the dw2102 driver: one in su3000_power_ctrl() and the other in tt_s2_4600_frontend_attach().
Both were due to the use of buffers on the stack as parameters to
dvb_usb_generic_rw() and the resulting attempt to do DMA with them.
The device was non-functional as a result.
So, switch this driver over to use a buffer within the device state
structure, as has been done with other DVB-USB drivers.
Tested with TechnoTrend TT-connect S2-4600.
[[email protected]: fixed a warning at su3000_i2c_transfer() that
state var were dereferenced before check 'd']
Signed-off-by: Jonathan McDowell <[email protected]>
Cc: <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119 | static int su3000_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[],
int num)
{
struct dvb_usb_device *d = i2c_get_adapdata(adap);
struct dw2102_state *state;
if (!d)
return -ENODEV;
state = d->priv;
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
return -EAGAIN;
if (mutex_lock_interruptible(&d->data_mutex) < 0) {
mutex_unlock(&d->i2c_mutex);
return -EAGAIN;
}
switch (num) {
case 1:
switch (msg[0].addr) {
case SU3000_STREAM_CTRL:
state->data[0] = msg[0].buf[0] + 0x36;
state->data[1] = 3;
state->data[2] = 0;
if (dvb_usb_generic_rw(d, state->data, 3,
state->data, 0, 0) < 0)
err("i2c transfer failed.");
break;
case DW2102_RC_QUERY:
state->data[0] = 0x10;
if (dvb_usb_generic_rw(d, state->data, 1,
state->data, 2, 0) < 0)
err("i2c transfer failed.");
msg[0].buf[1] = state->data[0];
msg[0].buf[0] = state->data[1];
break;
default:
/* always i2c write*/
state->data[0] = 0x08;
state->data[1] = msg[0].addr;
state->data[2] = msg[0].len;
memcpy(&state->data[3], msg[0].buf, msg[0].len);
if (dvb_usb_generic_rw(d, state->data, msg[0].len + 3,
state->data, 1, 0) < 0)
err("i2c transfer failed.");
}
break;
case 2:
/* always i2c read */
state->data[0] = 0x09;
state->data[1] = msg[0].len;
state->data[2] = msg[1].len;
state->data[3] = msg[0].addr;
memcpy(&state->data[4], msg[0].buf, msg[0].len);
if (dvb_usb_generic_rw(d, state->data, msg[0].len + 4,
state->data, msg[1].len + 1, 0) < 0)
err("i2c transfer failed.");
memcpy(msg[1].buf, &state->data[1], msg[1].len);
break;
default:
warn("more than 2 i2c messages at a time is not handled yet.");
break;
}
mutex_unlock(&d->data_mutex);
mutex_unlock(&d->i2c_mutex);
return num;
}
| 168,226 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: send_parameters(struct iperf_test *test)
{
int r = 0;
cJSON *j;
j = cJSON_CreateObject();
if (j == NULL) {
i_errno = IESENDPARAMS;
r = -1;
} else {
if (test->protocol->id == Ptcp)
cJSON_AddTrueToObject(j, "tcp");
else if (test->protocol->id == Pudp)
cJSON_AddTrueToObject(j, "udp");
cJSON_AddIntToObject(j, "omit", test->omit);
if (test->server_affinity != -1)
cJSON_AddIntToObject(j, "server_affinity", test->server_affinity);
if (test->duration)
cJSON_AddIntToObject(j, "time", test->duration);
if (test->settings->bytes)
cJSON_AddIntToObject(j, "num", test->settings->bytes);
if (test->settings->blocks)
cJSON_AddIntToObject(j, "blockcount", test->settings->blocks);
if (test->settings->mss)
cJSON_AddIntToObject(j, "MSS", test->settings->mss);
if (test->no_delay)
cJSON_AddTrueToObject(j, "nodelay");
cJSON_AddIntToObject(j, "parallel", test->num_streams);
if (test->reverse)
cJSON_AddTrueToObject(j, "reverse");
if (test->settings->socket_bufsize)
cJSON_AddIntToObject(j, "window", test->settings->socket_bufsize);
if (test->settings->blksize)
cJSON_AddIntToObject(j, "len", test->settings->blksize);
if (test->settings->rate)
cJSON_AddIntToObject(j, "bandwidth", test->settings->rate);
if (test->settings->burst)
cJSON_AddIntToObject(j, "burst", test->settings->burst);
if (test->settings->tos)
cJSON_AddIntToObject(j, "TOS", test->settings->tos);
if (test->settings->flowlabel)
cJSON_AddIntToObject(j, "flowlabel", test->settings->flowlabel);
if (test->title)
cJSON_AddStringToObject(j, "title", test->title);
if (test->congestion)
cJSON_AddStringToObject(j, "congestion", test->congestion);
if (test->get_server_output)
cJSON_AddIntToObject(j, "get_server_output", iperf_get_test_get_server_output(test));
if (test->debug) {
printf("send_parameters:\n%s\n", cJSON_Print(j));
}
if (JSON_write(test->ctrl_sck, j) < 0) {
i_errno = IESENDPARAMS;
r = -1;
}
cJSON_Delete(j);
}
return r;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | send_parameters(struct iperf_test *test)
{
int r = 0;
cJSON *j;
j = cJSON_CreateObject();
if (j == NULL) {
i_errno = IESENDPARAMS;
r = -1;
} else {
if (test->protocol->id == Ptcp)
cJSON_AddTrueToObject(j, "tcp");
else if (test->protocol->id == Pudp)
cJSON_AddTrueToObject(j, "udp");
cJSON_AddNumberToObject(j, "omit", test->omit);
if (test->server_affinity != -1)
cJSON_AddNumberToObject(j, "server_affinity", test->server_affinity);
if (test->duration)
cJSON_AddNumberToObject(j, "time", test->duration);
if (test->settings->bytes)
cJSON_AddNumberToObject(j, "num", test->settings->bytes);
if (test->settings->blocks)
cJSON_AddNumberToObject(j, "blockcount", test->settings->blocks);
if (test->settings->mss)
cJSON_AddNumberToObject(j, "MSS", test->settings->mss);
if (test->no_delay)
cJSON_AddTrueToObject(j, "nodelay");
cJSON_AddNumberToObject(j, "parallel", test->num_streams);
if (test->reverse)
cJSON_AddTrueToObject(j, "reverse");
if (test->settings->socket_bufsize)
cJSON_AddNumberToObject(j, "window", test->settings->socket_bufsize);
if (test->settings->blksize)
cJSON_AddNumberToObject(j, "len", test->settings->blksize);
if (test->settings->rate)
cJSON_AddNumberToObject(j, "bandwidth", test->settings->rate);
if (test->settings->burst)
cJSON_AddNumberToObject(j, "burst", test->settings->burst);
if (test->settings->tos)
cJSON_AddNumberToObject(j, "TOS", test->settings->tos);
if (test->settings->flowlabel)
cJSON_AddNumberToObject(j, "flowlabel", test->settings->flowlabel);
if (test->title)
cJSON_AddStringToObject(j, "title", test->title);
if (test->congestion)
cJSON_AddStringToObject(j, "congestion", test->congestion);
if (test->get_server_output)
<<<<<<< HEAD
cJSON_AddIntToObject(j, "get_server_output", iperf_get_test_get_server_output(test));
=======
cJSON_AddNumberToObject(j, "get_server_output", iperf_get_test_get_server_output(test));
if (test->udp_counters_64bit)
cJSON_AddNumberToObject(j, "udp_counters_64bit", iperf_get_test_udp_counters_64bit(test));
if (test->no_fq_socket_pacing)
cJSON_AddNumberToObject(j, "no_fq_socket_pacing", iperf_get_no_fq_socket_pacing(test));
cJSON_AddStringToObject(j, "client_version", IPERF_VERSION);
>>>>>>> ed94082... Fix a buffer overflow / heap corruption issue that could occur if a
if (test->debug) {
printf("send_parameters:\n%s\n", cJSON_Print(j));
}
if (JSON_write(test->ctrl_sck, j) < 0) {
i_errno = IESENDPARAMS;
r = -1;
}
cJSON_Delete(j);
}
return r;
}
| 167,316 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Gfx::Gfx(XRef *xrefA, OutputDev *outA, int pageNum, Dict *resDict, Catalog *catalogA,
double hDPI, double vDPI, PDFRectangle *box,
PDFRectangle *cropBox, int rotate,
GBool (*abortCheckCbkA)(void *data),
void *abortCheckCbkDataA)
#ifdef USE_CMS
: iccColorSpaceCache(5)
#endif
{
int i;
xref = xrefA;
catalog = catalogA;
subPage = gFalse;
printCommands = globalParams->getPrintCommands();
profileCommands = globalParams->getProfileCommands();
textHaveCSPattern = gFalse;
drawText = gFalse;
maskHaveCSPattern = gFalse;
mcStack = NULL;
res = new GfxResources(xref, resDict, NULL);
out = outA;
state = new GfxState(hDPI, vDPI, box, rotate, out->upsideDown());
stackHeight = 1;
pushStateGuard();
fontChanged = gFalse;
clip = clipNone;
ignoreUndef = 0;
out->startPage(pageNum, state);
out->setDefaultCTM(state->getCTM());
out->updateAll(state);
for (i = 0; i < 6; ++i) {
baseMatrix[i] = state->getCTM()[i];
}
formDepth = 0;
abortCheckCbk = abortCheckCbkA;
abortCheckCbkData = abortCheckCbkDataA;
if (cropBox) {
state->moveTo(cropBox->x1, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y2);
state->lineTo(cropBox->x1, cropBox->y2);
state->closePath();
state->clip();
out->clip(state);
state->clearPath();
}
}
Commit Message:
CWE ID: CWE-20 | Gfx::Gfx(XRef *xrefA, OutputDev *outA, int pageNum, Dict *resDict, Catalog *catalogA,
double hDPI, double vDPI, PDFRectangle *box,
PDFRectangle *cropBox, int rotate,
GBool (*abortCheckCbkA)(void *data),
void *abortCheckCbkDataA)
#ifdef USE_CMS
: iccColorSpaceCache(5)
#endif
{
int i;
xref = xrefA;
catalog = catalogA;
subPage = gFalse;
printCommands = globalParams->getPrintCommands();
profileCommands = globalParams->getProfileCommands();
textHaveCSPattern = gFalse;
drawText = gFalse;
maskHaveCSPattern = gFalse;
mcStack = NULL;
parser = NULL;
res = new GfxResources(xref, resDict, NULL);
out = outA;
state = new GfxState(hDPI, vDPI, box, rotate, out->upsideDown());
stackHeight = 1;
pushStateGuard();
fontChanged = gFalse;
clip = clipNone;
ignoreUndef = 0;
out->startPage(pageNum, state);
out->setDefaultCTM(state->getCTM());
out->updateAll(state);
for (i = 0; i < 6; ++i) {
baseMatrix[i] = state->getCTM()[i];
}
formDepth = 0;
abortCheckCbk = abortCheckCbkA;
abortCheckCbkData = abortCheckCbkDataA;
if (cropBox) {
state->moveTo(cropBox->x1, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y2);
state->lineTo(cropBox->x1, cropBox->y2);
state->closePath();
state->clip();
out->clip(state);
state->clearPath();
}
}
| 164,904 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebContentsImpl::IsLoading() const {
return frame_tree_.IsLoading() &&
!(ShowingInterstitialPage() &&
GetRenderManager()->interstitial_page()->pause_throbber());
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20 | bool WebContentsImpl::IsLoading() const {
return frame_tree_.IsLoading() &&
!(ShowingInterstitialPage() && interstitial_page_->pause_throbber());
}
| 172,331 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms,
CMS_RecipientInfo *ri)
{
CMS_KeyTransRecipientInfo *ktri = ri->d.ktri;
EVP_PKEY *pkey = ktri->pkey;
unsigned char *ek = NULL;
size_t eklen;
int ret = 0;
CMS_EncryptedContentInfo *ec;
ec = cms->d.envelopedData->encryptedContentInfo;
CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_NO_PRIVATE_KEY);
return 0;
return 0;
}
Commit Message:
CWE ID: CWE-311 | static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms,
CMS_RecipientInfo *ri)
{
CMS_KeyTransRecipientInfo *ktri = ri->d.ktri;
EVP_PKEY *pkey = ktri->pkey;
unsigned char *ek = NULL;
size_t eklen;
int ret = 0;
size_t fixlen = 0;
CMS_EncryptedContentInfo *ec;
ec = cms->d.envelopedData->encryptedContentInfo;
CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_NO_PRIVATE_KEY);
return 0;
return 0;
}
| 165,137 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 regulator_ena_gpio_free(struct regulator_dev *rdev)
{
struct regulator_enable_gpio *pin, *n;
if (!rdev->ena_pin)
return;
/* Free the GPIO only in case of no use */
list_for_each_entry_safe(pin, n, ®ulator_ena_gpio_list, list) {
if (pin->gpiod == rdev->ena_pin->gpiod) {
if (pin->request_count <= 1) {
pin->request_count = 0;
gpiod_put(pin->gpiod);
list_del(&pin->list);
kfree(pin);
} else {
pin->request_count--;
}
}
}
}
Commit Message: regulator: core: Fix regualtor_ena_gpio_free not to access pin after freeing
After freeing pin from regulator_ena_gpio_free, loop can access
the pin. So this patch fixes not to access pin after freeing.
Signed-off-by: Seung-Woo Kim <[email protected]>
Signed-off-by: Mark Brown <[email protected]>
CWE ID: CWE-416 | static void regulator_ena_gpio_free(struct regulator_dev *rdev)
{
struct regulator_enable_gpio *pin, *n;
if (!rdev->ena_pin)
return;
/* Free the GPIO only in case of no use */
list_for_each_entry_safe(pin, n, ®ulator_ena_gpio_list, list) {
if (pin->gpiod == rdev->ena_pin->gpiod) {
if (pin->request_count <= 1) {
pin->request_count = 0;
gpiod_put(pin->gpiod);
list_del(&pin->list);
kfree(pin);
rdev->ena_pin = NULL;
return;
} else {
pin->request_count--;
}
}
}
}
| 168,894 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: XSharedMemoryId AttachSharedMemory(Display* display, int shared_memory_key) {
DCHECK(QuerySharedMemorySupport(display));
XShmSegmentInfo shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmid = shared_memory_key;
if (!XShmAttach(display, &shminfo))
NOTREACHED();
return shminfo.shmseg;
}
Commit Message: Make shared memory segments writable only by their rightful owners.
BUG=143859
TEST=Chrome's UI still works on Linux and Chrome OS
Review URL: https://chromiumcodereview.appspot.com/10854242
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | XSharedMemoryId AttachSharedMemory(Display* display, int shared_memory_key) {
DCHECK(QuerySharedMemorySupport(display));
XShmSegmentInfo shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmid = shared_memory_key;
if (!XShmAttach(display, &shminfo)) {
LOG(WARNING) << "X failed to attach to shared memory segment "
<< shminfo.shmid;
NOTREACHED();
} else {
VLOG(1) << "X attached to shared memory segment " << shminfo.shmid;
}
return shminfo.shmseg;
}
| 171,593 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SSLManager::OnSSLCertificateError(
base::WeakPtr<SSLErrorHandler::Delegate> delegate,
const content::GlobalRequestID& id,
const ResourceType::Type resource_type,
const GURL& url,
int render_process_id,
int render_view_id,
const net::SSLInfo& ssl_info,
bool fatal) {
DCHECK(delegate);
DVLOG(1) << "OnSSLCertificateError() cert_error: "
<< net::MapCertStatusToNetError(ssl_info.cert_status)
<< " id: " << id.child_id << "," << id.request_id
<< " resource_type: " << resource_type
<< " url: " << url.spec()
<< " render_process_id: " << render_process_id
<< " render_view_id: " << render_view_id
<< " cert_status: " << std::hex << ssl_info.cert_status;
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&SSLCertErrorHandler::Dispatch,
new SSLCertErrorHandler(delegate,
id,
resource_type,
url,
render_process_id,
render_view_id,
ssl_info,
fatal)));
}
Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T>
This change refines r137676.
BUG=122654
TEST=browser_test
Review URL: https://chromiumcodereview.appspot.com/10332233
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void SSLManager::OnSSLCertificateError(
const base::WeakPtr<SSLErrorHandler::Delegate>& delegate,
const content::GlobalRequestID& id,
const ResourceType::Type resource_type,
const GURL& url,
int render_process_id,
int render_view_id,
const net::SSLInfo& ssl_info,
bool fatal) {
DCHECK(delegate);
DVLOG(1) << "OnSSLCertificateError() cert_error: "
<< net::MapCertStatusToNetError(ssl_info.cert_status)
<< " id: " << id.child_id << "," << id.request_id
<< " resource_type: " << resource_type
<< " url: " << url.spec()
<< " render_process_id: " << render_process_id
<< " render_view_id: " << render_view_id
<< " cert_status: " << std::hex << ssl_info.cert_status;
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&SSLCertErrorHandler::Dispatch,
new SSLCertErrorHandler(delegate,
id,
resource_type,
url,
render_process_id,
render_view_id,
ssl_info,
fatal)));
}
| 170,996 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
int ret;
mutex_lock(&dev->lock);
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_GET_REPORT);
if (ret != CP2112_GPIO_CONFIG_LENGTH) {
hid_err(hdev, "error requesting GPIO config: %d\n", ret);
goto exit;
}
buf[1] &= ~(1 << offset);
buf[2] = gpio_push_pull;
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (ret < 0) {
hid_err(hdev, "error setting GPIO config: %d\n", ret);
goto exit;
}
ret = 0;
exit:
mutex_unlock(&dev->lock);
return ret <= 0 ? ret : -EIO;
}
Commit Message: HID: cp2112: fix gpio-callback error handling
In case of a zero-length report, the gpio direction_input callback would
currently return success instead of an errno.
Fixes: 1ffb3c40ffb5 ("HID: cp2112: make transfer buffers DMA capable")
Cc: stable <[email protected]> # 4.9
Signed-off-by: Johan Hovold <[email protected]>
Reviewed-by: Benjamin Tissoires <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-388 | static int cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
int ret;
mutex_lock(&dev->lock);
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_GET_REPORT);
if (ret != CP2112_GPIO_CONFIG_LENGTH) {
hid_err(hdev, "error requesting GPIO config: %d\n", ret);
goto exit;
}
buf[1] &= ~(1 << offset);
buf[2] = gpio_push_pull;
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (ret < 0) {
hid_err(hdev, "error setting GPIO config: %d\n", ret);
goto exit;
}
ret = 0;
exit:
mutex_unlock(&dev->lock);
return ret < 0 ? ret : -EIO;
}
| 168,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 int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) + len > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
}
Commit Message: Add bounds check before length read
CWE ID: CWE-125 | static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
if( (*p) > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) + len > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
}
| 169,265 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: scandir(const char *dir, struct dirent ***namelist,
int (*select) (const struct dirent *),
int (*compar) (const struct dirent **, const struct dirent **))
{
DIR *d = opendir(dir);
struct dirent *current;
struct dirent **names;
int count = 0;
int pos = 0;
int result = -1;
if (NULL == d)
return -1;
while (NULL != readdir(d))
count++;
names = malloc(sizeof (struct dirent *) * count);
closedir(d);
d = opendir(dir);
if (NULL == d)
return -1;
while (NULL != (current = readdir(d))) {
if (NULL == select || select(current)) {
struct dirent *copyentry = malloc(current->d_reclen);
memcpy(copyentry, current, current->d_reclen);
names[pos] = copyentry;
pos++;
}
}
result = closedir(d);
if (pos != count)
names = realloc(names, sizeof (struct dirent *) * pos);
*namelist = names;
return pos;
}
Commit Message: misc oom and possible memory leak fix
CWE ID: | scandir(const char *dir, struct dirent ***namelist,
int (*select) (const struct dirent *),
int (*compar) (const struct dirent **, const struct dirent **))
{
DIR *d = opendir(dir);
struct dirent *current;
struct dirent **names;
int count = 0;
int pos = 0;
int result = -1;
if (NULL == d)
return -1;
while (NULL != readdir(d))
count++;
closedir(d);
names = malloc(sizeof (struct dirent *) * count);
if (!names)
return -1;
d = opendir(dir);
if (NULL == d) {
free(names);
return -1;
}
while (NULL != (current = readdir(d))) {
if (NULL == select || select(current)) {
struct dirent *copyentry = malloc(current->d_reclen);
/* FIXME: OOM, silently skip it?*/
if (!copyentry)
continue;
memcpy(copyentry, current, current->d_reclen);
names[pos] = copyentry;
pos++;
}
}
result = closedir(d);
if (pos != count)
names = realloc(names, sizeof (struct dirent *) * pos);
*namelist = names;
return pos;
}
| 169,754 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int iov_fault_in_pages_write(struct iovec *iov, unsigned long len)
{
while (!iov->iov_len)
iov++;
while (len > 0) {
unsigned long this_len;
this_len = min_t(unsigned long, len, iov->iov_len);
if (fault_in_pages_writeable(iov->iov_base, this_len))
break;
len -= this_len;
iov++;
}
return len;
}
Commit Message: switch pipe_read() to copy_page_to_iter()
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | static int iov_fault_in_pages_write(struct iovec *iov, unsigned long len)
| 169,927 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 <[email protected]>
Reviewed-by: Alexei Svitkine <[email protected]>
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: virtual InputMethodDescriptors* GetSupportedInputMethods() {
if (!initialized_successfully_) {
InputMethodDescriptors* result = new InputMethodDescriptors;
result->push_back(input_method::GetFallbackInputMethodDescriptor());
return result;
}
return chromeos::GetSupportedInputMethodDescriptors();
}
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 | virtual InputMethodDescriptors* GetSupportedInputMethods() {
virtual input_method::InputMethodDescriptors* GetSupportedInputMethods() {
if (!initialized_successfully_) {
input_method::InputMethodDescriptors* result =
new input_method::InputMethodDescriptors;
result->push_back(input_method::GetFallbackInputMethodDescriptor());
return result;
}
return input_method::GetSupportedInputMethodDescriptors();
}
| 170,492 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_MINIT_FUNCTION(zip)
{
#ifdef PHP_ZIP_USE_OO
zend_class_entry ce;
memcpy(&zip_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
zip_object_handlers.clone_obj = NULL;
zip_object_handlers.get_property_ptr_ptr = php_zip_get_property_ptr_ptr;
zip_object_handlers.get_properties = php_zip_get_properties;
zip_object_handlers.read_property = php_zip_read_property;
zip_object_handlers.has_property = php_zip_has_property;
INIT_CLASS_ENTRY(ce, "ZipArchive", zip_class_functions);
ce.create_object = php_zip_object_new;
zip_class_entry = zend_register_internal_class(&ce TSRMLS_CC);
zend_hash_init(&zip_prop_handlers, 0, NULL, NULL, 1);
php_zip_register_prop_handler(&zip_prop_handlers, "status", php_zip_status, NULL, NULL, IS_LONG TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "statusSys", php_zip_status_sys, NULL, NULL, IS_LONG TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "numFiles", php_zip_get_num_files, NULL, NULL, IS_LONG TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "filename", NULL, NULL, php_zipobj_get_filename, IS_STRING TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "comment", NULL, php_zipobj_get_zip_comment, NULL, IS_STRING TSRMLS_CC);
REGISTER_ZIP_CLASS_CONST_LONG("CREATE", ZIP_CREATE);
REGISTER_ZIP_CLASS_CONST_LONG("EXCL", ZIP_EXCL);
REGISTER_ZIP_CLASS_CONST_LONG("CHECKCONS", ZIP_CHECKCONS);
REGISTER_ZIP_CLASS_CONST_LONG("OVERWRITE", ZIP_OVERWRITE);
REGISTER_ZIP_CLASS_CONST_LONG("FL_NOCASE", ZIP_FL_NOCASE);
REGISTER_ZIP_CLASS_CONST_LONG("FL_NODIR", ZIP_FL_NODIR);
REGISTER_ZIP_CLASS_CONST_LONG("FL_COMPRESSED", ZIP_FL_COMPRESSED);
REGISTER_ZIP_CLASS_CONST_LONG("FL_UNCHANGED", ZIP_FL_UNCHANGED);
REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFAULT", ZIP_CM_DEFAULT);
REGISTER_ZIP_CLASS_CONST_LONG("CM_STORE", ZIP_CM_STORE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_SHRINK", ZIP_CM_SHRINK);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_1", ZIP_CM_REDUCE_1);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_2", ZIP_CM_REDUCE_2);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_3", ZIP_CM_REDUCE_3);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_4", ZIP_CM_REDUCE_4);
REGISTER_ZIP_CLASS_CONST_LONG("CM_IMPLODE", ZIP_CM_IMPLODE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFLATE", ZIP_CM_DEFLATE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFLATE64", ZIP_CM_DEFLATE64);
REGISTER_ZIP_CLASS_CONST_LONG("CM_PKWARE_IMPLODE", ZIP_CM_PKWARE_IMPLODE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_BZIP2", ZIP_CM_BZIP2);
REGISTER_ZIP_CLASS_CONST_LONG("CM_LZMA", ZIP_CM_LZMA);
REGISTER_ZIP_CLASS_CONST_LONG("CM_TERSE", ZIP_CM_TERSE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_LZ77", ZIP_CM_LZ77);
REGISTER_ZIP_CLASS_CONST_LONG("CM_WAVPACK", ZIP_CM_WAVPACK);
REGISTER_ZIP_CLASS_CONST_LONG("CM_PPMD", ZIP_CM_PPMD);
/* Error code */
REGISTER_ZIP_CLASS_CONST_LONG("ER_OK", ZIP_ER_OK); /* N No error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_MULTIDISK", ZIP_ER_MULTIDISK); /* N Multi-disk zip archives not supported */
REGISTER_ZIP_CLASS_CONST_LONG("ER_RENAME", ZIP_ER_RENAME); /* S Renaming temporary file failed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_CLOSE", ZIP_ER_CLOSE); /* S Closing zip archive failed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_SEEK", ZIP_ER_SEEK); /* S Seek error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_READ", ZIP_ER_READ); /* S Read error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_WRITE", ZIP_ER_WRITE); /* S Write error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_CRC", ZIP_ER_CRC); /* N CRC error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_ZIPCLOSED", ZIP_ER_ZIPCLOSED); /* N Containing zip archive was closed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_NOENT", ZIP_ER_NOENT); /* N No such file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_EXISTS", ZIP_ER_EXISTS); /* N File already exists */
REGISTER_ZIP_CLASS_CONST_LONG("ER_OPEN", ZIP_ER_OPEN); /* S Can't open file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_TMPOPEN", ZIP_ER_TMPOPEN); /* S Failure to create temporary file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_ZLIB", ZIP_ER_ZLIB); /* Z Zlib error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_MEMORY", ZIP_ER_MEMORY); /* N Malloc failure */
REGISTER_ZIP_CLASS_CONST_LONG("ER_CHANGED", ZIP_ER_CHANGED); /* N Entry has been changed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_COMPNOTSUPP", ZIP_ER_COMPNOTSUPP);/* N Compression method not supported */
REGISTER_ZIP_CLASS_CONST_LONG("ER_EOF", ZIP_ER_EOF); /* N Premature EOF */
REGISTER_ZIP_CLASS_CONST_LONG("ER_INVAL", ZIP_ER_INVAL); /* N Invalid argument */
REGISTER_ZIP_CLASS_CONST_LONG("ER_NOZIP", ZIP_ER_NOZIP); /* N Not a zip archive */
REGISTER_ZIP_CLASS_CONST_LONG("ER_INTERNAL", ZIP_ER_INTERNAL); /* N Internal error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_INCONS", ZIP_ER_INCONS); /* N Zip archive inconsistent */
REGISTER_ZIP_CLASS_CONST_LONG("ER_REMOVE", ZIP_ER_REMOVE); /* S Can't remove file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_DELETED", ZIP_ER_DELETED); /* N Entry has been deleted */
php_register_url_stream_wrapper("zip", &php_stream_zip_wrapper TSRMLS_CC);
#endif
le_zip_dir = zend_register_list_destructors_ex(php_zip_free_dir, NULL, le_zip_dir_name, module_number);
le_zip_entry = zend_register_list_destructors_ex(php_zip_free_entry, NULL, le_zip_entry_name, module_number);
return SUCCESS;
}
Commit Message: Fix bug #72434: ZipArchive class Use After Free Vulnerability in PHP's GC algorithm and unserialize
CWE ID: CWE-416 | static PHP_MINIT_FUNCTION(zip)
{
#ifdef PHP_ZIP_USE_OO
zend_class_entry ce;
memcpy(&zip_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
zip_object_handlers.clone_obj = NULL;
zip_object_handlers.get_property_ptr_ptr = php_zip_get_property_ptr_ptr;
zip_object_handlers.get_gc = php_zip_get_gc;
zip_object_handlers.get_properties = php_zip_get_properties;
zip_object_handlers.read_property = php_zip_read_property;
zip_object_handlers.has_property = php_zip_has_property;
INIT_CLASS_ENTRY(ce, "ZipArchive", zip_class_functions);
ce.create_object = php_zip_object_new;
zip_class_entry = zend_register_internal_class(&ce TSRMLS_CC);
zend_hash_init(&zip_prop_handlers, 0, NULL, NULL, 1);
php_zip_register_prop_handler(&zip_prop_handlers, "status", php_zip_status, NULL, NULL, IS_LONG TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "statusSys", php_zip_status_sys, NULL, NULL, IS_LONG TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "numFiles", php_zip_get_num_files, NULL, NULL, IS_LONG TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "filename", NULL, NULL, php_zipobj_get_filename, IS_STRING TSRMLS_CC);
php_zip_register_prop_handler(&zip_prop_handlers, "comment", NULL, php_zipobj_get_zip_comment, NULL, IS_STRING TSRMLS_CC);
REGISTER_ZIP_CLASS_CONST_LONG("CREATE", ZIP_CREATE);
REGISTER_ZIP_CLASS_CONST_LONG("EXCL", ZIP_EXCL);
REGISTER_ZIP_CLASS_CONST_LONG("CHECKCONS", ZIP_CHECKCONS);
REGISTER_ZIP_CLASS_CONST_LONG("OVERWRITE", ZIP_OVERWRITE);
REGISTER_ZIP_CLASS_CONST_LONG("FL_NOCASE", ZIP_FL_NOCASE);
REGISTER_ZIP_CLASS_CONST_LONG("FL_NODIR", ZIP_FL_NODIR);
REGISTER_ZIP_CLASS_CONST_LONG("FL_COMPRESSED", ZIP_FL_COMPRESSED);
REGISTER_ZIP_CLASS_CONST_LONG("FL_UNCHANGED", ZIP_FL_UNCHANGED);
REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFAULT", ZIP_CM_DEFAULT);
REGISTER_ZIP_CLASS_CONST_LONG("CM_STORE", ZIP_CM_STORE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_SHRINK", ZIP_CM_SHRINK);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_1", ZIP_CM_REDUCE_1);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_2", ZIP_CM_REDUCE_2);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_3", ZIP_CM_REDUCE_3);
REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_4", ZIP_CM_REDUCE_4);
REGISTER_ZIP_CLASS_CONST_LONG("CM_IMPLODE", ZIP_CM_IMPLODE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFLATE", ZIP_CM_DEFLATE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFLATE64", ZIP_CM_DEFLATE64);
REGISTER_ZIP_CLASS_CONST_LONG("CM_PKWARE_IMPLODE", ZIP_CM_PKWARE_IMPLODE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_BZIP2", ZIP_CM_BZIP2);
REGISTER_ZIP_CLASS_CONST_LONG("CM_LZMA", ZIP_CM_LZMA);
REGISTER_ZIP_CLASS_CONST_LONG("CM_TERSE", ZIP_CM_TERSE);
REGISTER_ZIP_CLASS_CONST_LONG("CM_LZ77", ZIP_CM_LZ77);
REGISTER_ZIP_CLASS_CONST_LONG("CM_WAVPACK", ZIP_CM_WAVPACK);
REGISTER_ZIP_CLASS_CONST_LONG("CM_PPMD", ZIP_CM_PPMD);
/* Error code */
REGISTER_ZIP_CLASS_CONST_LONG("ER_OK", ZIP_ER_OK); /* N No error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_MULTIDISK", ZIP_ER_MULTIDISK); /* N Multi-disk zip archives not supported */
REGISTER_ZIP_CLASS_CONST_LONG("ER_RENAME", ZIP_ER_RENAME); /* S Renaming temporary file failed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_CLOSE", ZIP_ER_CLOSE); /* S Closing zip archive failed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_SEEK", ZIP_ER_SEEK); /* S Seek error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_READ", ZIP_ER_READ); /* S Read error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_WRITE", ZIP_ER_WRITE); /* S Write error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_CRC", ZIP_ER_CRC); /* N CRC error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_ZIPCLOSED", ZIP_ER_ZIPCLOSED); /* N Containing zip archive was closed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_NOENT", ZIP_ER_NOENT); /* N No such file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_EXISTS", ZIP_ER_EXISTS); /* N File already exists */
REGISTER_ZIP_CLASS_CONST_LONG("ER_OPEN", ZIP_ER_OPEN); /* S Can't open file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_TMPOPEN", ZIP_ER_TMPOPEN); /* S Failure to create temporary file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_ZLIB", ZIP_ER_ZLIB); /* Z Zlib error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_MEMORY", ZIP_ER_MEMORY); /* N Malloc failure */
REGISTER_ZIP_CLASS_CONST_LONG("ER_CHANGED", ZIP_ER_CHANGED); /* N Entry has been changed */
REGISTER_ZIP_CLASS_CONST_LONG("ER_COMPNOTSUPP", ZIP_ER_COMPNOTSUPP);/* N Compression method not supported */
REGISTER_ZIP_CLASS_CONST_LONG("ER_EOF", ZIP_ER_EOF); /* N Premature EOF */
REGISTER_ZIP_CLASS_CONST_LONG("ER_INVAL", ZIP_ER_INVAL); /* N Invalid argument */
REGISTER_ZIP_CLASS_CONST_LONG("ER_NOZIP", ZIP_ER_NOZIP); /* N Not a zip archive */
REGISTER_ZIP_CLASS_CONST_LONG("ER_INTERNAL", ZIP_ER_INTERNAL); /* N Internal error */
REGISTER_ZIP_CLASS_CONST_LONG("ER_INCONS", ZIP_ER_INCONS); /* N Zip archive inconsistent */
REGISTER_ZIP_CLASS_CONST_LONG("ER_REMOVE", ZIP_ER_REMOVE); /* S Can't remove file */
REGISTER_ZIP_CLASS_CONST_LONG("ER_DELETED", ZIP_ER_DELETED); /* N Entry has been deleted */
php_register_url_stream_wrapper("zip", &php_stream_zip_wrapper TSRMLS_CC);
#endif
le_zip_dir = zend_register_list_destructors_ex(php_zip_free_dir, NULL, le_zip_dir_name, module_number);
le_zip_entry = zend_register_list_destructors_ex(php_zip_free_entry, NULL, le_zip_entry_name, module_number);
return SUCCESS;
}
| 167,023 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CtcpHandler::handleTime(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
Q_UNUSED(target)
if(ctcptype == CtcpQuery) {
if(_ignoreListManager->ctcpMatch(prefix, network()->networkName(), "TIME"))
return;
reply(nickFromMask(prefix), "TIME", QDateTime::currentDateTime().toString());
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME request by %1").arg(prefix));
}
else {
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME answer from %1: %2")
.arg(nickFromMask(prefix)).arg(param));
}
}
Commit Message:
CWE ID: CWE-399 | void CtcpHandler::handleTime(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
void CtcpHandler::handleTime(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m, QString &reply) {
Q_UNUSED(target)
if(ctcptype == CtcpQuery) {
reply = QDateTime::currentDateTime().toString();
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME request by %1").arg(prefix));
} else {
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME answer from %1: %2")
.arg(nickFromMask(prefix)).arg(param));
}
}
| 164,879 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp,
BIGNUM **rp)
{
BN_CTX *ctx;
BIGNUM k, kq, *K, *kinv = NULL, *r = NULL;
BIGNUM l, m;
int ret = 0;
int q_bits;
if (!dsa->p || !dsa->q || !dsa->g) {
DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_MISSING_PARAMETERS);
return 0;
}
BN_init(&k);
BN_init(&kq);
BN_init(&l);
BN_init(&m);
if (ctx_in == NULL) {
if ((ctx = BN_CTX_new()) == NULL)
goto err;
} else
ctx = ctx_in;
if ((r = BN_new()) == NULL)
goto err;
/* Preallocate space */
q_bits = BN_num_bits(dsa->q);
if (!BN_set_bit(&k, q_bits)
|| !BN_set_bit(&l, q_bits)
|| !BN_set_bit(&m, q_bits))
goto err;
/* Get random k */
do
if (!BN_rand_range(&k, dsa->q))
goto err;
while (BN_is_zero(&k));
if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {
BN_set_flags(&k, BN_FLG_CONSTTIME);
}
if (dsa->flags & DSA_FLAG_CACHE_MONT_P) {
if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p,
CRYPTO_LOCK_DSA, dsa->p, ctx))
goto err;
}
/* Compute r = (g^k mod p) mod q */
if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {
/*
* We do not want timing information to leak the length of k, so we
* compute G^k using an equivalent scalar of fixed bit-length.
*
* We unconditionally perform both of these additions to prevent a
* small timing information leakage. We then choose the sum that is
* one bit longer than the modulus.
*
* TODO: revisit the BN_copy aiming for a memory access agnostic
* conditional copy.
*/
if (!BN_add(&l, &k, dsa->q)
|| !BN_add(&m, &l, dsa->q)
|| !BN_copy(&kq, BN_num_bits(&l) > q_bits ? &l : &m))
goto err;
BN_set_flags(&kq, BN_FLG_CONSTTIME);
K = &kq;
} else {
K = &k;
}
DSA_BN_MOD_EXP(goto err, dsa, r, dsa->g, K, dsa->p, ctx,
dsa->method_mont_p);
if (!BN_mod(r, r, dsa->q, ctx))
goto err;
/* Compute part of 's = inv(k) (m + xr) mod q' */
if ((kinv = BN_mod_inverse(NULL, &k, dsa->q, ctx)) == NULL)
goto err;
if (*kinvp != NULL)
BN_clear_free(*kinvp);
*kinvp = kinv;
kinv = NULL;
if (*rp != NULL)
BN_clear_free(*rp);
*rp = r;
ret = 1;
err:
if (!ret) {
DSAerr(DSA_F_DSA_SIGN_SETUP, ERR_R_BN_LIB);
if (r != NULL)
BN_clear_free(r);
}
if (ctx_in == NULL)
BN_CTX_free(ctx);
BN_clear_free(&k);
BN_clear_free(&kq);
BN_clear_free(&l);
BN_clear_free(&m);
return ret;
}
Commit Message:
CWE ID: CWE-320 | static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp,
BIGNUM **rp)
{
BN_CTX *ctx;
BIGNUM k, kq, *K, *kinv = NULL, *r = NULL;
BIGNUM l, m;
int ret = 0;
int q_bits;
if (!dsa->p || !dsa->q || !dsa->g) {
DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_MISSING_PARAMETERS);
return 0;
}
BN_init(&k);
BN_init(&kq);
BN_init(&l);
BN_init(&m);
if (ctx_in == NULL) {
if ((ctx = BN_CTX_new()) == NULL)
goto err;
} else
ctx = ctx_in;
if ((r = BN_new()) == NULL)
goto err;
/* Preallocate space */
q_bits = BN_num_bits(dsa->q) + sizeof(dsa->q->d[0]) * 16;
if (!BN_set_bit(&k, q_bits)
|| !BN_set_bit(&l, q_bits)
|| !BN_set_bit(&m, q_bits))
goto err;
/* Get random k */
do
if (!BN_rand_range(&k, dsa->q))
goto err;
while (BN_is_zero(&k));
if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {
BN_set_flags(&k, BN_FLG_CONSTTIME);
}
if (dsa->flags & DSA_FLAG_CACHE_MONT_P) {
if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p,
CRYPTO_LOCK_DSA, dsa->p, ctx))
goto err;
}
/* Compute r = (g^k mod p) mod q */
if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {
/*
* We do not want timing information to leak the length of k, so we
* compute G^k using an equivalent scalar of fixed bit-length.
*
* We unconditionally perform both of these additions to prevent a
* small timing information leakage. We then choose the sum that is
* one bit longer than the modulus.
*
* TODO: revisit the BN_copy aiming for a memory access agnostic
* conditional copy.
*/
if (!BN_add(&l, &k, dsa->q)
|| !BN_add(&m, &l, dsa->q)
|| !BN_copy(&kq, BN_num_bits(&l) > q_bits ? &l : &m))
goto err;
BN_set_flags(&kq, BN_FLG_CONSTTIME);
K = &kq;
} else {
K = &k;
}
DSA_BN_MOD_EXP(goto err, dsa, r, dsa->g, K, dsa->p, ctx,
dsa->method_mont_p);
if (!BN_mod(r, r, dsa->q, ctx))
goto err;
/* Compute part of 's = inv(k) (m + xr) mod q' */
if ((kinv = BN_mod_inverse(NULL, &k, dsa->q, ctx)) == NULL)
goto err;
if (*kinvp != NULL)
BN_clear_free(*kinvp);
*kinvp = kinv;
kinv = NULL;
if (*rp != NULL)
BN_clear_free(*rp);
*rp = r;
ret = 1;
err:
if (!ret) {
DSAerr(DSA_F_DSA_SIGN_SETUP, ERR_R_BN_LIB);
if (r != NULL)
BN_clear_free(r);
}
if (ctx_in == NULL)
BN_CTX_free(ctx);
BN_clear_free(&k);
BN_clear_free(&kq);
BN_clear_free(&l);
BN_clear_free(&m);
return ret;
}
| 165,331 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, nbuf;
bool input_wakeup = false;
retry:
ret = ipipe_prep(ipipe, flags);
if (ret)
return ret;
ret = opipe_prep(opipe, flags);
if (ret)
return ret;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
if (!ipipe->nrbufs && !ipipe->writers)
break;
/*
* Cannot make any progress, because either the input
* pipe is empty or the output pipe is full.
*/
if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) {
/* Already processed some buffers, break */
if (ret)
break;
if (flags & SPLICE_F_NONBLOCK) {
ret = -EAGAIN;
break;
}
/*
* We raced with another reader/writer and haven't
* managed to process any buffers. A zero return
* value means EOF, so retry instead.
*/
pipe_unlock(ipipe);
pipe_unlock(opipe);
goto retry;
}
ibuf = ipipe->bufs + ipipe->curbuf;
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
obuf = opipe->bufs + nbuf;
if (len >= ibuf->len) {
/*
* Simply move the whole buffer from ipipe to opipe
*/
*obuf = *ibuf;
ibuf->ops = NULL;
opipe->nrbufs++;
ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1);
ipipe->nrbufs--;
input_wakeup = true;
} else {
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
pipe_buf_get(ipipe, ibuf);
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
pipe_buf_mark_unmergeable(obuf);
obuf->len = len;
opipe->nrbufs++;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
ret += obuf->len;
len -= obuf->len;
} while (len);
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
if (input_wakeup)
wakeup_pipe_writers(ipipe);
return ret;
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416 | static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, nbuf;
bool input_wakeup = false;
retry:
ret = ipipe_prep(ipipe, flags);
if (ret)
return ret;
ret = opipe_prep(opipe, flags);
if (ret)
return ret;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
if (!ipipe->nrbufs && !ipipe->writers)
break;
/*
* Cannot make any progress, because either the input
* pipe is empty or the output pipe is full.
*/
if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) {
/* Already processed some buffers, break */
if (ret)
break;
if (flags & SPLICE_F_NONBLOCK) {
ret = -EAGAIN;
break;
}
/*
* We raced with another reader/writer and haven't
* managed to process any buffers. A zero return
* value means EOF, so retry instead.
*/
pipe_unlock(ipipe);
pipe_unlock(opipe);
goto retry;
}
ibuf = ipipe->bufs + ipipe->curbuf;
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
obuf = opipe->bufs + nbuf;
if (len >= ibuf->len) {
/*
* Simply move the whole buffer from ipipe to opipe
*/
*obuf = *ibuf;
ibuf->ops = NULL;
opipe->nrbufs++;
ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1);
ipipe->nrbufs--;
input_wakeup = true;
} else {
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
if (!pipe_buf_get(ipipe, ibuf)) {
if (ret == 0)
ret = -EFAULT;
break;
}
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
pipe_buf_mark_unmergeable(obuf);
obuf->len = len;
opipe->nrbufs++;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
ret += obuf->len;
len -= obuf->len;
} while (len);
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
if (input_wakeup)
wakeup_pipe_writers(ipipe);
return ret;
}
| 170,220 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_emit_frobnicate (MyObject *obj, GError **error)
{
g_signal_emit (obj, signals[FROBNICATE], 0, 42);
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_emit_frobnicate (MyObject *obj, GError **error)
| 165,094 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 _out_verify(conn_t out, nad_t nad) {
int attr, ns;
jid_t from, to;
conn_t in;
char *rkey;
int valid;
attr = nad_find_attr(nad, 0, -1, "from", NULL);
if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid from on db verify packet");
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "to", NULL);
if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid to on db verify packet");
jid_free(from);
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "id", NULL);
if(attr < 0) {
log_debug(ZONE, "missing id on db verify packet");
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
/* get the incoming conn */
in = xhash_getx(out->s2s->in, NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr));
if(in == NULL) {
log_debug(ZONE, "got a verify for incoming conn %.*s, but it doesn't exist, dropping the packet", NAD_AVAL_L(nad, attr), NAD_AVAL(nad, attr));
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
rkey = s2s_route_key(NULL, to->domain, from->domain);
attr = nad_find_attr(nad, 0, -1, "type", "valid");
if(attr >= 0) {
xhash_put(in->states, pstrdup(xhash_pool(in->states), rkey), (void *) conn_VALID);
log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now valid%s%s", in->fd->fd, in->ip, in->port, rkey, (in->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", in->s->compressed ? ", ZLIB compression enabled" : "");
valid = 1;
} else {
log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now invalid", in->fd->fd, in->ip, in->port, rkey);
valid = 0;
}
free(rkey);
nad_free(nad);
/* decrement outstanding verify counter */
--out->verify;
/* let them know what happened */
nad = nad_new();
ns = nad_add_namespace(nad, uri_DIALBACK, "db");
nad_append_elem(nad, ns, "result", 0);
nad_append_attr(nad, -1, "to", from->domain);
nad_append_attr(nad, -1, "from", to->domain);
nad_append_attr(nad, -1, "type", valid ? "valid" : "invalid");
/* off it goes */
sx_nad_write(in->s, nad);
/* if invalid, close the stream */
if (!valid) {
/* generate stream error */
sx_error(in->s, stream_err_INVALID_ID, "dialback negotiation failed");
/* close the incoming stream */
sx_close(in->s);
}
jid_free(from);
jid_free(to);
}
Commit Message: Fixed possibility of Unsolicited Dialback Attacks
CWE ID: CWE-20 | static void _out_verify(conn_t out, nad_t nad) {
int attr, ns;
jid_t from, to;
conn_t in;
char *rkey;
int valid;
attr = nad_find_attr(nad, 0, -1, "from", NULL);
if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid from on db verify packet");
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "to", NULL);
if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid to on db verify packet");
jid_free(from);
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "id", NULL);
if(attr < 0) {
log_debug(ZONE, "missing id on db verify packet");
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
/* get the incoming conn */
in = xhash_getx(out->s2s->in, NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr));
if(in == NULL) {
log_debug(ZONE, "got a verify for incoming conn %.*s, but it doesn't exist, dropping the packet", NAD_AVAL_L(nad, attr), NAD_AVAL(nad, attr));
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
rkey = s2s_route_key(NULL, to->domain, from->domain);
attr = nad_find_attr(nad, 0, -1, "type", "valid");
if(attr >= 0 && xhash_get(in->states, rkey) == (void*) conn_INPROGRESS) {
xhash_put(in->states, pstrdup(xhash_pool(in->states), rkey), (void *) conn_VALID);
log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now valid%s%s", in->fd->fd, in->ip, in->port, rkey, (in->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", in->s->compressed ? ", ZLIB compression enabled" : "");
valid = 1;
} else {
log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now invalid", in->fd->fd, in->ip, in->port, rkey);
valid = 0;
}
free(rkey);
nad_free(nad);
/* decrement outstanding verify counter */
--out->verify;
/* let them know what happened */
nad = nad_new();
ns = nad_add_namespace(nad, uri_DIALBACK, "db");
nad_append_elem(nad, ns, "result", 0);
nad_append_attr(nad, -1, "to", from->domain);
nad_append_attr(nad, -1, "from", to->domain);
nad_append_attr(nad, -1, "type", valid ? "valid" : "invalid");
/* off it goes */
sx_nad_write(in->s, nad);
/* if invalid, close the stream */
if (!valid) {
/* generate stream error */
sx_error(in->s, stream_err_INVALID_ID, "dialback negotiation failed");
/* close the incoming stream */
sx_close(in->s);
}
jid_free(from);
jid_free(to);
}
| 165,577 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PluginModule::InitAsProxiedNaCl(
scoped_ptr<PluginDelegate::OutOfProcessProxy> out_of_process_proxy,
PP_Instance instance) {
nacl_ipc_proxy_ = true;
InitAsProxied(out_of_process_proxy.release());
out_of_process_proxy_->AddInstance(instance);
PluginInstance* plugin_instance = host_globals->GetInstance(instance);
if (!plugin_instance)
return;
plugin_instance->ResetAsProxied();
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void PluginModule::InitAsProxiedNaCl(
PluginDelegate::OutOfProcessProxy* out_of_process_proxy,
PP_Instance instance) {
InitAsProxied(out_of_process_proxy);
out_of_process_proxy_->AddInstance(instance);
PluginInstance* plugin_instance = host_globals->GetInstance(instance);
if (!plugin_instance)
return;
plugin_instance->ResetAsProxied();
}
| 170,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: void ThreadableBlobRegistry::addDataToStream(const KURL& url, PassRefPtr<RawData> streamData)
{
if (isMainThread()) {
blobRegistry().addDataToStream(url, streamData);
} else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, streamData));
callOnMainThread(&addDataToStreamTask, context.leakPtr());
}
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void ThreadableBlobRegistry::addDataToStream(const KURL& url, PassRefPtr<RawData> streamData)
void BlobRegistry::addDataToStream(const KURL& url, PassRefPtr<RawData> streamData)
{
if (isMainThread()) {
if (WebBlobRegistry* registry = blobRegistry()) {
WebThreadSafeData webThreadSafeData(streamData);
registry->addDataToStream(url, webThreadSafeData);
}
} else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, streamData));
callOnMainThread(&addDataToStreamTask, context.leakPtr());
}
}
| 170,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: static vpx_codec_err_t decoder_peek_si_internal(const uint8_t *data,
unsigned int data_sz,
vpx_codec_stream_info_t *si,
int *is_intra_only,
vpx_decrypt_cb decrypt_cb,
void *decrypt_state) {
int intra_only_flag = 0;
uint8_t clear_buffer[9];
if (data + data_sz <= data)
return VPX_CODEC_INVALID_PARAM;
si->is_kf = 0;
si->w = si->h = 0;
if (decrypt_cb) {
data_sz = VPXMIN(sizeof(clear_buffer), data_sz);
decrypt_cb(decrypt_state, data, clear_buffer, data_sz);
data = clear_buffer;
}
{
int show_frame;
int error_resilient;
struct vpx_read_bit_buffer rb = { data, data + data_sz, 0, NULL, NULL };
const int frame_marker = vpx_rb_read_literal(&rb, 2);
const BITSTREAM_PROFILE profile = vp9_read_profile(&rb);
if (frame_marker != VP9_FRAME_MARKER)
return VPX_CODEC_UNSUP_BITSTREAM;
if (profile >= MAX_PROFILES)
return VPX_CODEC_UNSUP_BITSTREAM;
if ((profile >= 2 && data_sz <= 1) || data_sz < 1)
return VPX_CODEC_UNSUP_BITSTREAM;
if (vpx_rb_read_bit(&rb)) { // show an existing frame
vpx_rb_read_literal(&rb, 3); // Frame buffer to show.
return VPX_CODEC_OK;
}
if (data_sz <= 8)
return VPX_CODEC_UNSUP_BITSTREAM;
si->is_kf = !vpx_rb_read_bit(&rb);
show_frame = vpx_rb_read_bit(&rb);
error_resilient = vpx_rb_read_bit(&rb);
if (si->is_kf) {
if (!vp9_read_sync_code(&rb))
return VPX_CODEC_UNSUP_BITSTREAM;
if (!parse_bitdepth_colorspace_sampling(profile, &rb))
return VPX_CODEC_UNSUP_BITSTREAM;
vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h);
} else {
intra_only_flag = show_frame ? 0 : vpx_rb_read_bit(&rb);
rb.bit_offset += error_resilient ? 0 : 2; // reset_frame_context
if (intra_only_flag) {
if (!vp9_read_sync_code(&rb))
return VPX_CODEC_UNSUP_BITSTREAM;
if (profile > PROFILE_0) {
if (!parse_bitdepth_colorspace_sampling(profile, &rb))
return VPX_CODEC_UNSUP_BITSTREAM;
}
rb.bit_offset += REF_FRAMES; // refresh_frame_flags
vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h);
}
}
}
if (is_intra_only != NULL)
*is_intra_only = intra_only_flag;
return VPX_CODEC_OK;
}
Commit Message: DO NOT MERGE | libvpx: cherry-pick aa1c813 from upstream
Description from upstream:
vp9: Fix potential SEGV in decoder_peek_si_internal
decoder_peek_si_internal could potentially read more bytes than
what actually exists in the input buffer. We check for the buffer
size to be at least 8, but we try to read up to 10 bytes in the
worst case. A well crafted file could thus cause a segfault.
Likely change that introduced this bug was:
https://chromium-review.googlesource.com/#/c/70439 (git hash:
7c43fb6)
Bug: 30013856
Change-Id: If556414cb5b82472d5673e045bc185cc57bb9af3
(cherry picked from commit bd57d587c2eb743c61b049add18f9fd72bf78c33)
CWE ID: CWE-119 | static vpx_codec_err_t decoder_peek_si_internal(const uint8_t *data,
unsigned int data_sz,
vpx_codec_stream_info_t *si,
int *is_intra_only,
vpx_decrypt_cb decrypt_cb,
void *decrypt_state) {
int intra_only_flag = 0;
uint8_t clear_buffer[10];
if (data + data_sz <= data)
return VPX_CODEC_INVALID_PARAM;
si->is_kf = 0;
si->w = si->h = 0;
if (decrypt_cb) {
data_sz = VPXMIN(sizeof(clear_buffer), data_sz);
decrypt_cb(decrypt_state, data, clear_buffer, data_sz);
data = clear_buffer;
}
// A maximum of 6 bits are needed to read the frame marker, profile and
// show_existing_frame.
if (data_sz < 1)
return VPX_CODEC_UNSUP_BITSTREAM;
{
int show_frame;
int error_resilient;
struct vpx_read_bit_buffer rb = { data, data + data_sz, 0, NULL, NULL };
const int frame_marker = vpx_rb_read_literal(&rb, 2);
const BITSTREAM_PROFILE profile = vp9_read_profile(&rb);
if (frame_marker != VP9_FRAME_MARKER)
return VPX_CODEC_UNSUP_BITSTREAM;
if (profile >= MAX_PROFILES)
return VPX_CODEC_UNSUP_BITSTREAM;
if (vpx_rb_read_bit(&rb)) { // show an existing frame
// If profile is > 2 and show_existing_frame is true, then at least 1 more
// byte (6+3=9 bits) is needed.
if (profile > 2 && data_sz < 2)
return VPX_CODEC_UNSUP_BITSTREAM;
vpx_rb_read_literal(&rb, 3); // Frame buffer to show.
return VPX_CODEC_OK;
}
// For the rest of the function, a maximum of 9 more bytes are needed
// (computed by taking the maximum possible bits needed in each case). Note
// that this has to be updated if we read any more bits in this function.
if (data_sz < 10)
return VPX_CODEC_UNSUP_BITSTREAM;
si->is_kf = !vpx_rb_read_bit(&rb);
show_frame = vpx_rb_read_bit(&rb);
error_resilient = vpx_rb_read_bit(&rb);
if (si->is_kf) {
if (!vp9_read_sync_code(&rb))
return VPX_CODEC_UNSUP_BITSTREAM;
if (!parse_bitdepth_colorspace_sampling(profile, &rb))
return VPX_CODEC_UNSUP_BITSTREAM;
vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h);
} else {
intra_only_flag = show_frame ? 0 : vpx_rb_read_bit(&rb);
rb.bit_offset += error_resilient ? 0 : 2; // reset_frame_context
if (intra_only_flag) {
if (!vp9_read_sync_code(&rb))
return VPX_CODEC_UNSUP_BITSTREAM;
if (profile > PROFILE_0) {
if (!parse_bitdepth_colorspace_sampling(profile, &rb))
return VPX_CODEC_UNSUP_BITSTREAM;
}
rb.bit_offset += REF_FRAMES; // refresh_frame_flags
vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h);
}
}
}
if (is_intra_only != NULL)
*is_intra_only = intra_only_flag;
return VPX_CODEC_OK;
}
| 173,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 FetchManager::Loader::Start() {
if (!ContentSecurityPolicy::ShouldBypassMainWorld(execution_context_) &&
!execution_context_->GetContentSecurityPolicy()->AllowConnectToSource(
fetch_request_data_->Url())) {
PerformNetworkError(
"Refused to connect to '" + fetch_request_data_->Url().ElidedString() +
"' because it violates the document's Content Security Policy.");
return;
}
if ((SecurityOrigin::Create(fetch_request_data_->Url())
->IsSameSchemeHostPort(fetch_request_data_->Origin().get())) ||
(fetch_request_data_->Url().ProtocolIsData() &&
fetch_request_data_->SameOriginDataURLFlag()) ||
(fetch_request_data_->Mode() == FetchRequestMode::kNavigate)) {
PerformSchemeFetch();
return;
}
if (fetch_request_data_->Mode() == FetchRequestMode::kSameOrigin) {
PerformNetworkError("Fetch API cannot load " +
fetch_request_data_->Url().GetString() +
". Request mode is \"same-origin\" but the URL\'s "
"origin is not same as the request origin " +
fetch_request_data_->Origin()->ToString() + ".");
return;
}
if (fetch_request_data_->Mode() == FetchRequestMode::kNoCORS) {
fetch_request_data_->SetResponseTainting(FetchRequestData::kOpaqueTainting);
PerformSchemeFetch();
return;
}
if (!SchemeRegistry::ShouldTreatURLSchemeAsSupportingFetchAPI(
fetch_request_data_->Url().Protocol())) {
PerformNetworkError(
"Fetch API cannot load " + fetch_request_data_->Url().GetString() +
". URL scheme must be \"http\" or \"https\" for CORS request.");
return;
}
fetch_request_data_->SetResponseTainting(FetchRequestData::kCORSTainting);
PerformHTTPFetch();
}
Commit Message: [Fetch API] Fix redirect leak on "no-cors" requests
The spec issue is now fixed, and this CL follows the spec change[1].
1: https://github.com/whatwg/fetch/commit/14858d3e9402285a7ff3b5e47a22896ff3adc95d
Bug: 791324
Change-Id: Ic3e3955f43578b38fc44a5a6b2a1b43d56a2becb
Reviewed-on: https://chromium-review.googlesource.com/1023613
Reviewed-by: Tsuyoshi Horo <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#552964}
CWE ID: CWE-200 | void FetchManager::Loader::Start() {
if (!ContentSecurityPolicy::ShouldBypassMainWorld(execution_context_) &&
!execution_context_->GetContentSecurityPolicy()->AllowConnectToSource(
fetch_request_data_->Url())) {
PerformNetworkError(
"Refused to connect to '" + fetch_request_data_->Url().ElidedString() +
"' because it violates the document's Content Security Policy.");
return;
}
if ((SecurityOrigin::Create(fetch_request_data_->Url())
->IsSameSchemeHostPort(fetch_request_data_->Origin().get())) ||
(fetch_request_data_->Url().ProtocolIsData() &&
fetch_request_data_->SameOriginDataURLFlag()) ||
(fetch_request_data_->Mode() == FetchRequestMode::kNavigate)) {
PerformSchemeFetch();
return;
}
if (fetch_request_data_->Mode() == FetchRequestMode::kSameOrigin) {
PerformNetworkError("Fetch API cannot load " +
fetch_request_data_->Url().GetString() +
". Request mode is \"same-origin\" but the URL\'s "
"origin is not same as the request origin " +
fetch_request_data_->Origin()->ToString() + ".");
return;
}
if (fetch_request_data_->Mode() == FetchRequestMode::kNoCORS) {
// "If |request|'s redirect mode is not |follow|, then return a network
// error.
if (fetch_request_data_->Redirect() != FetchRedirectMode::kFollow) {
PerformNetworkError("Fetch API cannot load " +
fetch_request_data_->Url().GetString() +
". Request mode is \"no-cors\" but the redirect mode "
" is not \"follow\".");
return;
}
fetch_request_data_->SetResponseTainting(FetchRequestData::kOpaqueTainting);
PerformSchemeFetch();
return;
}
if (!SchemeRegistry::ShouldTreatURLSchemeAsSupportingFetchAPI(
fetch_request_data_->Url().Protocol())) {
PerformNetworkError(
"Fetch API cannot load " + fetch_request_data_->Url().GetString() +
". URL scheme must be \"http\" or \"https\" for CORS request.");
return;
}
fetch_request_data_->SetResponseTainting(FetchRequestData::kCORSTainting);
PerformHTTPFetch();
}
| 173,166 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::unique_ptr<HistogramBase> PersistentHistogramAllocator::AllocateHistogram(
HistogramType histogram_type,
const std::string& name,
int minimum,
int maximum,
const BucketRanges* bucket_ranges,
int32_t flags,
Reference* ref_ptr) {
if (memory_allocator_->IsCorrupt()) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_ALLOCATOR_CORRUPT);
return nullptr;
}
PersistentHistogramData* histogram_data =
memory_allocator_->New<PersistentHistogramData>(
offsetof(PersistentHistogramData, name) + name.length() + 1);
if (histogram_data) {
memcpy(histogram_data->name, name.c_str(), name.size() + 1);
histogram_data->histogram_type = histogram_type;
histogram_data->flags = flags | HistogramBase::kIsPersistent;
}
if (histogram_type != SPARSE_HISTOGRAM) {
size_t bucket_count = bucket_ranges->bucket_count();
size_t counts_bytes = CalculateRequiredCountsBytes(bucket_count);
if (counts_bytes == 0) {
NOTREACHED();
return nullptr;
}
DCHECK_EQ(this, GlobalHistogramAllocator::Get());
PersistentMemoryAllocator::Reference ranges_ref =
bucket_ranges->persistent_reference();
if (!ranges_ref) {
size_t ranges_count = bucket_count + 1;
size_t ranges_bytes = ranges_count * sizeof(HistogramBase::Sample);
ranges_ref =
memory_allocator_->Allocate(ranges_bytes, kTypeIdRangesArray);
if (ranges_ref) {
HistogramBase::Sample* ranges_data =
memory_allocator_->GetAsArray<HistogramBase::Sample>(
ranges_ref, kTypeIdRangesArray, ranges_count);
if (ranges_data) {
for (size_t i = 0; i < bucket_ranges->size(); ++i)
ranges_data[i] = bucket_ranges->range(i);
bucket_ranges->set_persistent_reference(ranges_ref);
} else {
NOTREACHED();
ranges_ref = PersistentMemoryAllocator::kReferenceNull;
}
}
} else {
DCHECK_EQ(kTypeIdRangesArray, memory_allocator_->GetType(ranges_ref));
}
if (ranges_ref && histogram_data) {
histogram_data->minimum = minimum;
histogram_data->maximum = maximum;
histogram_data->bucket_count = static_cast<uint32_t>(bucket_count);
histogram_data->ranges_ref = ranges_ref;
histogram_data->ranges_checksum = bucket_ranges->checksum();
} else {
histogram_data = nullptr; // Clear this for proper handling below.
}
}
if (histogram_data) {
std::unique_ptr<HistogramBase> histogram = CreateHistogram(histogram_data);
DCHECK(histogram);
DCHECK_NE(0U, histogram_data->samples_metadata.id);
DCHECK_NE(0U, histogram_data->logged_metadata.id);
PersistentMemoryAllocator::Reference histogram_ref =
memory_allocator_->GetAsReference(histogram_data);
if (ref_ptr != nullptr)
*ref_ptr = histogram_ref;
subtle::NoBarrier_Store(&last_created_, histogram_ref);
return histogram;
}
CreateHistogramResultType result;
if (memory_allocator_->IsCorrupt()) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_ALLOCATOR_NEWLY_CORRUPT);
result = CREATE_HISTOGRAM_ALLOCATOR_CORRUPT;
} else if (memory_allocator_->IsFull()) {
result = CREATE_HISTOGRAM_ALLOCATOR_FULL;
} else {
result = CREATE_HISTOGRAM_ALLOCATOR_ERROR;
}
RecordCreateHistogramResult(result);
if (result != CREATE_HISTOGRAM_ALLOCATOR_FULL)
NOTREACHED() << memory_allocator_->Name() << ", error=" << result;
return nullptr;
}
Commit Message: Remove UMA.CreatePersistentHistogram.Result
This histogram isn't showing anything meaningful and the problems it
could show are better observed by looking at the allocators directly.
Bug: 831013
Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9
Reviewed-on: https://chromium-review.googlesource.com/1008047
Commit-Queue: Brian White <[email protected]>
Reviewed-by: Alexei Svitkine <[email protected]>
Cr-Commit-Position: refs/heads/master@{#549986}
CWE ID: CWE-264 | std::unique_ptr<HistogramBase> PersistentHistogramAllocator::AllocateHistogram(
HistogramType histogram_type,
const std::string& name,
int minimum,
int maximum,
const BucketRanges* bucket_ranges,
int32_t flags,
Reference* ref_ptr) {
if (memory_allocator_->IsCorrupt())
return nullptr;
PersistentHistogramData* histogram_data =
memory_allocator_->New<PersistentHistogramData>(
offsetof(PersistentHistogramData, name) + name.length() + 1);
if (histogram_data) {
memcpy(histogram_data->name, name.c_str(), name.size() + 1);
histogram_data->histogram_type = histogram_type;
histogram_data->flags = flags | HistogramBase::kIsPersistent;
}
if (histogram_type != SPARSE_HISTOGRAM) {
size_t bucket_count = bucket_ranges->bucket_count();
size_t counts_bytes = CalculateRequiredCountsBytes(bucket_count);
if (counts_bytes == 0) {
NOTREACHED();
return nullptr;
}
DCHECK_EQ(this, GlobalHistogramAllocator::Get());
PersistentMemoryAllocator::Reference ranges_ref =
bucket_ranges->persistent_reference();
if (!ranges_ref) {
size_t ranges_count = bucket_count + 1;
size_t ranges_bytes = ranges_count * sizeof(HistogramBase::Sample);
ranges_ref =
memory_allocator_->Allocate(ranges_bytes, kTypeIdRangesArray);
if (ranges_ref) {
HistogramBase::Sample* ranges_data =
memory_allocator_->GetAsArray<HistogramBase::Sample>(
ranges_ref, kTypeIdRangesArray, ranges_count);
if (ranges_data) {
for (size_t i = 0; i < bucket_ranges->size(); ++i)
ranges_data[i] = bucket_ranges->range(i);
bucket_ranges->set_persistent_reference(ranges_ref);
} else {
NOTREACHED();
ranges_ref = PersistentMemoryAllocator::kReferenceNull;
}
}
} else {
DCHECK_EQ(kTypeIdRangesArray, memory_allocator_->GetType(ranges_ref));
}
if (ranges_ref && histogram_data) {
histogram_data->minimum = minimum;
histogram_data->maximum = maximum;
histogram_data->bucket_count = static_cast<uint32_t>(bucket_count);
histogram_data->ranges_ref = ranges_ref;
histogram_data->ranges_checksum = bucket_ranges->checksum();
} else {
histogram_data = nullptr; // Clear this for proper handling below.
}
}
if (histogram_data) {
std::unique_ptr<HistogramBase> histogram = CreateHistogram(histogram_data);
DCHECK(histogram);
DCHECK_NE(0U, histogram_data->samples_metadata.id);
DCHECK_NE(0U, histogram_data->logged_metadata.id);
PersistentMemoryAllocator::Reference histogram_ref =
memory_allocator_->GetAsReference(histogram_data);
if (ref_ptr != nullptr)
*ref_ptr = histogram_ref;
subtle::NoBarrier_Store(&last_created_, histogram_ref);
return histogram;
}
if (memory_allocator_->IsCorrupt())
NOTREACHED() << memory_allocator_->Name() << " is corrupt!";
return nullptr;
}
| 172,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: HeapVector<NotificationAction> Notification::actions() const
{
HeapVector<NotificationAction> actions;
actions.grow(m_data.actions.size());
for (size_t i = 0; i < m_data.actions.size(); ++i) {
actions[i].setAction(m_data.actions[i].action);
actions[i].setTitle(m_data.actions[i].title);
}
return actions;
}
Commit Message: Notification actions may have an icon url.
This is behind a runtime flag for two reasons:
* The implementation is incomplete.
* We're still evaluating the API design.
Intent to Implement and Ship: Notification Action Icons
https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ
BUG=581336
Review URL: https://codereview.chromium.org/1644573002
Cr-Commit-Position: refs/heads/master@{#374649}
CWE ID: | HeapVector<NotificationAction> Notification::actions() const
{
HeapVector<NotificationAction> actions;
actions.grow(m_data.actions.size());
for (size_t i = 0; i < m_data.actions.size(); ++i) {
actions[i].setAction(m_data.actions[i].action);
actions[i].setTitle(m_data.actions[i].title);
actions[i].setIcon(m_data.actions[i].icon.string());
}
return actions;
}
| 171,633 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ff_mms_asf_header_parser(MMSContext *mms)
{
uint8_t *p = mms->asf_header;
uint8_t *end;
int flags, stream_id;
mms->stream_num = 0;
if (mms->asf_header_size < sizeof(ff_asf_guid) * 2 + 22 ||
memcmp(p, ff_asf_header, sizeof(ff_asf_guid))) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (invalid ASF header, size=%d)\n",
mms->asf_header_size);
return AVERROR_INVALIDDATA;
}
end = mms->asf_header + mms->asf_header_size;
p += sizeof(ff_asf_guid) + 14;
while(end - p >= sizeof(ff_asf_guid) + 8) {
uint64_t chunksize;
if (!memcmp(p, ff_asf_data_header, sizeof(ff_asf_guid))) {
chunksize = 50; // see Reference [2] section 5.1
} else {
chunksize = AV_RL64(p + sizeof(ff_asf_guid));
}
if (!chunksize || chunksize > end - p) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (header chunksize %"PRId64" is invalid)\n",
chunksize);
return AVERROR_INVALIDDATA;
}
if (!memcmp(p, ff_asf_file_header, sizeof(ff_asf_guid))) {
/* read packet size */
if (end - p > sizeof(ff_asf_guid) * 2 + 68) {
mms->asf_packet_len = AV_RL32(p + sizeof(ff_asf_guid) * 2 + 64);
if (mms->asf_packet_len <= 0 || mms->asf_packet_len > sizeof(mms->in_buffer)) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (too large pkt_len %d)\n",
mms->asf_packet_len);
return AVERROR_INVALIDDATA;
}
}
} else if (!memcmp(p, ff_asf_stream_header, sizeof(ff_asf_guid))) {
flags = AV_RL16(p + sizeof(ff_asf_guid)*3 + 24);
stream_id = flags & 0x7F;
if (mms->stream_num < MMS_MAX_STREAMS &&
46 + mms->stream_num * 6 < sizeof(mms->out_buffer)) {
mms->streams = av_fast_realloc(mms->streams,
&mms->nb_streams_allocated,
(mms->stream_num + 1) * sizeof(MMSStream));
if (!mms->streams)
return AVERROR(ENOMEM);
mms->streams[mms->stream_num].id = stream_id;
mms->stream_num++;
} else {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (too many A/V streams)\n");
return AVERROR_INVALIDDATA;
}
} else if (!memcmp(p, ff_asf_ext_stream_header, sizeof(ff_asf_guid))) {
if (end - p >= 88) {
int stream_count = AV_RL16(p + 84), ext_len_count = AV_RL16(p + 86);
uint64_t skip_bytes = 88;
while (stream_count--) {
if (end - p < skip_bytes + 4) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (next stream name length is not in the buffer)\n");
return AVERROR_INVALIDDATA;
}
skip_bytes += 4 + AV_RL16(p + skip_bytes + 2);
}
while (ext_len_count--) {
if (end - p < skip_bytes + 22) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (next extension system info length is not in the buffer)\n");
return AVERROR_INVALIDDATA;
}
skip_bytes += 22 + AV_RL32(p + skip_bytes + 18);
}
if (end - p < skip_bytes) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (the last extension system info length is invalid)\n");
return AVERROR_INVALIDDATA;
}
if (chunksize - skip_bytes > 24)
chunksize = skip_bytes;
}
} else if (!memcmp(p, ff_asf_head1_guid, sizeof(ff_asf_guid))) {
chunksize = 46; // see references [2] section 3.4. This should be set 46.
}
p += chunksize;
}
return 0;
}
Commit Message: avformat/mms: Add missing chunksize check
Fixes: out of array read
Fixes: mms-crash-01b6c5d85f9d9f40f4e879896103e9f5b222816a
Found-by: Paul Ch <[email protected]>
1st hunk by Paul Ch <[email protected]>
Tested-by: Paul Ch <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-125 | int ff_mms_asf_header_parser(MMSContext *mms)
{
uint8_t *p = mms->asf_header;
uint8_t *end;
int flags, stream_id;
mms->stream_num = 0;
if (mms->asf_header_size < sizeof(ff_asf_guid) * 2 + 22 ||
memcmp(p, ff_asf_header, sizeof(ff_asf_guid))) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (invalid ASF header, size=%d)\n",
mms->asf_header_size);
return AVERROR_INVALIDDATA;
}
end = mms->asf_header + mms->asf_header_size;
p += sizeof(ff_asf_guid) + 14;
while(end - p >= sizeof(ff_asf_guid) + 8) {
uint64_t chunksize;
if (!memcmp(p, ff_asf_data_header, sizeof(ff_asf_guid))) {
chunksize = 50; // see Reference [2] section 5.1
} else {
chunksize = AV_RL64(p + sizeof(ff_asf_guid));
}
if (!chunksize || chunksize > end - p) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (header chunksize %"PRId64" is invalid)\n",
chunksize);
return AVERROR_INVALIDDATA;
}
if (!memcmp(p, ff_asf_file_header, sizeof(ff_asf_guid))) {
/* read packet size */
if (end - p > sizeof(ff_asf_guid) * 2 + 68) {
mms->asf_packet_len = AV_RL32(p + sizeof(ff_asf_guid) * 2 + 64);
if (mms->asf_packet_len <= 0 || mms->asf_packet_len > sizeof(mms->in_buffer)) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (too large pkt_len %d)\n",
mms->asf_packet_len);
return AVERROR_INVALIDDATA;
}
}
} else if (!memcmp(p, ff_asf_stream_header, sizeof(ff_asf_guid))) {
if (end - p >= (sizeof(ff_asf_guid) * 3 + 26)) {
flags = AV_RL16(p + sizeof(ff_asf_guid)*3 + 24);
stream_id = flags & 0x7F;
//The second condition is for checking CS_PKT_STREAM_ID_REQUEST packet size,
//we can calculate the packet size by stream_num.
//Please see function send_stream_selection_request().
if (mms->stream_num < MMS_MAX_STREAMS &&
46 + mms->stream_num * 6 < sizeof(mms->out_buffer)) {
mms->streams = av_fast_realloc(mms->streams,
&mms->nb_streams_allocated,
(mms->stream_num + 1) * sizeof(MMSStream));
if (!mms->streams)
return AVERROR(ENOMEM);
mms->streams[mms->stream_num].id = stream_id;
mms->stream_num++;
} else {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (too many A/V streams)\n");
return AVERROR_INVALIDDATA;
}
}
} else if (!memcmp(p, ff_asf_ext_stream_header, sizeof(ff_asf_guid))) {
if (end - p >= 88) {
int stream_count = AV_RL16(p + 84), ext_len_count = AV_RL16(p + 86);
uint64_t skip_bytes = 88;
while (stream_count--) {
if (end - p < skip_bytes + 4) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (next stream name length is not in the buffer)\n");
return AVERROR_INVALIDDATA;
}
skip_bytes += 4 + AV_RL16(p + skip_bytes + 2);
}
while (ext_len_count--) {
if (end - p < skip_bytes + 22) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (next extension system info length is not in the buffer)\n");
return AVERROR_INVALIDDATA;
}
skip_bytes += 22 + AV_RL32(p + skip_bytes + 18);
}
if (end - p < skip_bytes) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (the last extension system info length is invalid)\n");
return AVERROR_INVALIDDATA;
}
if (chunksize - skip_bytes > 24)
chunksize = skip_bytes;
}
} else if (!memcmp(p, ff_asf_head1_guid, sizeof(ff_asf_guid))) {
chunksize = 46; // see references [2] section 3.4. This should be set 46.
if (chunksize > end - p) {
av_log(NULL, AV_LOG_ERROR,
"Corrupt stream (header chunksize %"PRId64" is invalid)\n",
chunksize);
return AVERROR_INVALIDDATA;
}
}
p += chunksize;
}
return 0;
}
| 168,927 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: jbig2_end_of_stripe(Jbig2Ctx *ctx, Jbig2Segment *segment, const uint8_t *segment_data)
{
Jbig2Page page = ctx->pages[ctx->current_page];
int end_row;
end_row = jbig2_get_int32(segment_data);
if (end_row < page.end_row) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number,
"end of stripe segment with non-positive end row advance" " (new end row %d vs current end row %d)", end_row, page.end_row);
} else {
jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "end of stripe: advancing end row to %d", end_row);
}
page.end_row = end_row;
return 0;
}
Commit Message:
CWE ID: CWE-119 | jbig2_end_of_stripe(Jbig2Ctx *ctx, Jbig2Segment *segment, const uint8_t *segment_data)
{
Jbig2Page page = ctx->pages[ctx->current_page];
uint32_t end_row;
end_row = jbig2_get_uint32(segment_data);
if (end_row < page.end_row) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number,
"end of stripe segment with non-positive end row advance" " (new end row %d vs current end row %d)", end_row, page.end_row);
} else {
jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "end of stripe: advancing end row to %d", end_row);
}
page.end_row = end_row;
return 0;
}
| 165,495 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_read_mmco_commands(struct _DecStruct * ps_dec)
{
dec_bit_stream_t *ps_bitstrm = ps_dec->ps_bitstrm;
dpb_commands_t *ps_dpb_cmds = ps_dec->ps_dpb_cmds;
dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice;
WORD32 j;
UWORD8 u1_buf_mode;
struct MMCParams *ps_mmc_params;
UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
UWORD32 u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst;
ps_slice->u1_mmco_equalto5 = 0;
{
if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL)
{
ps_slice->u1_no_output_of_prior_pics_flag =
ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: no_output_of_prior_pics_flag",
ps_slice->u1_no_output_of_prior_pics_flag);
ps_slice->u1_long_term_reference_flag = ih264d_get_bit_h264(
ps_bitstrm);
COPYTHECONTEXT("SH: long_term_reference_flag",
ps_slice->u1_long_term_reference_flag);
ps_dpb_cmds->u1_idr_pic = 1;
ps_dpb_cmds->u1_no_output_of_prior_pics_flag =
ps_slice->u1_no_output_of_prior_pics_flag;
ps_dpb_cmds->u1_long_term_reference_flag =
ps_slice->u1_long_term_reference_flag;
}
else
{
u1_buf_mode = ih264d_get_bit_h264(ps_bitstrm); //0 - sliding window; 1 - arbitrary
COPYTHECONTEXT("SH: adaptive_ref_pic_buffering_flag", u1_buf_mode);
ps_dpb_cmds->u1_buf_mode = u1_buf_mode;
j = 0;
if(u1_buf_mode == 1)
{
UWORD32 u4_mmco;
UWORD32 u4_diff_pic_num;
UWORD32 u4_lt_idx, u4_max_lt_idx;
u4_mmco = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
while(u4_mmco != END_OF_MMCO)
{
if (j >= MAX_REF_BUFS)
{
#ifdef __ANDROID__
ALOGE("b/25818142");
android_errorWriteLog(0x534e4554, "25818142");
#endif
ps_dpb_cmds->u1_num_of_commands = 0;
return -1;
}
ps_mmc_params = &ps_dpb_cmds->as_mmc_params[j];
ps_mmc_params->u4_mmco = u4_mmco;
switch(u4_mmco)
{
case MARK_ST_PICNUM_AS_NONREF:
u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num;
break;
case MARK_LT_INDEX_AS_NONREF:
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
case MARK_ST_PICNUM_AS_LT_INDEX:
u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num;
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
case SET_MAX_LT_INDEX:
{
u4_max_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_max_lt_idx_plus1 = u4_max_lt_idx;
break;
}
case RESET_REF_PICTURES:
{
ps_slice->u1_mmco_equalto5 = 1;
break;
}
case SET_LT_INDEX:
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
default:
break;
}
u4_mmco = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
j++;
}
ps_dpb_cmds->u1_num_of_commands = j;
}
}
ps_dpb_cmds->u1_dpb_commands_read = 1;
ps_dpb_cmds->u1_dpb_commands_read_slc = 1;
}
u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst - u4_bit_ofst;
return u4_bit_ofst;
}
Commit Message: Decoder: Fixed incorrect use of mmco parameters.
Added extra structure to read mmco values and copied only once per
picture.
Bug: 65735716
Change-Id: I25b08a37bc78342042c52957774b089abce1a54b
(cherry picked from commit 3c70b9a190875938fc57164d9295a3ec791554df)
CWE ID: CWE-20 | WORD32 ih264d_read_mmco_commands(struct _DecStruct * ps_dec)
{
dec_bit_stream_t *ps_bitstrm = ps_dec->ps_bitstrm;
dpb_commands_t *ps_dpb_cmds = &(ps_dec->s_dpb_cmds_scratch);
dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice;
WORD32 j;
UWORD8 u1_buf_mode;
struct MMCParams *ps_mmc_params;
UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
UWORD32 u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst;
ps_slice->u1_mmco_equalto5 = 0;
{
if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL)
{
ps_slice->u1_no_output_of_prior_pics_flag =
ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: no_output_of_prior_pics_flag",
ps_slice->u1_no_output_of_prior_pics_flag);
ps_slice->u1_long_term_reference_flag = ih264d_get_bit_h264(
ps_bitstrm);
COPYTHECONTEXT("SH: long_term_reference_flag",
ps_slice->u1_long_term_reference_flag);
ps_dpb_cmds->u1_idr_pic = 1;
ps_dpb_cmds->u1_no_output_of_prior_pics_flag =
ps_slice->u1_no_output_of_prior_pics_flag;
ps_dpb_cmds->u1_long_term_reference_flag =
ps_slice->u1_long_term_reference_flag;
}
else
{
u1_buf_mode = ih264d_get_bit_h264(ps_bitstrm); //0 - sliding window; 1 - arbitrary
COPYTHECONTEXT("SH: adaptive_ref_pic_buffering_flag", u1_buf_mode);
ps_dpb_cmds->u1_buf_mode = u1_buf_mode;
j = 0;
if(u1_buf_mode == 1)
{
UWORD32 u4_mmco;
UWORD32 u4_diff_pic_num;
UWORD32 u4_lt_idx, u4_max_lt_idx;
u4_mmco = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
while(u4_mmco != END_OF_MMCO)
{
if (j >= MAX_REF_BUFS)
{
#ifdef __ANDROID__
ALOGE("b/25818142");
android_errorWriteLog(0x534e4554, "25818142");
#endif
ps_dpb_cmds->u1_num_of_commands = 0;
return -1;
}
ps_mmc_params = &ps_dpb_cmds->as_mmc_params[j];
ps_mmc_params->u4_mmco = u4_mmco;
switch(u4_mmco)
{
case MARK_ST_PICNUM_AS_NONREF:
u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num;
break;
case MARK_LT_INDEX_AS_NONREF:
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
case MARK_ST_PICNUM_AS_LT_INDEX:
u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num;
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
case SET_MAX_LT_INDEX:
{
u4_max_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_max_lt_idx_plus1 = u4_max_lt_idx;
break;
}
case RESET_REF_PICTURES:
{
ps_slice->u1_mmco_equalto5 = 1;
break;
}
case SET_LT_INDEX:
u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
ps_mmc_params->u4_lt_idx = u4_lt_idx;
break;
default:
break;
}
u4_mmco = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
j++;
}
ps_dpb_cmds->u1_num_of_commands = j;
}
}
ps_dpb_cmds->u1_dpb_commands_read = 1;
ps_dpb_cmds->u1_dpb_commands_read_slc = 1;
}
u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst - u4_bit_ofst;
return u4_bit_ofst;
}
| 174,116 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftAACEncoder2::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_encoder.aac",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPortFormat:
{
const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
if ((formatParams->nPortIndex == 0
&& formatParams->eEncoding != OMX_AUDIO_CodingPCM)
|| (formatParams->nPortIndex == 1
&& formatParams->eEncoding != OMX_AUDIO_CodingAAC)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAac:
{
OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (aacParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mBitRate = aacParams->nBitRate;
mNumChannels = aacParams->nChannels;
mSampleRate = aacParams->nSampleRate;
if (aacParams->eAACProfile != OMX_AUDIO_AACObjectNull) {
mAACProfile = aacParams->eAACProfile;
}
if (!(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR)
&& !(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) {
mSBRMode = 0;
mSBRRatio = 0;
} else if ((aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR)
&& !(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) {
mSBRMode = 1;
mSBRRatio = 1;
} else if (!(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR)
&& (aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) {
mSBRMode = 1;
mSBRRatio = 2;
} else {
mSBRMode = -1; // codec default sbr mode
mSBRRatio = 0;
}
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
mNumChannels = pcmParams->nChannels;
mSampleRate = pcmParams->nSamplingRate;
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftAACEncoder2::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (strncmp((const char *)roleParams->cRole,
"audio_encoder.aac",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPortFormat:
{
const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (!isValidOMXParam(formatParams)) {
return OMX_ErrorBadParameter;
}
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
if ((formatParams->nPortIndex == 0
&& formatParams->eEncoding != OMX_AUDIO_CodingPCM)
|| (formatParams->nPortIndex == 1
&& formatParams->eEncoding != OMX_AUDIO_CodingAAC)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAac:
{
OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (!isValidOMXParam(aacParams)) {
return OMX_ErrorBadParameter;
}
if (aacParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mBitRate = aacParams->nBitRate;
mNumChannels = aacParams->nChannels;
mSampleRate = aacParams->nSampleRate;
if (aacParams->eAACProfile != OMX_AUDIO_AACObjectNull) {
mAACProfile = aacParams->eAACProfile;
}
if (!(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR)
&& !(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) {
mSBRMode = 0;
mSBRRatio = 0;
} else if ((aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR)
&& !(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) {
mSBRMode = 1;
mSBRRatio = 1;
} else if (!(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR)
&& (aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) {
mSBRMode = 1;
mSBRRatio = 2;
} else {
mSBRMode = -1; // codec default sbr mode
mSBRRatio = 0;
}
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
mNumChannels = pcmParams->nChannels;
mSampleRate = pcmParams->nSamplingRate;
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,191 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: path_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
PATH *path;
int isopen;
char *s;
int npts;
int size;
int depth = 0;
if ((npts = pair_count(str, ',')) <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type path: \"%s\"", str)));
s = str;
while (isspace((unsigned char) *s))
s++;
/* skip single leading paren */
if ((*s == LDELIM) && (strrchr(s, LDELIM) == s))
{
s++;
depth++;
}
size = offsetof(PATH, p[0]) +sizeof(path->p[0]) * npts;
path = (PATH *) palloc(size);
SET_VARSIZE(path, size);
path->npts = npts;
if ((!path_decode(TRUE, npts, s, &isopen, &s, &(path->p[0])))
&& (!((depth == 0) && (*s == '\0'))) && !((depth >= 1) && (*s == RDELIM)))
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type path: \"%s\"", str)));
path->closed = (!isopen);
/* prevent instability in unused pad bytes */
path->dummy = 0;
PG_RETURN_PATH_P(path);
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | path_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
PATH *path;
int isopen;
char *s;
int npts;
int size;
int base_size;
int depth = 0;
if ((npts = pair_count(str, ',')) <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type path: \"%s\"", str)));
s = str;
while (isspace((unsigned char) *s))
s++;
/* skip single leading paren */
if ((*s == LDELIM) && (strrchr(s, LDELIM) == s))
{
s++;
depth++;
}
base_size = sizeof(path->p[0]) * npts;
size = offsetof(PATH, p[0]) + base_size;
/* Check for integer overflow */
if (base_size / npts != sizeof(path->p[0]) || size <= base_size)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("too many points requested")));
path = (PATH *) palloc(size);
SET_VARSIZE(path, size);
path->npts = npts;
if ((!path_decode(TRUE, npts, s, &isopen, &s, &(path->p[0])))
&& (!((depth == 0) && (*s == '\0'))) && !((depth >= 1) && (*s == RDELIM)))
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type path: \"%s\"", str)));
path->closed = (!isopen);
/* prevent instability in unused pad bytes */
path->dummy = 0;
PG_RETURN_PATH_P(path);
}
| 166,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: static struct mnt_namespace *dup_mnt_ns(struct mnt_namespace *mnt_ns,
struct user_namespace *user_ns, struct fs_struct *fs)
{
struct mnt_namespace *new_ns;
struct vfsmount *rootmnt = NULL, *pwdmnt = NULL;
struct mount *p, *q;
struct mount *old = mnt_ns->root;
struct mount *new;
int copy_flags;
new_ns = alloc_mnt_ns(user_ns);
if (IS_ERR(new_ns))
return new_ns;
down_write(&namespace_sem);
/* First pass: copy the tree topology */
copy_flags = CL_COPY_ALL | CL_EXPIRE;
if (user_ns != mnt_ns->user_ns)
copy_flags |= CL_SHARED_TO_SLAVE;
new = copy_tree(old, old->mnt.mnt_root, copy_flags);
if (IS_ERR(new)) {
up_write(&namespace_sem);
free_mnt_ns(new_ns);
return ERR_CAST(new);
}
new_ns->root = new;
br_write_lock(&vfsmount_lock);
list_add_tail(&new_ns->list, &new->mnt_list);
br_write_unlock(&vfsmount_lock);
/*
* Second pass: switch the tsk->fs->* elements and mark new vfsmounts
* as belonging to new namespace. We have already acquired a private
* fs_struct, so tsk->fs->lock is not needed.
*/
p = old;
q = new;
while (p) {
q->mnt_ns = new_ns;
if (fs) {
if (&p->mnt == fs->root.mnt) {
fs->root.mnt = mntget(&q->mnt);
rootmnt = &p->mnt;
}
if (&p->mnt == fs->pwd.mnt) {
fs->pwd.mnt = mntget(&q->mnt);
pwdmnt = &p->mnt;
}
}
p = next_mnt(p, old);
q = next_mnt(q, new);
}
up_write(&namespace_sem);
if (rootmnt)
mntput(rootmnt);
if (pwdmnt)
mntput(pwdmnt);
return new_ns;
}
Commit Message: vfs: Carefully propogate mounts across user namespaces
As a matter of policy MNT_READONLY should not be changable if the
original mounter had more privileges than creator of the mount
namespace.
Add the flag CL_UNPRIVILEGED to note when we are copying a mount from
a mount namespace that requires more privileges to a mount namespace
that requires fewer privileges.
When the CL_UNPRIVILEGED flag is set cause clone_mnt to set MNT_NO_REMOUNT
if any of the mnt flags that should never be changed are set.
This protects both mount propagation and the initial creation of a less
privileged mount namespace.
Cc: [email protected]
Acked-by: Serge Hallyn <[email protected]>
Reported-by: Andy Lutomirski <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-264 | static struct mnt_namespace *dup_mnt_ns(struct mnt_namespace *mnt_ns,
struct user_namespace *user_ns, struct fs_struct *fs)
{
struct mnt_namespace *new_ns;
struct vfsmount *rootmnt = NULL, *pwdmnt = NULL;
struct mount *p, *q;
struct mount *old = mnt_ns->root;
struct mount *new;
int copy_flags;
new_ns = alloc_mnt_ns(user_ns);
if (IS_ERR(new_ns))
return new_ns;
down_write(&namespace_sem);
/* First pass: copy the tree topology */
copy_flags = CL_COPY_ALL | CL_EXPIRE;
if (user_ns != mnt_ns->user_ns)
copy_flags |= CL_SHARED_TO_SLAVE | CL_UNPRIVILEGED;
new = copy_tree(old, old->mnt.mnt_root, copy_flags);
if (IS_ERR(new)) {
up_write(&namespace_sem);
free_mnt_ns(new_ns);
return ERR_CAST(new);
}
new_ns->root = new;
br_write_lock(&vfsmount_lock);
list_add_tail(&new_ns->list, &new->mnt_list);
br_write_unlock(&vfsmount_lock);
/*
* Second pass: switch the tsk->fs->* elements and mark new vfsmounts
* as belonging to new namespace. We have already acquired a private
* fs_struct, so tsk->fs->lock is not needed.
*/
p = old;
q = new;
while (p) {
q->mnt_ns = new_ns;
if (fs) {
if (&p->mnt == fs->root.mnt) {
fs->root.mnt = mntget(&q->mnt);
rootmnt = &p->mnt;
}
if (&p->mnt == fs->pwd.mnt) {
fs->pwd.mnt = mntget(&q->mnt);
pwdmnt = &p->mnt;
}
}
p = next_mnt(p, old);
q = next_mnt(q, new);
}
up_write(&namespace_sem);
if (rootmnt)
mntput(rootmnt);
if (pwdmnt)
mntput(pwdmnt);
return new_ns;
}
| 166,095 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: lrmd_remote_listen(gpointer data)
{
int csock = 0;
int flag = 0;
unsigned laddr = 0;
struct sockaddr addr;
gnutls_session_t *session = NULL;
crm_client_t *new_client = NULL;
static struct mainloop_fd_callbacks lrmd_remote_fd_cb = {
.dispatch = lrmd_remote_client_msg,
.destroy = lrmd_remote_client_destroy,
};
laddr = sizeof(addr);
memset(&addr, 0, sizeof(addr));
getsockname(ssock, &addr, &laddr);
/* accept the connection */
if (addr.sa_family == AF_INET6) {
struct sockaddr_in6 sa;
char addr_str[INET6_ADDRSTRLEN];
laddr = sizeof(sa);
memset(&sa, 0, sizeof(sa));
csock = accept(ssock, &sa, &laddr);
get_ip_str((struct sockaddr *)&sa, addr_str, INET6_ADDRSTRLEN);
crm_info("New remote connection from %s", addr_str);
} else {
struct sockaddr_in sa;
char addr_str[INET_ADDRSTRLEN];
laddr = sizeof(sa);
memset(&sa, 0, sizeof(sa));
csock = accept(ssock, &sa, &laddr);
get_ip_str((struct sockaddr *)&sa, addr_str, INET_ADDRSTRLEN);
crm_info("New remote connection from %s", addr_str);
}
if (csock == -1) {
crm_err("accept socket failed");
return TRUE;
}
if ((flag = fcntl(csock, F_GETFL)) >= 0) {
if (fcntl(csock, F_SETFL, flag | O_NONBLOCK) < 0) {
crm_err("fcntl() write failed");
close(csock);
return TRUE;
}
} else {
crm_err("fcntl() read failed");
close(csock);
return TRUE;
}
session = create_psk_tls_session(csock, GNUTLS_SERVER, psk_cred_s);
if (session == NULL) {
crm_err("TLS session creation failed");
close(csock);
return TRUE;
}
new_client = calloc(1, sizeof(crm_client_t));
new_client->remote = calloc(1, sizeof(crm_remote_t));
new_client->kind = CRM_CLIENT_TLS;
new_client->remote->tls_session = session;
new_client->id = crm_generate_uuid();
new_client->remote->auth_timeout =
g_timeout_add(LRMD_REMOTE_AUTH_TIMEOUT, lrmd_auth_timeout_cb, new_client);
crm_notice("LRMD client connection established. %p id: %s", new_client, new_client->id);
new_client->remote->source =
mainloop_add_fd("lrmd-remote-client", G_PRIORITY_DEFAULT, csock, new_client,
&lrmd_remote_fd_cb);
g_hash_table_insert(client_connections, new_client->id, new_client);
/* Alert other clients of the new connection */
notify_of_new_client(new_client);
return TRUE;
}
Commit Message: Fix: remote: cl#5269 - Notify other clients of a new connection only if the handshake has completed (bsc#967388)
CWE ID: CWE-254 | lrmd_remote_listen(gpointer data)
{
int csock = 0;
int flag = 0;
unsigned laddr = 0;
struct sockaddr addr;
gnutls_session_t *session = NULL;
crm_client_t *new_client = NULL;
static struct mainloop_fd_callbacks lrmd_remote_fd_cb = {
.dispatch = lrmd_remote_client_msg,
.destroy = lrmd_remote_client_destroy,
};
laddr = sizeof(addr);
memset(&addr, 0, sizeof(addr));
getsockname(ssock, &addr, &laddr);
/* accept the connection */
if (addr.sa_family == AF_INET6) {
struct sockaddr_in6 sa;
char addr_str[INET6_ADDRSTRLEN];
laddr = sizeof(sa);
memset(&sa, 0, sizeof(sa));
csock = accept(ssock, &sa, &laddr);
get_ip_str((struct sockaddr *)&sa, addr_str, INET6_ADDRSTRLEN);
crm_info("New remote connection from %s", addr_str);
} else {
struct sockaddr_in sa;
char addr_str[INET_ADDRSTRLEN];
laddr = sizeof(sa);
memset(&sa, 0, sizeof(sa));
csock = accept(ssock, &sa, &laddr);
get_ip_str((struct sockaddr *)&sa, addr_str, INET_ADDRSTRLEN);
crm_info("New remote connection from %s", addr_str);
}
if (csock == -1) {
crm_err("accept socket failed");
return TRUE;
}
if ((flag = fcntl(csock, F_GETFL)) >= 0) {
if (fcntl(csock, F_SETFL, flag | O_NONBLOCK) < 0) {
crm_err("fcntl() write failed");
close(csock);
return TRUE;
}
} else {
crm_err("fcntl() read failed");
close(csock);
return TRUE;
}
session = create_psk_tls_session(csock, GNUTLS_SERVER, psk_cred_s);
if (session == NULL) {
crm_err("TLS session creation failed");
close(csock);
return TRUE;
}
new_client = calloc(1, sizeof(crm_client_t));
new_client->remote = calloc(1, sizeof(crm_remote_t));
new_client->kind = CRM_CLIENT_TLS;
new_client->remote->tls_session = session;
new_client->id = crm_generate_uuid();
new_client->remote->auth_timeout =
g_timeout_add(LRMD_REMOTE_AUTH_TIMEOUT, lrmd_auth_timeout_cb, new_client);
crm_notice("LRMD client connection established. %p id: %s", new_client, new_client->id);
new_client->remote->source =
mainloop_add_fd("lrmd-remote-client", G_PRIORITY_DEFAULT, csock, new_client,
&lrmd_remote_fd_cb);
g_hash_table_insert(client_connections, new_client->id, new_client);
return TRUE;
}
| 168,785 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
int len)
{
int r;
unsigned long addr;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return -EFAULT;
r = copy_from_user(data, (void __user *)addr + offset, len);
if (r)
return -EFAULT;
return 0;
}
Commit Message: KVM: Validate userspace_addr of memslot when registered
This way, we can avoid checking the user space address many times when
we read the guest memory.
Although we can do the same for write if we check which slots are
writable, we do not care write now: reading the guest memory happens
more often than writing.
[avi: change VERIFY_READ to VERIFY_WRITE]
Signed-off-by: Takuya Yoshikawa <[email protected]>
Signed-off-by: Avi Kivity <[email protected]>
CWE ID: CWE-20 | int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
int len)
{
int r;
unsigned long addr;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return -EFAULT;
r = __copy_from_user(data, (void __user *)addr + offset, len);
if (r)
return -EFAULT;
return 0;
}
| 166,100 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Local<v8::Value> V8Debugger::functionLocation(v8::Local<v8::Context> context, v8::Local<v8::Function> function)
{
int scriptId = function->ScriptId();
if (scriptId == v8::UnboundScript::kNoScriptId)
return v8::Null(m_isolate);
int lineNumber = function->GetScriptLineNumber();
int columnNumber = function->GetScriptColumnNumber();
if (lineNumber == v8::Function::kLineOffsetNotFound || columnNumber == v8::Function::kLineOffsetNotFound)
return v8::Null(m_isolate);
v8::Local<v8::Object> location = v8::Object::New(m_isolate);
if (!location->Set(context, toV8StringInternalized(m_isolate, "scriptId"), toV8String(m_isolate, String16::fromInteger(scriptId))).FromMaybe(false))
return v8::Null(m_isolate);
if (!location->Set(context, toV8StringInternalized(m_isolate, "lineNumber"), v8::Integer::New(m_isolate, lineNumber)).FromMaybe(false))
return v8::Null(m_isolate);
if (!location->Set(context, toV8StringInternalized(m_isolate, "columnNumber"), v8::Integer::New(m_isolate, columnNumber)).FromMaybe(false))
return v8::Null(m_isolate);
if (!markAsInternal(context, location, V8InternalValueType::kLocation))
return v8::Null(m_isolate);
return location;
}
Commit Message: [DevTools] Copy objects from debugger context to inspected context properly.
BUG=637594
Review-Url: https://codereview.chromium.org/2253643002
Cr-Commit-Position: refs/heads/master@{#412436}
CWE ID: CWE-79 | v8::Local<v8::Value> V8Debugger::functionLocation(v8::Local<v8::Context> context, v8::Local<v8::Function> function)
{
int scriptId = function->ScriptId();
if (scriptId == v8::UnboundScript::kNoScriptId)
return v8::Null(m_isolate);
int lineNumber = function->GetScriptLineNumber();
int columnNumber = function->GetScriptColumnNumber();
if (lineNumber == v8::Function::kLineOffsetNotFound || columnNumber == v8::Function::kLineOffsetNotFound)
return v8::Null(m_isolate);
v8::Local<v8::Object> location = v8::Object::New(m_isolate);
if (!location->SetPrototype(context, v8::Null(m_isolate)).FromMaybe(false))
return v8::Null(m_isolate);
if (!location->Set(context, toV8StringInternalized(m_isolate, "scriptId"), toV8String(m_isolate, String16::fromInteger(scriptId))).FromMaybe(false))
return v8::Null(m_isolate);
if (!location->Set(context, toV8StringInternalized(m_isolate, "lineNumber"), v8::Integer::New(m_isolate, lineNumber)).FromMaybe(false))
return v8::Null(m_isolate);
if (!location->Set(context, toV8StringInternalized(m_isolate, "columnNumber"), v8::Integer::New(m_isolate, columnNumber)).FromMaybe(false))
return v8::Null(m_isolate);
if (!markAsInternal(context, location, V8InternalValueType::kLocation))
return v8::Null(m_isolate);
return location;
}
| 172,065 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: HistogramBase* Histogram::Factory::Build() {
HistogramBase* histogram = StatisticsRecorder::FindHistogram(name_);
if (!histogram) {
const BucketRanges* created_ranges = CreateRanges();
const BucketRanges* registered_ranges =
StatisticsRecorder::RegisterOrDeleteDuplicateRanges(created_ranges);
if (bucket_count_ == 0) {
bucket_count_ = static_cast<uint32_t>(registered_ranges->bucket_count());
minimum_ = registered_ranges->range(1);
maximum_ = registered_ranges->range(bucket_count_ - 1);
}
PersistentHistogramAllocator::Reference histogram_ref = 0;
std::unique_ptr<HistogramBase> tentative_histogram;
PersistentHistogramAllocator* allocator = GlobalHistogramAllocator::Get();
if (allocator) {
tentative_histogram = allocator->AllocateHistogram(
histogram_type_,
name_,
minimum_,
maximum_,
registered_ranges,
flags_,
&histogram_ref);
}
if (!tentative_histogram) {
DCHECK(!histogram_ref); // Should never have been set.
DCHECK(!allocator); // Shouldn't have failed.
flags_ &= ~HistogramBase::kIsPersistent;
tentative_histogram = HeapAlloc(registered_ranges);
tentative_histogram->SetFlags(flags_);
}
FillHistogram(tentative_histogram.get());
const void* tentative_histogram_ptr = tentative_histogram.get();
histogram = StatisticsRecorder::RegisterOrDeleteDuplicate(
tentative_histogram.release());
if (histogram_ref) {
allocator->FinalizeHistogram(histogram_ref,
histogram == tentative_histogram_ptr);
}
ReportHistogramActivity(*histogram, HISTOGRAM_CREATED);
} else {
ReportHistogramActivity(*histogram, HISTOGRAM_LOOKUP);
}
DCHECK_EQ(histogram_type_, histogram->GetHistogramType()) << name_;
if (bucket_count_ != 0 &&
!histogram->HasConstructionArguments(minimum_, maximum_, bucket_count_)) {
DLOG(ERROR) << "Histogram " << name_ << " has bad construction arguments";
return nullptr;
}
return histogram;
}
Commit Message: Convert DCHECKs to CHECKs for histogram types
When a histogram is looked up by name, there is currently a DCHECK that
verifies the type of the stored histogram matches the expected type.
A mismatch represents a significant problem because the returned
HistogramBase is cast to a Histogram in ValidateRangeChecksum,
potentially causing a crash.
This CL converts the DCHECK to a CHECK to prevent the possibility of
type confusion in release builds.
BUG=651443
[email protected]
Review-Url: https://codereview.chromium.org/2381893003
Cr-Commit-Position: refs/heads/master@{#421929}
CWE ID: CWE-476 | HistogramBase* Histogram::Factory::Build() {
HistogramBase* histogram = StatisticsRecorder::FindHistogram(name_);
if (!histogram) {
const BucketRanges* created_ranges = CreateRanges();
const BucketRanges* registered_ranges =
StatisticsRecorder::RegisterOrDeleteDuplicateRanges(created_ranges);
if (bucket_count_ == 0) {
bucket_count_ = static_cast<uint32_t>(registered_ranges->bucket_count());
minimum_ = registered_ranges->range(1);
maximum_ = registered_ranges->range(bucket_count_ - 1);
}
PersistentHistogramAllocator::Reference histogram_ref = 0;
std::unique_ptr<HistogramBase> tentative_histogram;
PersistentHistogramAllocator* allocator = GlobalHistogramAllocator::Get();
if (allocator) {
tentative_histogram = allocator->AllocateHistogram(
histogram_type_,
name_,
minimum_,
maximum_,
registered_ranges,
flags_,
&histogram_ref);
}
if (!tentative_histogram) {
DCHECK(!histogram_ref); // Should never have been set.
DCHECK(!allocator); // Shouldn't have failed.
flags_ &= ~HistogramBase::kIsPersistent;
tentative_histogram = HeapAlloc(registered_ranges);
tentative_histogram->SetFlags(flags_);
}
FillHistogram(tentative_histogram.get());
const void* tentative_histogram_ptr = tentative_histogram.get();
histogram = StatisticsRecorder::RegisterOrDeleteDuplicate(
tentative_histogram.release());
if (histogram_ref) {
allocator->FinalizeHistogram(histogram_ref,
histogram == tentative_histogram_ptr);
}
ReportHistogramActivity(*histogram, HISTOGRAM_CREATED);
} else {
ReportHistogramActivity(*histogram, HISTOGRAM_LOOKUP);
}
CHECK_EQ(histogram_type_, histogram->GetHistogramType()) << name_;
if (bucket_count_ != 0 &&
!histogram->HasConstructionArguments(minimum_, maximum_, bucket_count_)) {
DLOG(ERROR) << "Histogram " << name_ << " has bad construction arguments";
return nullptr;
}
return histogram;
}
| 172,493 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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: void ahci_uninit(AHCIState *s)
{
g_free(s->dev);
}
Commit Message:
CWE ID: CWE-772 | void ahci_uninit(AHCIState *s)
{
int i, j;
for (i = 0; i < s->ports; i++) {
AHCIDevice *ad = &s->dev[i];
for (j = 0; j < 2; j++) {
IDEState *s = &ad->port.ifs[j];
ide_exit(s);
}
}
g_free(s->dev);
}
| 164,797 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BGD_DECLARE(void *) gdImageWebpPtrEx (gdImagePtr im, int *size, int quality)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx(2048, NULL);
if (out == NULL) {
return NULL;
}
gdImageWebpCtx(im, out, quality);
rv = gdDPExtractData(out, size);
out->gd_free(out);
return rv;
}
Commit Message: Fix double-free in gdImageWebPtr()
The issue is that gdImageWebpCtx() (which is called by gdImageWebpPtr() and
the other WebP output functions to do the real work) does not return whether
it succeeded or failed, so this is not checked in gdImageWebpPtr() and the
function wrongly assumes everything is okay, which is not, in this case,
because there is a size limitation for WebP, namely that the width and
height must by less than 16383.
We can't change the signature of gdImageWebpCtx() for API compatibility
reasons, so we introduce the static helper _gdImageWebpCtx() which returns
success respective failure, so gdImageWebpPtr() and gdImageWebpPtrEx() can
check the return value. We leave it solely to libwebp for now to report
warnings regarding the failing write.
This issue had been reported by Ibrahim El-Sayed to [email protected].
CVE-2016-6912
CWE ID: CWE-415 | BGD_DECLARE(void *) gdImageWebpPtrEx (gdImagePtr im, int *size, int quality)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx(2048, NULL);
if (out == NULL) {
return NULL;
}
if (_gdImageWebpCtx(im, out, quality)) {
rv = NULL;
} else {
rv = gdDPExtractData(out, size);
}
out->gd_free(out);
return rv;
}
| 168,820 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParsePEReference(xmlParserCtxtPtr ctxt)
{
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%')
return;
NEXT;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_PEREF_NO_NAME, "PEReference: no name\n");
return;
}
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"PEReference: %s\n", name);
if (RAW != ';') {
xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL);
return;
}
NEXT;
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Request the entity from SAX
*/
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (ctxt->instate == XML_PARSER_EOF)
return;
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must
* precede any reference to it...
*/
if ((ctxt->validate) && (ctxt->vctxt.error != NULL)) {
xmlValidityError(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
} else
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
xmlParserEntityCheck(ctxt, 0, NULL, 0);
} else {
/*
* Internal checking in case the entity quest barfed
*/
if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Internal: %%%s; is not a parameter entity\n",
name, NULL);
} else {
xmlChar start[4];
xmlCharEncoding enc;
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
((ctxt->options & XML_PARSE_NOENT) == 0) &&
((ctxt->options & XML_PARSE_DTDVALID) == 0) &&
((ctxt->options & XML_PARSE_DTDLOAD) == 0) &&
((ctxt->options & XML_PARSE_DTDATTR) == 0) &&
(ctxt->replaceEntities == 0) &&
(ctxt->validate == 0))
return;
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
if (entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) {
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
* Note that, since we may have some non-UTF8
* encoding (like UTF16, bug 135229), the 'length'
* is not known, but we can calculate based upon
* the amount of data in the buffer.
*/
GROW
if (ctxt->instate == XML_PARSER_EOF)
return;
if ((ctxt->input->end - ctxt->input->cur)>=4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
}
}
}
}
ctxt->hasPErefs = 1;
}
Commit Message: Detect infinite recursion in parameter entities
When expanding a parameter entity in a DTD, infinite recursion could
lead to an infinite loop or memory exhaustion.
Thanks to Wei Lei for the first of many reports.
Fixes bug 759579.
CWE ID: CWE-835 | xmlParsePEReference(xmlParserCtxtPtr ctxt)
{
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%')
return;
NEXT;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_PEREF_NO_NAME, "PEReference: no name\n");
return;
}
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"PEReference: %s\n", name);
if (RAW != ';') {
xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL);
return;
}
NEXT;
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Request the entity from SAX
*/
if ((ctxt->sax != NULL) &&
(ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (ctxt->instate == XML_PARSER_EOF)
return;
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must
* precede any reference to it...
*/
if ((ctxt->validate) && (ctxt->vctxt.error != NULL)) {
xmlValidityError(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
} else
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
xmlParserEntityCheck(ctxt, 0, NULL, 0);
} else {
/*
* Internal checking in case the entity quest barfed
*/
if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Internal: %%%s; is not a parameter entity\n",
name, NULL);
} else {
xmlChar start[4];
xmlCharEncoding enc;
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
((ctxt->options & XML_PARSE_NOENT) == 0) &&
((ctxt->options & XML_PARSE_DTDVALID) == 0) &&
((ctxt->options & XML_PARSE_DTDLOAD) == 0) &&
((ctxt->options & XML_PARSE_DTDATTR) == 0) &&
(ctxt->replaceEntities == 0) &&
(ctxt->validate == 0))
return;
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0) {
xmlFreeInputStream(input);
return;
}
if (entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) {
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
* Note that, since we may have some non-UTF8
* encoding (like UTF16, bug 135229), the 'length'
* is not known, but we can calculate based upon
* the amount of data in the buffer.
*/
GROW
if (ctxt->instate == XML_PARSER_EOF)
return;
if ((ctxt->input->end - ctxt->input->cur)>=4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
}
}
}
}
ctxt->hasPErefs = 1;
}
| 167,665 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: sg_start_req(Sg_request *srp, unsigned char *cmd)
{
int res;
struct request *rq;
Sg_fd *sfp = srp->parentfp;
sg_io_hdr_t *hp = &srp->header;
int dxfer_len = (int) hp->dxfer_len;
int dxfer_dir = hp->dxfer_direction;
unsigned int iov_count = hp->iovec_count;
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
struct rq_map_data *md, map_data;
int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ;
unsigned char *long_cmdp = NULL;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_start_req: dxfer_len=%d\n",
dxfer_len));
if (hp->cmd_len > BLK_MAX_CDB) {
long_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL);
if (!long_cmdp)
return -ENOMEM;
}
/*
* NOTE
*
* With scsi-mq enabled, there are a fixed number of preallocated
* requests equal in number to shost->can_queue. If all of the
* preallocated requests are already in use, then using GFP_ATOMIC with
* blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL
* will cause blk_get_request() to sleep until an active command
* completes, freeing up a request. Neither option is ideal, but
* GFP_KERNEL is the better choice to prevent userspace from getting an
* unexpected EWOULDBLOCK.
*
* With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually
* does not sleep except under memory pressure.
*/
rq = blk_get_request(q, rw, GFP_KERNEL);
if (IS_ERR(rq)) {
kfree(long_cmdp);
return PTR_ERR(rq);
}
blk_rq_set_block_pc(rq);
if (hp->cmd_len > BLK_MAX_CDB)
rq->cmd = long_cmdp;
memcpy(rq->cmd, cmd, hp->cmd_len);
rq->cmd_len = hp->cmd_len;
srp->rq = rq;
rq->end_io_data = srp;
rq->sense = srp->sense_b;
rq->retries = SG_DEFAULT_RETRIES;
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
return 0;
if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO &&
dxfer_dir != SG_DXFER_UNKNOWN && !iov_count &&
!sfp->parentdp->device->host->unchecked_isa_dma &&
blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len))
md = NULL;
else
md = &map_data;
if (md) {
if (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen)
sg_link_reserve(sfp, srp, dxfer_len);
else {
res = sg_build_indirect(req_schp, sfp, dxfer_len);
if (res)
return res;
}
md->pages = req_schp->pages;
md->page_order = req_schp->page_order;
md->nr_entries = req_schp->k_use_sg;
md->offset = 0;
md->null_mapped = hp->dxferp ? 0 : 1;
if (dxfer_dir == SG_DXFER_TO_FROM_DEV)
md->from_user = 1;
else
md->from_user = 0;
}
if (unlikely(iov_count > MAX_UIOVEC))
return -EINVAL;
if (iov_count) {
int size = sizeof(struct iovec) * iov_count;
struct iovec *iov;
struct iov_iter i;
iov = memdup_user(hp->dxferp, size);
if (IS_ERR(iov))
return PTR_ERR(iov);
iov_iter_init(&i, rw, iov, iov_count,
min_t(size_t, hp->dxfer_len,
iov_length(iov, iov_count)));
res = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC);
kfree(iov);
} else
res = blk_rq_map_user(q, rq, md, hp->dxferp,
hp->dxfer_len, GFP_ATOMIC);
if (!res) {
srp->bio = rq->bio;
if (!md) {
req_schp->dio_in_use = 1;
hp->info |= SG_INFO_DIRECT_IO;
}
}
return res;
}
Commit Message: sg_start_req(): use import_iovec()
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-189 | sg_start_req(Sg_request *srp, unsigned char *cmd)
{
int res;
struct request *rq;
Sg_fd *sfp = srp->parentfp;
sg_io_hdr_t *hp = &srp->header;
int dxfer_len = (int) hp->dxfer_len;
int dxfer_dir = hp->dxfer_direction;
unsigned int iov_count = hp->iovec_count;
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
struct rq_map_data *md, map_data;
int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ;
unsigned char *long_cmdp = NULL;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_start_req: dxfer_len=%d\n",
dxfer_len));
if (hp->cmd_len > BLK_MAX_CDB) {
long_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL);
if (!long_cmdp)
return -ENOMEM;
}
/*
* NOTE
*
* With scsi-mq enabled, there are a fixed number of preallocated
* requests equal in number to shost->can_queue. If all of the
* preallocated requests are already in use, then using GFP_ATOMIC with
* blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL
* will cause blk_get_request() to sleep until an active command
* completes, freeing up a request. Neither option is ideal, but
* GFP_KERNEL is the better choice to prevent userspace from getting an
* unexpected EWOULDBLOCK.
*
* With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually
* does not sleep except under memory pressure.
*/
rq = blk_get_request(q, rw, GFP_KERNEL);
if (IS_ERR(rq)) {
kfree(long_cmdp);
return PTR_ERR(rq);
}
blk_rq_set_block_pc(rq);
if (hp->cmd_len > BLK_MAX_CDB)
rq->cmd = long_cmdp;
memcpy(rq->cmd, cmd, hp->cmd_len);
rq->cmd_len = hp->cmd_len;
srp->rq = rq;
rq->end_io_data = srp;
rq->sense = srp->sense_b;
rq->retries = SG_DEFAULT_RETRIES;
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
return 0;
if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO &&
dxfer_dir != SG_DXFER_UNKNOWN && !iov_count &&
!sfp->parentdp->device->host->unchecked_isa_dma &&
blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len))
md = NULL;
else
md = &map_data;
if (md) {
if (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen)
sg_link_reserve(sfp, srp, dxfer_len);
else {
res = sg_build_indirect(req_schp, sfp, dxfer_len);
if (res)
return res;
}
md->pages = req_schp->pages;
md->page_order = req_schp->page_order;
md->nr_entries = req_schp->k_use_sg;
md->offset = 0;
md->null_mapped = hp->dxferp ? 0 : 1;
if (dxfer_dir == SG_DXFER_TO_FROM_DEV)
md->from_user = 1;
else
md->from_user = 0;
}
if (iov_count) {
struct iovec *iov = NULL;
struct iov_iter i;
res = import_iovec(rw, hp->dxferp, iov_count, 0, &iov, &i);
if (res < 0)
return res;
iov_iter_truncate(&i, hp->dxfer_len);
res = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC);
kfree(iov);
} else
res = blk_rq_map_user(q, rq, md, hp->dxferp,
hp->dxfer_len, GFP_ATOMIC);
if (!res) {
srp->bio = rq->bio;
if (!md) {
req_schp->dio_in_use = 1;
hp->info |= SG_INFO_DIRECT_IO;
}
}
return res;
}
| 169,924 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 rpc_init_task(struct rpc_task *task, const struct rpc_task_setup *task_setup_data)
{
memset(task, 0, sizeof(*task));
atomic_set(&task->tk_count, 1);
task->tk_flags = task_setup_data->flags;
task->tk_ops = task_setup_data->callback_ops;
task->tk_calldata = task_setup_data->callback_data;
INIT_LIST_HEAD(&task->tk_task);
/* Initialize retry counters */
task->tk_garb_retry = 2;
task->tk_cred_retry = 2;
task->tk_priority = task_setup_data->priority - RPC_PRIORITY_LOW;
task->tk_owner = current->tgid;
/* Initialize workqueue for async tasks */
task->tk_workqueue = task_setup_data->workqueue;
if (task->tk_ops->rpc_call_prepare != NULL)
task->tk_action = rpc_prepare_task;
/* starting timestamp */
task->tk_start = ktime_get();
dprintk("RPC: new task initialized, procpid %u\n",
task_pid_nr(current));
}
Commit Message: NLM: Don't hang forever on NLM unlock requests
If the NLM daemon is killed on the NFS server, we can currently end up
hanging forever on an 'unlock' request, instead of aborting. Basically,
if the rpcbind request fails, or the server keeps returning garbage, we
really want to quit instead of retrying.
Tested-by: Vasily Averin <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
Cc: [email protected]
CWE ID: CWE-399 | static void rpc_init_task(struct rpc_task *task, const struct rpc_task_setup *task_setup_data)
{
memset(task, 0, sizeof(*task));
atomic_set(&task->tk_count, 1);
task->tk_flags = task_setup_data->flags;
task->tk_ops = task_setup_data->callback_ops;
task->tk_calldata = task_setup_data->callback_data;
INIT_LIST_HEAD(&task->tk_task);
/* Initialize retry counters */
task->tk_garb_retry = 2;
task->tk_cred_retry = 2;
task->tk_rebind_retry = 2;
task->tk_priority = task_setup_data->priority - RPC_PRIORITY_LOW;
task->tk_owner = current->tgid;
/* Initialize workqueue for async tasks */
task->tk_workqueue = task_setup_data->workqueue;
if (task->tk_ops->rpc_call_prepare != NULL)
task->tk_action = rpc_prepare_task;
/* starting timestamp */
task->tk_start = ktime_get();
dprintk("RPC: new task initialized, procpid %u\n",
task_pid_nr(current));
}
| 166,223 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GKI_delay(UINT32 timeout_ms) {
struct timespec delay;
delay.tv_sec = timeout_ms / 1000;
delay.tv_nsec = 1000 * 1000 * (timeout_ms % 1000);
int err;
do {
err = nanosleep(&delay, &delay);
} while (err == -1 && errno == EINTR);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | void GKI_delay(UINT32 timeout_ms) {
struct timespec delay;
delay.tv_sec = timeout_ms / 1000;
delay.tv_nsec = 1000 * 1000 * (timeout_ms % 1000);
int err;
do {
err = TEMP_FAILURE_RETRY(nanosleep(&delay, &delay));
} while (err == -1 && errno == EINTR);
}
| 173,471 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 qemu_spice_create_host_primary(SimpleSpiceDisplay *ssd)
{
QXLDevSurfaceCreate surface;
memset(&surface, 0, sizeof(surface));
dprint(1, "%s/%d: %dx%d\n", __func__, ssd->qxl.id,
surface_width(ssd->ds), surface_height(ssd->ds));
surface.format = SPICE_SURFACE_FMT_32_xRGB;
surface.width = surface_width(ssd->ds);
{
dprint(1, "%s/%d:\n", __func__, ssd->qxl.id);
qemu_spice_destroy_primary_surface(ssd, 0, QXL_SYNC);
}
void qemu_spice_display_init_common(SimpleSpiceDisplay *ssd)
{
qemu_mutex_init(&ssd->lock);
QTAILQ_INIT(&ssd->updates);
ssd->mouse_x = -1;
ssd->mouse_y = -1;
if (ssd->num_surfaces == 0) {
ssd->num_surfaces = 1024;
}
ssd->bufsize = (16 * 1024 * 1024);
ssd->buf = g_malloc(ssd->bufsize);
}
/* display listener callbacks */
void qemu_spice_display_update(SimpleSpiceDisplay *ssd,
int x, int y, int w, int h)
{
if (ssd->num_surfaces == 0) {
ssd->num_surfaces = 1024;
}
ssd->bufsize = (16 * 1024 * 1024);
ssd->buf = g_malloc(ssd->bufsize);
}
/* display listener callbacks */
update_area.top = y;
update_area.bottom = y + h;
if (qemu_spice_rect_is_empty(&ssd->dirty)) {
ssd->notify++;
}
qemu_spice_rect_union(&ssd->dirty, &update_area);
}
Commit Message:
CWE ID: CWE-200 | void qemu_spice_create_host_primary(SimpleSpiceDisplay *ssd)
{
QXLDevSurfaceCreate surface;
uint64_t surface_size;
memset(&surface, 0, sizeof(surface));
surface_size = (uint64_t) surface_width(ssd->ds) *
surface_height(ssd->ds) * 4;
assert(surface_size > 0);
assert(surface_size < INT_MAX);
if (ssd->bufsize < surface_size) {
ssd->bufsize = surface_size;
g_free(ssd->buf);
ssd->buf = g_malloc(ssd->bufsize);
}
dprint(1, "%s/%d: %ux%u (size %" PRIu64 "/%d)\n", __func__, ssd->qxl.id,
surface_width(ssd->ds), surface_height(ssd->ds),
surface_size, ssd->bufsize);
surface.format = SPICE_SURFACE_FMT_32_xRGB;
surface.width = surface_width(ssd->ds);
{
dprint(1, "%s/%d:\n", __func__, ssd->qxl.id);
qemu_spice_destroy_primary_surface(ssd, 0, QXL_SYNC);
}
void qemu_spice_display_init_common(SimpleSpiceDisplay *ssd)
{
qemu_mutex_init(&ssd->lock);
QTAILQ_INIT(&ssd->updates);
ssd->mouse_x = -1;
ssd->mouse_y = -1;
if (ssd->num_surfaces == 0) {
ssd->num_surfaces = 1024;
}
ssd->bufsize = (16 * 1024 * 1024);
ssd->buf = g_malloc(ssd->bufsize);
}
/* display listener callbacks */
void qemu_spice_display_update(SimpleSpiceDisplay *ssd,
int x, int y, int w, int h)
{
if (ssd->num_surfaces == 0) {
ssd->num_surfaces = 1024;
}
}
/* display listener callbacks */
update_area.top = y;
update_area.bottom = y + h;
if (qemu_spice_rect_is_empty(&ssd->dirty)) {
ssd->notify++;
}
qemu_spice_rect_union(&ssd->dirty, &update_area);
}
| 165,151 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(RecursiveDirectoryIterator, getSubPath)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (intern->u.dir.sub_path) {
RETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1);
} else {
RETURN_STRINGL("", 0, 1);
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(RecursiveDirectoryIterator, getSubPath)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (intern->u.dir.sub_path) {
RETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1);
} else {
RETURN_STRINGL("", 0, 1);
}
}
| 167,046 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SocketStream::set_context(URLRequestContext* context) {
const URLRequestContext* prev_context = context_.get();
if (context) {
context_ = context->AsWeakPtr();
} else {
context_.reset();
}
if (prev_context != context) {
if (prev_context && pac_request_) {
prev_context->proxy_service()->CancelPacRequest(pac_request_);
pac_request_ = NULL;
}
net_log_.EndEvent(NetLog::TYPE_REQUEST_ALIVE);
net_log_ = BoundNetLog();
if (context) {
net_log_ = BoundNetLog::Make(
context->net_log(),
NetLog::SOURCE_SOCKET_STREAM);
net_log_.BeginEvent(NetLog::TYPE_REQUEST_ALIVE);
}
}
}
Commit Message: Revert a workaround commit for a Use-After-Free crash.
Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed.
URLRequestContext does not inherit SupportsWeakPtr now.
R=mmenke
BUG=244746
Review URL: https://chromiumcodereview.appspot.com/16870008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void SocketStream::set_context(URLRequestContext* context) {
const URLRequestContext* prev_context = context_;
context_ = context;
if (prev_context != context) {
if (prev_context && pac_request_) {
prev_context->proxy_service()->CancelPacRequest(pac_request_);
pac_request_ = NULL;
}
net_log_.EndEvent(NetLog::TYPE_REQUEST_ALIVE);
net_log_ = BoundNetLog();
if (context) {
net_log_ = BoundNetLog::Make(
context->net_log(),
NetLog::SOURCE_SOCKET_STREAM);
net_log_.BeginEvent(NetLog::TYPE_REQUEST_ALIVE);
}
}
}
| 171,257 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int flush_completed_IO(struct inode *inode)
{
ext4_io_end_t *io;
int ret = 0;
int ret2 = 0;
if (list_empty(&EXT4_I(inode)->i_completed_io_list))
return ret;
dump_completed_IO(inode);
while (!list_empty(&EXT4_I(inode)->i_completed_io_list)){
io = list_entry(EXT4_I(inode)->i_completed_io_list.next,
ext4_io_end_t, list);
/*
* Calling ext4_end_io_nolock() to convert completed
* IO to written.
*
* When ext4_sync_file() is called, run_queue() may already
* about to flush the work corresponding to this io structure.
* It will be upset if it founds the io structure related
* to the work-to-be schedule is freed.
*
* Thus we need to keep the io structure still valid here after
* convertion finished. The io structure has a flag to
* avoid double converting from both fsync and background work
* queue work.
*/
ret = ext4_end_io_nolock(io);
if (ret < 0)
ret2 = ret;
else
list_del_init(&io->list);
}
return (ret2 < 0) ? ret2 : 0;
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID: | int flush_completed_IO(struct inode *inode)
{
ext4_io_end_t *io;
struct ext4_inode_info *ei = EXT4_I(inode);
unsigned long flags;
int ret = 0;
int ret2 = 0;
if (list_empty(&ei->i_completed_io_list))
return ret;
dump_completed_IO(inode);
spin_lock_irqsave(&ei->i_completed_io_lock, flags);
while (!list_empty(&ei->i_completed_io_list)){
io = list_entry(ei->i_completed_io_list.next,
ext4_io_end_t, list);
/*
* Calling ext4_end_io_nolock() to convert completed
* IO to written.
*
* When ext4_sync_file() is called, run_queue() may already
* about to flush the work corresponding to this io structure.
* It will be upset if it founds the io structure related
* to the work-to-be schedule is freed.
*
* Thus we need to keep the io structure still valid here after
* convertion finished. The io structure has a flag to
* avoid double converting from both fsync and background work
* queue work.
*/
spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
ret = ext4_end_io_nolock(io);
spin_lock_irqsave(&ei->i_completed_io_lock, flags);
if (ret < 0)
ret2 = ret;
else
list_del_init(&io->list);
}
spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
return (ret2 < 0) ? ret2 : 0;
}
| 167,550 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 uhid_event(btif_hh_device_t *p_dev)
{
struct uhid_event ev;
ssize_t ret;
memset(&ev, 0, sizeof(ev));
if(!p_dev)
{
APPL_TRACE_ERROR("%s: Device not found",__FUNCTION__)
return -1;
}
ret = read(p_dev->fd, &ev, sizeof(ev));
if (ret == 0) {
APPL_TRACE_ERROR("%s: Read HUP on uhid-cdev %s", __FUNCTION__,
strerror(errno));
return -EFAULT;
} else if (ret < 0) {
APPL_TRACE_ERROR("%s: Cannot read uhid-cdev: %s", __FUNCTION__,
strerror(errno));
return -errno;
} else if ((ev.type == UHID_OUTPUT) || (ev.type==UHID_OUTPUT_EV)) {
if (ret < (ssize_t)sizeof(ev)) {
APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %ld != %lu",
__FUNCTION__, ret, sizeof(ev.type));
return -EFAULT;
}
}
switch (ev.type) {
case UHID_START:
APPL_TRACE_DEBUG("UHID_START from uhid-dev\n");
p_dev->ready_for_data = TRUE;
break;
case UHID_STOP:
APPL_TRACE_DEBUG("UHID_STOP from uhid-dev\n");
p_dev->ready_for_data = FALSE;
break;
case UHID_OPEN:
APPL_TRACE_DEBUG("UHID_OPEN from uhid-dev\n");
break;
case UHID_CLOSE:
APPL_TRACE_DEBUG("UHID_CLOSE from uhid-dev\n");
p_dev->ready_for_data = FALSE;
break;
case UHID_OUTPUT:
if (ret < (ssize_t)(sizeof(ev.type) + sizeof(ev.u.output))) {
APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %zd < %zu",
__FUNCTION__, ret,
sizeof(ev.type) + sizeof(ev.u.output));
return -EFAULT;
}
APPL_TRACE_DEBUG("UHID_OUTPUT: Report type = %d, report_size = %d"
,ev.u.output.rtype, ev.u.output.size);
if(ev.u.output.rtype == UHID_FEATURE_REPORT)
btif_hh_setreport(p_dev, BTHH_FEATURE_REPORT,
ev.u.output.size, ev.u.output.data);
else if(ev.u.output.rtype == UHID_OUTPUT_REPORT)
btif_hh_setreport(p_dev, BTHH_OUTPUT_REPORT,
ev.u.output.size, ev.u.output.data);
else
btif_hh_setreport(p_dev, BTHH_INPUT_REPORT,
ev.u.output.size, ev.u.output.data);
break;
case UHID_OUTPUT_EV:
APPL_TRACE_DEBUG("UHID_OUTPUT_EV from uhid-dev\n");
break;
case UHID_FEATURE:
APPL_TRACE_DEBUG("UHID_FEATURE from uhid-dev\n");
break;
case UHID_FEATURE_ANSWER:
APPL_TRACE_DEBUG("UHID_FEATURE_ANSWER from uhid-dev\n");
break;
default:
APPL_TRACE_DEBUG("Invalid event from uhid-dev: %u\n", ev.type);
}
return 0;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static int uhid_event(btif_hh_device_t *p_dev)
{
struct uhid_event ev;
ssize_t ret;
memset(&ev, 0, sizeof(ev));
if(!p_dev)
{
APPL_TRACE_ERROR("%s: Device not found",__FUNCTION__)
return -1;
}
ret = TEMP_FAILURE_RETRY(read(p_dev->fd, &ev, sizeof(ev)));
if (ret == 0) {
APPL_TRACE_ERROR("%s: Read HUP on uhid-cdev %s", __FUNCTION__,
strerror(errno));
return -EFAULT;
} else if (ret < 0) {
APPL_TRACE_ERROR("%s: Cannot read uhid-cdev: %s", __FUNCTION__,
strerror(errno));
return -errno;
} else if ((ev.type == UHID_OUTPUT) || (ev.type==UHID_OUTPUT_EV)) {
if (ret < (ssize_t)sizeof(ev)) {
APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %ld != %lu",
__FUNCTION__, ret, sizeof(ev.type));
return -EFAULT;
}
}
switch (ev.type) {
case UHID_START:
APPL_TRACE_DEBUG("UHID_START from uhid-dev\n");
p_dev->ready_for_data = TRUE;
break;
case UHID_STOP:
APPL_TRACE_DEBUG("UHID_STOP from uhid-dev\n");
p_dev->ready_for_data = FALSE;
break;
case UHID_OPEN:
APPL_TRACE_DEBUG("UHID_OPEN from uhid-dev\n");
break;
case UHID_CLOSE:
APPL_TRACE_DEBUG("UHID_CLOSE from uhid-dev\n");
p_dev->ready_for_data = FALSE;
break;
case UHID_OUTPUT:
if (ret < (ssize_t)(sizeof(ev.type) + sizeof(ev.u.output))) {
APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %zd < %zu",
__FUNCTION__, ret,
sizeof(ev.type) + sizeof(ev.u.output));
return -EFAULT;
}
APPL_TRACE_DEBUG("UHID_OUTPUT: Report type = %d, report_size = %d"
,ev.u.output.rtype, ev.u.output.size);
if(ev.u.output.rtype == UHID_FEATURE_REPORT)
btif_hh_setreport(p_dev, BTHH_FEATURE_REPORT,
ev.u.output.size, ev.u.output.data);
else if(ev.u.output.rtype == UHID_OUTPUT_REPORT)
btif_hh_setreport(p_dev, BTHH_OUTPUT_REPORT,
ev.u.output.size, ev.u.output.data);
else
btif_hh_setreport(p_dev, BTHH_INPUT_REPORT,
ev.u.output.size, ev.u.output.data);
break;
case UHID_OUTPUT_EV:
APPL_TRACE_DEBUG("UHID_OUTPUT_EV from uhid-dev\n");
break;
case UHID_FEATURE:
APPL_TRACE_DEBUG("UHID_FEATURE from uhid-dev\n");
break;
case UHID_FEATURE_ANSWER:
APPL_TRACE_DEBUG("UHID_FEATURE_ANSWER from uhid-dev\n");
break;
default:
APPL_TRACE_DEBUG("Invalid event from uhid-dev: %u\n", ev.type);
}
return 0;
}
| 173,432 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry,
struct inode **delegated_inode, unsigned int flags)
{
int error;
bool is_dir = d_is_dir(old_dentry);
const unsigned char *old_name;
struct inode *source = old_dentry->d_inode;
struct inode *target = new_dentry->d_inode;
bool new_is_dir = false;
unsigned max_links = new_dir->i_sb->s_max_links;
if (source == target)
return 0;
error = may_delete(old_dir, old_dentry, is_dir);
if (error)
return error;
if (!target) {
error = may_create(new_dir, new_dentry);
} else {
new_is_dir = d_is_dir(new_dentry);
if (!(flags & RENAME_EXCHANGE))
error = may_delete(new_dir, new_dentry, is_dir);
else
error = may_delete(new_dir, new_dentry, new_is_dir);
}
if (error)
return error;
if (!old_dir->i_op->rename && !old_dir->i_op->rename2)
return -EPERM;
if (flags && !old_dir->i_op->rename2)
return -EINVAL;
/*
* If we are going to change the parent - check write permissions,
* we'll need to flip '..'.
*/
if (new_dir != old_dir) {
if (is_dir) {
error = inode_permission(source, MAY_WRITE);
if (error)
return error;
}
if ((flags & RENAME_EXCHANGE) && new_is_dir) {
error = inode_permission(target, MAY_WRITE);
if (error)
return error;
}
}
error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
flags);
if (error)
return error;
old_name = fsnotify_oldname_init(old_dentry->d_name.name);
dget(new_dentry);
if (!is_dir || (flags & RENAME_EXCHANGE))
lock_two_nondirectories(source, target);
else if (target)
inode_lock(target);
error = -EBUSY;
if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
goto out;
if (max_links && new_dir != old_dir) {
error = -EMLINK;
if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
goto out;
if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
old_dir->i_nlink >= max_links)
goto out;
}
if (is_dir && !(flags & RENAME_EXCHANGE) && target)
shrink_dcache_parent(new_dentry);
if (!is_dir) {
error = try_break_deleg(source, delegated_inode);
if (error)
goto out;
}
if (target && !new_is_dir) {
error = try_break_deleg(target, delegated_inode);
if (error)
goto out;
}
if (!old_dir->i_op->rename2) {
error = old_dir->i_op->rename(old_dir, old_dentry,
new_dir, new_dentry);
} else {
WARN_ON(old_dir->i_op->rename != NULL);
error = old_dir->i_op->rename2(old_dir, old_dentry,
new_dir, new_dentry, flags);
}
if (error)
goto out;
if (!(flags & RENAME_EXCHANGE) && target) {
if (is_dir)
target->i_flags |= S_DEAD;
dont_mount(new_dentry);
detach_mounts(new_dentry);
}
if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
if (!(flags & RENAME_EXCHANGE))
d_move(old_dentry, new_dentry);
else
d_exchange(old_dentry, new_dentry);
}
out:
if (!is_dir || (flags & RENAME_EXCHANGE))
unlock_two_nondirectories(source, target);
else if (target)
inode_unlock(target);
dput(new_dentry);
if (!error) {
fsnotify_move(old_dir, new_dir, old_name, is_dir,
!(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
if (flags & RENAME_EXCHANGE) {
fsnotify_move(new_dir, old_dir, old_dentry->d_name.name,
new_is_dir, NULL, new_dentry);
}
}
fsnotify_oldname_free(old_name);
return error;
}
Commit Message: vfs: rename: check backing inode being equal
If a file is renamed to a hardlink of itself POSIX specifies that rename(2)
should do nothing and return success.
This condition is checked in vfs_rename(). However it won't detect hard
links on overlayfs where these are given separate inodes on the overlayfs
layer.
Overlayfs itself detects this condition and returns success without doing
anything, but then vfs_rename() will proceed as if this was a successful
rename (detach_mounts(), d_move()).
The correct thing to do is to detect this condition before even calling
into overlayfs. This patch does this by calling vfs_select_inode() to get
the underlying inodes.
Signed-off-by: Miklos Szeredi <[email protected]>
Cc: <[email protected]> # v4.2+
CWE ID: CWE-284 | int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry,
struct inode **delegated_inode, unsigned int flags)
{
int error;
bool is_dir = d_is_dir(old_dentry);
const unsigned char *old_name;
struct inode *source = old_dentry->d_inode;
struct inode *target = new_dentry->d_inode;
bool new_is_dir = false;
unsigned max_links = new_dir->i_sb->s_max_links;
/*
* Check source == target.
* On overlayfs need to look at underlying inodes.
*/
if (vfs_select_inode(old_dentry, 0) == vfs_select_inode(new_dentry, 0))
return 0;
error = may_delete(old_dir, old_dentry, is_dir);
if (error)
return error;
if (!target) {
error = may_create(new_dir, new_dentry);
} else {
new_is_dir = d_is_dir(new_dentry);
if (!(flags & RENAME_EXCHANGE))
error = may_delete(new_dir, new_dentry, is_dir);
else
error = may_delete(new_dir, new_dentry, new_is_dir);
}
if (error)
return error;
if (!old_dir->i_op->rename && !old_dir->i_op->rename2)
return -EPERM;
if (flags && !old_dir->i_op->rename2)
return -EINVAL;
/*
* If we are going to change the parent - check write permissions,
* we'll need to flip '..'.
*/
if (new_dir != old_dir) {
if (is_dir) {
error = inode_permission(source, MAY_WRITE);
if (error)
return error;
}
if ((flags & RENAME_EXCHANGE) && new_is_dir) {
error = inode_permission(target, MAY_WRITE);
if (error)
return error;
}
}
error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
flags);
if (error)
return error;
old_name = fsnotify_oldname_init(old_dentry->d_name.name);
dget(new_dentry);
if (!is_dir || (flags & RENAME_EXCHANGE))
lock_two_nondirectories(source, target);
else if (target)
inode_lock(target);
error = -EBUSY;
if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
goto out;
if (max_links && new_dir != old_dir) {
error = -EMLINK;
if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
goto out;
if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
old_dir->i_nlink >= max_links)
goto out;
}
if (is_dir && !(flags & RENAME_EXCHANGE) && target)
shrink_dcache_parent(new_dentry);
if (!is_dir) {
error = try_break_deleg(source, delegated_inode);
if (error)
goto out;
}
if (target && !new_is_dir) {
error = try_break_deleg(target, delegated_inode);
if (error)
goto out;
}
if (!old_dir->i_op->rename2) {
error = old_dir->i_op->rename(old_dir, old_dentry,
new_dir, new_dentry);
} else {
WARN_ON(old_dir->i_op->rename != NULL);
error = old_dir->i_op->rename2(old_dir, old_dentry,
new_dir, new_dentry, flags);
}
if (error)
goto out;
if (!(flags & RENAME_EXCHANGE) && target) {
if (is_dir)
target->i_flags |= S_DEAD;
dont_mount(new_dentry);
detach_mounts(new_dentry);
}
if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
if (!(flags & RENAME_EXCHANGE))
d_move(old_dentry, new_dentry);
else
d_exchange(old_dentry, new_dentry);
}
out:
if (!is_dir || (flags & RENAME_EXCHANGE))
unlock_two_nondirectories(source, target);
else if (target)
inode_unlock(target);
dput(new_dentry);
if (!error) {
fsnotify_move(old_dir, new_dir, old_name, is_dir,
!(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
if (flags & RENAME_EXCHANGE) {
fsnotify_move(new_dir, old_dir, old_dentry->d_name.name,
new_is_dir, NULL, new_dentry);
}
}
fsnotify_oldname_free(old_name);
return error;
}
| 167,013 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ProcDbeGetVisualInfo(ClientPtr client)
{
REQUEST(xDbeGetVisualInfoReq);
DbeScreenPrivPtr pDbeScreenPriv;
xDbeGetVisualInfoReply rep;
Drawable *drawables;
DrawablePtr *pDrawables = NULL;
register int i, j, rc;
register int count; /* number of visual infos in reply */
register int length; /* length of reply */
ScreenPtr pScreen;
XdbeScreenVisualInfo *pScrVisInfo;
REQUEST_AT_LEAST_SIZE(xDbeGetVisualInfoReq);
if (stuff->n > UINT32_MAX / sizeof(DrawablePtr))
return BadAlloc;
return BadAlloc;
}
Commit Message:
CWE ID: CWE-190 | ProcDbeGetVisualInfo(ClientPtr client)
{
REQUEST(xDbeGetVisualInfoReq);
DbeScreenPrivPtr pDbeScreenPriv;
xDbeGetVisualInfoReply rep;
Drawable *drawables;
DrawablePtr *pDrawables = NULL;
register int i, j, rc;
register int count; /* number of visual infos in reply */
register int length; /* length of reply */
ScreenPtr pScreen;
XdbeScreenVisualInfo *pScrVisInfo;
REQUEST_AT_LEAST_SIZE(xDbeGetVisualInfoReq);
if (stuff->n > UINT32_MAX / sizeof(CARD32))
return BadLength;
REQUEST_FIXED_SIZE(xDbeGetVisualInfoReq, stuff->n * sizeof(CARD32));
if (stuff->n > UINT32_MAX / sizeof(DrawablePtr))
return BadAlloc;
return BadAlloc;
}
| 165,447 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ProcPanoramiXGetScreenSize(ClientPtr client)
{
REQUEST(xPanoramiXGetScreenSizeReq);
WindowPtr pWin;
xPanoramiXGetScreenSizeReply rep;
int rc;
if (stuff->screen >= PanoramiXNumScreens)
return BadMatch;
REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq);
rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
if (rc != Success)
return rc;
rep = (xPanoramiXGetScreenSizeReply) {
.type = X_Reply,
.sequenceNumber = client->sequence,
.length = 0,
/* screen dimensions */
.width = screenInfo.screens[stuff->screen]->width,
.height = screenInfo.screens[stuff->screen]->height,
.window = stuff->window,
.screen = stuff->screen
};
if (client->swapped) {
swaps(&rep.sequenceNumber);
swapl(&rep.length);
swapl(&rep.width);
swapl(&rep.height);
swapl(&rep.window);
swapl(&rep.screen);
}
WriteToClient(client, sizeof(xPanoramiXGetScreenSizeReply), &rep);
return Success;
}
Commit Message:
CWE ID: CWE-20 | ProcPanoramiXGetScreenSize(ClientPtr client)
{
REQUEST(xPanoramiXGetScreenSizeReq);
WindowPtr pWin;
xPanoramiXGetScreenSizeReply rep;
int rc;
REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq);
if (stuff->screen >= PanoramiXNumScreens)
return BadMatch;
rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
if (rc != Success)
return rc;
rep = (xPanoramiXGetScreenSizeReply) {
.type = X_Reply,
.sequenceNumber = client->sequence,
.length = 0,
/* screen dimensions */
.width = screenInfo.screens[stuff->screen]->width,
.height = screenInfo.screens[stuff->screen]->height,
.window = stuff->window,
.screen = stuff->screen
};
if (client->swapped) {
swaps(&rep.sequenceNumber);
swapl(&rep.length);
swapl(&rep.width);
swapl(&rep.height);
swapl(&rep.window);
swapl(&rep.screen);
}
WriteToClient(client, sizeof(xPanoramiXGetScreenSizeReply), &rep);
return Success;
}
| 165,432 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 StartSync(const StartSyncArgs& args,
OneClickSigninSyncStarter::StartSyncMode start_mode) {
if (start_mode == OneClickSigninSyncStarter::UNDO_SYNC) {
LogOneClickHistogramValue(one_click_signin::HISTOGRAM_UNDO);
return;
}
OneClickSigninSyncStarter::ConfirmationRequired confirmation =
args.confirmation_required;
if (start_mode == OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST &&
confirmation == OneClickSigninSyncStarter::CONFIRM_UNTRUSTED_SIGNIN) {
confirmation = OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN;
}
new OneClickSigninSyncStarter(args.profile, args.browser, args.session_index,
args.email, args.password, start_mode,
args.force_same_tab_navigation,
confirmation);
int action = one_click_signin::HISTOGRAM_MAX;
switch (args.auto_accept) {
case OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT:
break;
case OneClickSigninHelper::AUTO_ACCEPT_ACCEPTED:
action =
start_mode == OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS ?
one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS :
one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
break;
action = one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS;
break;
case OneClickSigninHelper::AUTO_ACCEPT_CONFIGURE:
DCHECK(start_mode == OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST);
action = one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
break;
default:
NOTREACHED() << "Invalid auto_accept: " << args.auto_accept;
break;
}
if (action != one_click_signin::HISTOGRAM_MAX)
LogOneClickHistogramValue(action);
}
Commit Message: Display confirmation dialog for untrusted signins
BUG=252062
Review URL: https://chromiumcodereview.appspot.com/17482002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void StartSync(const StartSyncArgs& args,
OneClickSigninSyncStarter::StartSyncMode start_mode) {
if (start_mode == OneClickSigninSyncStarter::UNDO_SYNC) {
LogOneClickHistogramValue(one_click_signin::HISTOGRAM_UNDO);
return;
}
new OneClickSigninSyncStarter(args.profile, args.browser, args.session_index,
args.email, args.password, start_mode,
args.force_same_tab_navigation,
args.confirmation_required,
args.source);
int action = one_click_signin::HISTOGRAM_MAX;
switch (args.auto_accept) {
case OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT:
break;
case OneClickSigninHelper::AUTO_ACCEPT_ACCEPTED:
action =
start_mode == OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS ?
one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS :
one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
break;
action = one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS;
break;
case OneClickSigninHelper::AUTO_ACCEPT_CONFIGURE:
DCHECK(start_mode == OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST);
action = one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
break;
default:
NOTREACHED() << "Invalid auto_accept: " << args.auto_accept;
break;
}
if (action != one_click_signin::HISTOGRAM_MAX)
LogOneClickHistogramValue(action);
}
| 171,244 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vapic_exit(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
int idx;
if (!apic || !apic->vapic_addr)
return;
idx = srcu_read_lock(&vcpu->kvm->srcu);
kvm_release_page_dirty(apic->vapic_page);
mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
srcu_read_unlock(&vcpu->kvm->srcu, idx);
}
Commit Message: KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368)
In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the
potential to corrupt kernel memory if userspace provides an address that
is at the end of a page. This patches concerts those functions to use
kvm_write_guest_cached and kvm_read_guest_cached. It also checks the
vapic_address specified by userspace during ioctl processing and returns
an error to userspace if the address is not a valid GPA.
This is generally not guest triggerable, because the required write is
done by firmware that runs before the guest. Also, it only affects AMD
processors and oldish Intel that do not have the FlexPriority feature
(unless you disable FlexPriority, of course; then newer processors are
also affected).
Fixes: b93463aa59d6 ('KVM: Accelerated apic support')
Reported-by: Andrew Honig <[email protected]>
Cc: [email protected]
Signed-off-by: Andrew Honig <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-20 | static void vapic_exit(struct kvm_vcpu *vcpu)
| 165,950 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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: static int get_bitmap_file(struct mddev *mddev, void __user * arg)
{
mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
char *ptr;
int err;
file = kmalloc(sizeof(*file), GFP_NOIO);
if (!file)
return -ENOMEM;
err = 0;
spin_lock(&mddev->lock);
/* bitmap disabled, zero the first byte and copy out */
if (!mddev->bitmap_info.file)
file->pathname[0] = '\0';
else if ((ptr = file_path(mddev->bitmap_info.file,
file->pathname, sizeof(file->pathname))),
IS_ERR(ptr))
err = PTR_ERR(ptr);
else
memmove(file->pathname, ptr,
sizeof(file->pathname)-(ptr-file->pathname));
spin_unlock(&mddev->lock);
if (err == 0 &&
copy_to_user(arg, file, sizeof(*file)))
err = -EFAULT;
kfree(file);
return err;
}
Commit Message: md: use kzalloc() when bitmap is disabled
In drivers/md/md.c get_bitmap_file() uses kmalloc() for creating a
mdu_bitmap_file_t called "file".
5769 file = kmalloc(sizeof(*file), GFP_NOIO);
5770 if (!file)
5771 return -ENOMEM;
This structure is copied to user space at the end of the function.
5786 if (err == 0 &&
5787 copy_to_user(arg, file, sizeof(*file)))
5788 err = -EFAULT
But if bitmap is disabled only the first byte of "file" is initialized
with zero, so it's possible to read some bytes (up to 4095) of kernel
space memory from user space. This is an information leak.
5775 /* bitmap disabled, zero the first byte and copy out */
5776 if (!mddev->bitmap_info.file)
5777 file->pathname[0] = '\0';
Signed-off-by: Benjamin Randazzo <[email protected]>
Signed-off-by: NeilBrown <[email protected]>
CWE ID: CWE-200 | static int get_bitmap_file(struct mddev *mddev, void __user * arg)
{
mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
char *ptr;
int err;
file = kzalloc(sizeof(*file), GFP_NOIO);
if (!file)
return -ENOMEM;
err = 0;
spin_lock(&mddev->lock);
/* bitmap disabled, zero the first byte and copy out */
if (!mddev->bitmap_info.file)
file->pathname[0] = '\0';
else if ((ptr = file_path(mddev->bitmap_info.file,
file->pathname, sizeof(file->pathname))),
IS_ERR(ptr))
err = PTR_ERR(ptr);
else
memmove(file->pathname, ptr,
sizeof(file->pathname)-(ptr-file->pathname));
spin_unlock(&mddev->lock);
if (err == 0 &&
copy_to_user(arg, file, sizeof(*file)))
err = -EFAULT;
kfree(file);
return err;
}
| 166,595 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PrintWebViewHelper::OnPrintPages() {
blink::WebLocalFrame* frame;
if (!GetPrintFrame(&frame))
return;
auto plugin = delegate_->GetPdfElement(frame);
Print(frame, plugin, false);
}
Commit Message: Crash on nested IPC handlers in PrintWebViewHelper
Class is not designed to handle nested IPC. Regular flows also does not
expect them. Still during printing of plugging them may show message
boxes and start nested message loops.
For now we are going just crash. If stats show us that this case is
frequent we will have to do something more complicated.
BUG=502562
Review URL: https://codereview.chromium.org/1228693002
Cr-Commit-Position: refs/heads/master@{#338100}
CWE ID: | void PrintWebViewHelper::OnPrintPages() {
CHECK_LE(ipc_nesting_level_, 1);
blink::WebLocalFrame* frame;
if (!GetPrintFrame(&frame))
return;
auto plugin = delegate_->GetPdfElement(frame);
Print(frame, plugin, false);
}
| 171,875 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int sgi_timer_set(struct k_itimer *timr, int flags,
struct itimerspec * new_setting,
struct itimerspec * old_setting)
{
unsigned long when, period, irqflags;
int err = 0;
cnodeid_t nodeid;
struct mmtimer *base;
struct rb_node *n;
if (old_setting)
sgi_timer_get(timr, old_setting);
sgi_timer_del(timr);
when = timespec_to_ns(new_setting->it_value);
period = timespec_to_ns(new_setting->it_interval);
if (when == 0)
/* Clear timer */
return 0;
base = kmalloc(sizeof(struct mmtimer), GFP_KERNEL);
if (base == NULL)
return -ENOMEM;
if (flags & TIMER_ABSTIME) {
struct timespec n;
unsigned long now;
getnstimeofday(&n);
now = timespec_to_ns(n);
if (when > now)
when -= now;
else
/* Fire the timer immediately */
when = 0;
}
/*
* Convert to sgi clock period. Need to keep rtc_time() as near as possible
* to getnstimeofday() in order to be as faithful as possible to the time
* specified.
*/
when = (when + sgi_clock_period - 1) / sgi_clock_period + rtc_time();
period = (period + sgi_clock_period - 1) / sgi_clock_period;
/*
* We are allocating a local SHub comparator. If we would be moved to another
* cpu then another SHub may be local to us. Prohibit that by switching off
* preemption.
*/
preempt_disable();
nodeid = cpu_to_node(smp_processor_id());
/* Lock the node timer structure */
spin_lock_irqsave(&timers[nodeid].lock, irqflags);
base->timer = timr;
base->cpu = smp_processor_id();
timr->it.mmtimer.clock = TIMER_SET;
timr->it.mmtimer.node = nodeid;
timr->it.mmtimer.incr = period;
timr->it.mmtimer.expires = when;
n = timers[nodeid].next;
/* Add the new struct mmtimer to node's timer list */
mmtimer_add_list(base);
if (timers[nodeid].next == n) {
/* No need to reprogram comparator for now */
spin_unlock_irqrestore(&timers[nodeid].lock, irqflags);
preempt_enable();
return err;
}
/* We need to reprogram the comparator */
if (n)
mmtimer_disable_int(cnodeid_to_nasid(nodeid), COMPARATOR);
mmtimer_set_next_timer(nodeid);
/* Unlock the node timer structure */
spin_unlock_irqrestore(&timers[nodeid].lock, irqflags);
preempt_enable();
return err;
}
Commit Message: remove div_long_long_rem
x86 is the only arch right now, which provides an optimized for
div_long_long_rem and it has the downside that one has to be very careful that
the divide doesn't overflow.
The API is a little akward, as the arguments for the unsigned divide are
signed. The signed version also doesn't handle a negative divisor and
produces worse code on 64bit archs.
There is little incentive to keep this API alive, so this converts the few
users to the new API.
Signed-off-by: Roman Zippel <[email protected]>
Cc: Ralf Baechle <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: john stultz <[email protected]>
Cc: Christoph Lameter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | static int sgi_timer_set(struct k_itimer *timr, int flags,
struct itimerspec * new_setting,
struct itimerspec * old_setting)
{
unsigned long when, period, irqflags;
int err = 0;
cnodeid_t nodeid;
struct mmtimer *base;
struct rb_node *n;
if (old_setting)
sgi_timer_get(timr, old_setting);
sgi_timer_del(timr);
when = timespec_to_ns(&new_setting->it_value);
period = timespec_to_ns(&new_setting->it_interval);
if (when == 0)
/* Clear timer */
return 0;
base = kmalloc(sizeof(struct mmtimer), GFP_KERNEL);
if (base == NULL)
return -ENOMEM;
if (flags & TIMER_ABSTIME) {
struct timespec n;
unsigned long now;
getnstimeofday(&n);
now = timespec_to_ns(&n);
if (when > now)
when -= now;
else
/* Fire the timer immediately */
when = 0;
}
/*
* Convert to sgi clock period. Need to keep rtc_time() as near as possible
* to getnstimeofday() in order to be as faithful as possible to the time
* specified.
*/
when = (when + sgi_clock_period - 1) / sgi_clock_period + rtc_time();
period = (period + sgi_clock_period - 1) / sgi_clock_period;
/*
* We are allocating a local SHub comparator. If we would be moved to another
* cpu then another SHub may be local to us. Prohibit that by switching off
* preemption.
*/
preempt_disable();
nodeid = cpu_to_node(smp_processor_id());
/* Lock the node timer structure */
spin_lock_irqsave(&timers[nodeid].lock, irqflags);
base->timer = timr;
base->cpu = smp_processor_id();
timr->it.mmtimer.clock = TIMER_SET;
timr->it.mmtimer.node = nodeid;
timr->it.mmtimer.incr = period;
timr->it.mmtimer.expires = when;
n = timers[nodeid].next;
/* Add the new struct mmtimer to node's timer list */
mmtimer_add_list(base);
if (timers[nodeid].next == n) {
/* No need to reprogram comparator for now */
spin_unlock_irqrestore(&timers[nodeid].lock, irqflags);
preempt_enable();
return err;
}
/* We need to reprogram the comparator */
if (n)
mmtimer_disable_int(cnodeid_to_nasid(nodeid), COMPARATOR);
mmtimer_set_next_timer(nodeid);
/* Unlock the node timer structure */
spin_unlock_irqrestore(&timers[nodeid].lock, irqflags);
preempt_enable();
return err;
}
| 165,752 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int nfc_genl_deactivate_target(struct sk_buff *skb,
struct genl_info *info)
{
struct nfc_dev *dev;
u32 device_idx, target_idx;
int rc;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX])
return -EINVAL;
device_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(device_idx);
if (!dev)
return -ENODEV;
target_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]);
rc = nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP);
nfc_put_device(dev);
return rc;
}
Commit Message: nfc: Ensure presence of required attributes in the deactivate_target handler
Check that the NFC_ATTR_TARGET_INDEX attributes (in addition to
NFC_ATTR_DEVICE_INDEX) are provided by the netlink client prior to
accessing them. This prevents potential unhandled NULL pointer dereference
exceptions which can be triggered by malicious user-mode programs,
if they omit one or both of these attributes.
Signed-off-by: Young Xiao <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-476 | static int nfc_genl_deactivate_target(struct sk_buff *skb,
struct genl_info *info)
{
struct nfc_dev *dev;
u32 device_idx, target_idx;
int rc;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX] ||
!info->attrs[NFC_ATTR_TARGET_INDEX])
return -EINVAL;
device_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(device_idx);
if (!dev)
return -ENODEV;
target_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]);
rc = nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP);
nfc_put_device(dev);
return rc;
}
| 169,645 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dtls1_listen(SSL *s, struct sockaddr *client)
{
int ret;
SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE);
s->d1->listen = 1;
(void)BIO_dgram_get_peer(SSL_get_rbio(s), client);
return 1;
}
Commit Message:
CWE ID: | int dtls1_listen(SSL *s, struct sockaddr *client)
{
int ret;
/* Ensure there is no state left over from a previous invocation */
SSL_clear(s);
SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE);
s->d1->listen = 1;
(void)BIO_dgram_get_peer(SSL_get_rbio(s), client);
return 1;
}
| 164,821 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 adev_open_output_stream(struct audio_hw_device *dev,
audio_io_handle_t handle,
audio_devices_t devices,
audio_output_flags_t flags,
struct audio_config *config,
struct audio_stream_out **stream_out,
const char *address)
{
struct a2dp_audio_device *a2dp_dev = (struct a2dp_audio_device *)dev;
struct a2dp_stream_out *out;
int ret = 0;
int i;
UNUSED(address);
UNUSED(handle);
UNUSED(devices);
UNUSED(flags);
INFO("opening output");
out = (struct a2dp_stream_out *)calloc(1, sizeof(struct a2dp_stream_out));
if (!out)
return -ENOMEM;
out->stream.common.get_sample_rate = out_get_sample_rate;
out->stream.common.set_sample_rate = out_set_sample_rate;
out->stream.common.get_buffer_size = out_get_buffer_size;
out->stream.common.get_channels = out_get_channels;
out->stream.common.get_format = out_get_format;
out->stream.common.set_format = out_set_format;
out->stream.common.standby = out_standby;
out->stream.common.dump = out_dump;
out->stream.common.set_parameters = out_set_parameters;
out->stream.common.get_parameters = out_get_parameters;
out->stream.common.add_audio_effect = out_add_audio_effect;
out->stream.common.remove_audio_effect = out_remove_audio_effect;
out->stream.get_latency = out_get_latency;
out->stream.set_volume = out_set_volume;
out->stream.write = out_write;
out->stream.get_render_position = out_get_render_position;
out->stream.get_presentation_position = out_get_presentation_position;
/* initialize a2dp specifics */
a2dp_stream_common_init(&out->common);
out->common.cfg.channel_flags = AUDIO_STREAM_DEFAULT_CHANNEL_FLAG;
out->common.cfg.format = AUDIO_STREAM_DEFAULT_FORMAT;
out->common.cfg.rate = AUDIO_STREAM_DEFAULT_RATE;
/* set output config values */
if (config)
{
config->format = out_get_format((const struct audio_stream *)&out->stream);
config->sample_rate = out_get_sample_rate((const struct audio_stream *)&out->stream);
config->channel_mask = out_get_channels((const struct audio_stream *)&out->stream);
}
*stream_out = &out->stream;
a2dp_dev->output = out;
a2dp_open_ctrl_path(&out->common);
if (out->common.ctrl_fd == AUDIO_SKT_DISCONNECTED)
{
ERROR("ctrl socket failed to connect (%s)", strerror(errno));
ret = -1;
goto err_open;
}
DEBUG("success");
/* Delay to ensure Headset is in proper state when START is initiated
from DUT immediately after the connection due to ongoing music playback. */
usleep(250000);
return 0;
err_open:
free(out);
*stream_out = NULL;
a2dp_dev->output = NULL;
ERROR("failed");
return ret;
}
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 int adev_open_output_stream(struct audio_hw_device *dev,
audio_io_handle_t handle,
audio_devices_t devices,
audio_output_flags_t flags,
struct audio_config *config,
struct audio_stream_out **stream_out,
const char *address)
{
struct a2dp_audio_device *a2dp_dev = (struct a2dp_audio_device *)dev;
struct a2dp_stream_out *out;
int ret = 0;
int i;
UNUSED(address);
UNUSED(handle);
UNUSED(devices);
UNUSED(flags);
INFO("opening output");
out = (struct a2dp_stream_out *)calloc(1, sizeof(struct a2dp_stream_out));
if (!out)
return -ENOMEM;
out->stream.common.get_sample_rate = out_get_sample_rate;
out->stream.common.set_sample_rate = out_set_sample_rate;
out->stream.common.get_buffer_size = out_get_buffer_size;
out->stream.common.get_channels = out_get_channels;
out->stream.common.get_format = out_get_format;
out->stream.common.set_format = out_set_format;
out->stream.common.standby = out_standby;
out->stream.common.dump = out_dump;
out->stream.common.set_parameters = out_set_parameters;
out->stream.common.get_parameters = out_get_parameters;
out->stream.common.add_audio_effect = out_add_audio_effect;
out->stream.common.remove_audio_effect = out_remove_audio_effect;
out->stream.get_latency = out_get_latency;
out->stream.set_volume = out_set_volume;
out->stream.write = out_write;
out->stream.get_render_position = out_get_render_position;
out->stream.get_presentation_position = out_get_presentation_position;
/* initialize a2dp specifics */
a2dp_stream_common_init(&out->common);
out->common.cfg.channel_flags = AUDIO_STREAM_DEFAULT_CHANNEL_FLAG;
out->common.cfg.format = AUDIO_STREAM_DEFAULT_FORMAT;
out->common.cfg.rate = AUDIO_STREAM_DEFAULT_RATE;
/* set output config values */
if (config)
{
config->format = out_get_format((const struct audio_stream *)&out->stream);
config->sample_rate = out_get_sample_rate((const struct audio_stream *)&out->stream);
config->channel_mask = out_get_channels((const struct audio_stream *)&out->stream);
}
*stream_out = &out->stream;
a2dp_dev->output = out;
a2dp_open_ctrl_path(&out->common);
if (out->common.ctrl_fd == AUDIO_SKT_DISCONNECTED)
{
ERROR("ctrl socket failed to connect (%s)", strerror(errno));
ret = -1;
goto err_open;
}
DEBUG("success");
/* Delay to ensure Headset is in proper state when START is initiated
from DUT immediately after the connection due to ongoing music playback. */
TEMP_FAILURE_RETRY(usleep(250000));
return 0;
err_open:
free(out);
*stream_out = NULL;
a2dp_dev->output = NULL;
ERROR("failed");
return ret;
}
| 173,425 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DecoderTest::RunLoop(CompressedVideoSource *video) {
vpx_codec_dec_cfg_t dec_cfg = {0};
Decoder* const decoder = codec_->CreateDecoder(dec_cfg, 0);
ASSERT_TRUE(decoder != NULL);
for (video->Begin(); video->cxdata(); video->Next()) {
PreDecodeFrameHook(*video, decoder);
vpx_codec_err_t res_dec = decoder->DecodeFrame(video->cxdata(),
video->frame_size());
ASSERT_EQ(VPX_CODEC_OK, res_dec) << decoder->DecodeError();
DxDataIterator dec_iter = decoder->GetDxData();
const vpx_image_t *img = NULL;
while ((img = dec_iter.Next()))
DecompressedFrameHook(*img, video->frame_number());
}
delete decoder;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void DecoderTest::RunLoop(CompressedVideoSource *video) {
bool Decoder::IsVP8() const {
const char *codec_name = GetDecoderName();
return strncmp(kVP8Name, codec_name, sizeof(kVP8Name) - 1) == 0;
}
void DecoderTest::HandlePeekResult(Decoder *const decoder,
CompressedVideoSource *video,
const vpx_codec_err_t res_peek) {
const bool is_vp8 = decoder->IsVP8();
if (is_vp8) {
/* Vp8's implementation of PeekStream returns an error if the frame you
* pass it is not a keyframe, so we only expect VPX_CODEC_OK on the first
* frame, which must be a keyframe. */
if (video->frame_number() == 0)
ASSERT_EQ(VPX_CODEC_OK, res_peek) << "Peek return failed: "
<< vpx_codec_err_to_string(res_peek);
} else {
/* The Vp9 implementation of PeekStream returns an error only if the
* data passed to it isn't a valid Vp9 chunk. */
ASSERT_EQ(VPX_CODEC_OK, res_peek) << "Peek return failed: "
<< vpx_codec_err_to_string(res_peek);
}
}
void DecoderTest::RunLoop(CompressedVideoSource *video,
const vpx_codec_dec_cfg_t &dec_cfg) {
Decoder* const decoder = codec_->CreateDecoder(dec_cfg, flags_, 0);
ASSERT_TRUE(decoder != NULL);
bool end_of_file = false;
for (video->Begin(); !::testing::Test::HasFailure() && !end_of_file;
video->Next()) {
PreDecodeFrameHook(*video, decoder);
vpx_codec_stream_info_t stream_info;
stream_info.sz = sizeof(stream_info);
if (video->cxdata() != NULL) {
const vpx_codec_err_t res_peek = decoder->PeekStream(video->cxdata(),
video->frame_size(),
&stream_info);
HandlePeekResult(decoder, video, res_peek);
ASSERT_FALSE(::testing::Test::HasFailure());
vpx_codec_err_t res_dec = decoder->DecodeFrame(video->cxdata(),
video->frame_size());
if (!HandleDecodeResult(res_dec, *video, decoder))
break;
} else {
// Signal end of the file to the decoder.
const vpx_codec_err_t res_dec = decoder->DecodeFrame(NULL, 0);
ASSERT_EQ(VPX_CODEC_OK, res_dec) << decoder->DecodeError();
end_of_file = true;
}
DxDataIterator dec_iter = decoder->GetDxData();
const vpx_image_t *img = NULL;
while ((img = dec_iter.Next()))
DecompressedFrameHook(*img, video->frame_number());
}
delete decoder;
}
| 174,535 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 pdf_creator_t *new_creator(int *n_elements)
{
pdf_creator_t *daddy;
static const pdf_creator_t creator_template[] =
{
{"Title", ""},
{"Author", ""},
{"Subject", ""},
{"Keywords", ""},
{"Creator", ""},
{"Producer", ""},
{"CreationDate", ""},
{"ModDate", ""},
{"Trapped", ""},
};
daddy = malloc(sizeof(creator_template));
memcpy(daddy, creator_template, sizeof(creator_template));
if (n_elements)
*n_elements = sizeof(creator_template) / sizeof(creator_template[0]);
return daddy;
}
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 | static pdf_creator_t *new_creator(int *n_elements)
{
pdf_creator_t *daddy;
static const pdf_creator_t creator_template[] =
{
{"Title", ""},
{"Author", ""},
{"Subject", ""},
{"Keywords", ""},
{"Creator", ""},
{"Producer", ""},
{"CreationDate", ""},
{"ModDate", ""},
{"Trapped", ""},
};
daddy = safe_calloc(sizeof(creator_template));
memcpy(daddy, creator_template, sizeof(creator_template));
if (n_elements)
*n_elements = sizeof(creator_template) / sizeof(creator_template[0]);
return daddy;
}
| 169,570 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 inode_init_owner(struct inode *inode, const struct inode *dir,
umode_t mode)
{
inode->i_uid = current_fsuid();
if (dir && dir->i_mode & S_ISGID) {
inode->i_gid = dir->i_gid;
if (S_ISDIR(mode))
mode |= S_ISGID;
} else
inode->i_gid = current_fsgid();
inode->i_mode = mode;
}
Commit Message: Fix up non-directory creation in SGID directories
sgid directories have special semantics, making newly created files in
the directory belong to the group of the directory, and newly created
subdirectories will also become sgid. This is historically used for
group-shared directories.
But group directories writable by non-group members should not imply
that such non-group members can magically join the group, so make sure
to clear the sgid bit on non-directories for non-members (but remember
that sgid without group execute means "mandatory locking", just to
confuse things even more).
Reported-by: Jann Horn <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Al Viro <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-269 | void inode_init_owner(struct inode *inode, const struct inode *dir,
umode_t mode)
{
inode->i_uid = current_fsuid();
if (dir && dir->i_mode & S_ISGID) {
inode->i_gid = dir->i_gid;
/* Directories are special, and always inherit S_ISGID */
if (S_ISDIR(mode))
mode |= S_ISGID;
else if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP) &&
!in_group_p(inode->i_gid) &&
!capable_wrt_inode_uidgid(dir, CAP_FSETID))
mode &= ~S_ISGID;
} else
inode->i_gid = current_fsgid();
inode->i_mode = mode;
}
| 169,153 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool AXNodeObject::computeAccessibilityIsIgnored(
IgnoredReasons* ignoredReasons) const {
#if DCHECK_IS_ON()
ASSERT(m_initialized);
#endif
if (isDescendantOfLeafNode()) {
if (ignoredReasons)
ignoredReasons->push_back(
IgnoredReason(AXAncestorIsLeafNode, leafNodeAncestor()));
return true;
}
AXObject* controlObject = correspondingControlForLabelElement();
if (controlObject && controlObject->isCheckboxOrRadio() &&
controlObject->nameFromLabelElement()) {
if (ignoredReasons) {
HTMLLabelElement* label = labelElementContainer();
if (label && label != getNode()) {
AXObject* labelAXObject = axObjectCache().getOrCreate(label);
ignoredReasons->push_back(
IgnoredReason(AXLabelContainer, labelAXObject));
}
ignoredReasons->push_back(IgnoredReason(AXLabelFor, controlObject));
}
return true;
}
Element* element = getNode()->isElementNode() ? toElement(getNode())
: getNode()->parentElement();
if (!getLayoutObject() && (!element || !element->isInCanvasSubtree()) &&
!equalIgnoringCase(getAttribute(aria_hiddenAttr), "false")) {
if (ignoredReasons)
ignoredReasons->push_back(IgnoredReason(AXNotRendered));
return true;
}
if (m_role == UnknownRole) {
if (ignoredReasons)
ignoredReasons->push_back(IgnoredReason(AXUninteresting));
return true;
}
return false;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | bool AXNodeObject::computeAccessibilityIsIgnored(
IgnoredReasons* ignoredReasons) const {
#if DCHECK_IS_ON()
ASSERT(m_initialized);
#endif
if (isDescendantOfLeafNode()) {
if (ignoredReasons)
ignoredReasons->push_back(
IgnoredReason(AXAncestorIsLeafNode, leafNodeAncestor()));
return true;
}
AXObject* controlObject = correspondingControlForLabelElement();
if (controlObject && controlObject->isCheckboxOrRadio() &&
controlObject->nameFromLabelElement()) {
if (ignoredReasons) {
HTMLLabelElement* label = labelElementContainer();
if (label && label != getNode()) {
AXObject* labelAXObject = axObjectCache().getOrCreate(label);
ignoredReasons->push_back(
IgnoredReason(AXLabelContainer, labelAXObject));
}
ignoredReasons->push_back(IgnoredReason(AXLabelFor, controlObject));
}
return true;
}
Element* element = getNode()->isElementNode() ? toElement(getNode())
: getNode()->parentElement();
if (!getLayoutObject() && (!element || !element->isInCanvasSubtree()) &&
!equalIgnoringASCIICase(getAttribute(aria_hiddenAttr), "false")) {
if (ignoredReasons)
ignoredReasons->push_back(IgnoredReason(AXNotRendered));
return true;
}
if (m_role == UnknownRole) {
if (ignoredReasons)
ignoredReasons->push_back(IgnoredReason(AXUninteresting));
return true;
}
return false;
}
| 171,911 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ExtensionsGuestViewMessageFilter::FrameNavigationHelper::GetGuestView() const {
return MimeHandlerViewGuest::From(
parent_site_instance_->GetProcess()->GetID(), guest_instance_id_)
->As<MimeHandlerViewGuest>();
}
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155}
CWE ID: CWE-362 | ExtensionsGuestViewMessageFilter::FrameNavigationHelper::GetGuestView() const {
| 173,042 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BluetoothChooserDesktop::~BluetoothChooserDesktop() {
bluetooth_chooser_controller_->ResetEventHandler();
}
Commit Message: Ensure device choosers are closed on navigation
The requestDevice() IPCs can race with navigation. This change ensures
that choosers are closed on navigation and adds browser tests to
exercise this for Web Bluetooth and WebUSB.
Bug: 723503
Change-Id: I66760161220e17bd2be9309cca228d161fe76e9c
Reviewed-on: https://chromium-review.googlesource.com/1099961
Commit-Queue: Reilly Grant <[email protected]>
Reviewed-by: Michael Wasserman <[email protected]>
Reviewed-by: Jeffrey Yasskin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#569900}
CWE ID: CWE-362 | BluetoothChooserDesktop::~BluetoothChooserDesktop() {
bluetooth_chooser_controller_->ResetEventHandler();
if (bubble_)
bubble_->CloseBubble(BUBBLE_CLOSE_FORCED);
}
| 173,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 int vmxnet3_post_load(void *opaque, int version_id)
{
VMXNET3State *s = opaque;
PCIDevice *d = PCI_DEVICE(s);
vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr);
vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr);
if (s->msix_used) {
if (!vmxnet3_use_msix_vectors(s, VMXNET3_MAX_INTRS)) {
VMW_WRPRN("Failed to re-use MSI-X vectors");
msix_uninit(d, &s->msix_bar, &s->msix_bar);
s->msix_used = false;
return -1;
}
}
return 0;
}
Commit Message:
CWE ID: CWE-20 | static int vmxnet3_post_load(void *opaque, int version_id)
{
VMXNET3State *s = opaque;
PCIDevice *d = PCI_DEVICE(s);
vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr);
vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr);
if (s->msix_used) {
if (!vmxnet3_use_msix_vectors(s, VMXNET3_MAX_INTRS)) {
VMW_WRPRN("Failed to re-use MSI-X vectors");
msix_uninit(d, &s->msix_bar, &s->msix_bar);
s->msix_used = false;
return -1;
}
}
vmxnet3_validate_interrupts(s);
return 0;
}
| 165,354 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ikev2_parent_inI1outR1_continue(struct pluto_crypto_req_cont *pcrc,
struct pluto_crypto_req *r,
err_t ugh)
{
struct ke_continuation *ke = (struct ke_continuation *)pcrc;
struct msg_digest *md = ke->md;
struct state *const st = md->st;
stf_status e;
DBG(DBG_CONTROLMORE,
DBG_log("ikev2 parent inI1outR1: calculated ke+nonce, sending R1"));
if (st == NULL) {
loglog(RC_LOG_SERIOUS,
"%s: Request was disconnected from state",
__FUNCTION__);
if (ke->md)
release_md(ke->md);
return;
}
/* XXX should check out ugh */
passert(ugh == NULL);
passert(cur_state == NULL);
passert(st != NULL);
passert(st->st_suspended_md == ke->md);
set_suspended(st, NULL); /* no longer connected or suspended */
set_cur_state(st);
st->st_calculating = FALSE;
e = ikev2_parent_inI1outR1_tail(pcrc, r);
if (ke->md != NULL) {
complete_v2_state_transition(&ke->md, e);
if (ke->md)
release_md(ke->md);
}
reset_globals();
passert(GLOBALS_ARE_RESET());
}
Commit Message: SECURITY: Properly handle IKEv2 I1 notification packet without KE payload
CWE ID: CWE-20 | static void ikev2_parent_inI1outR1_continue(struct pluto_crypto_req_cont *pcrc,
struct pluto_crypto_req *r,
err_t ugh)
{
struct ke_continuation *ke = (struct ke_continuation *)pcrc;
struct msg_digest *md = ke->md;
struct state *const st = md->st;
stf_status e;
DBG(DBG_CONTROLMORE,
DBG_log("ikev2 parent inI1outR1: calculated ke+nonce, sending R1"));
if (st == NULL) {
loglog(RC_LOG_SERIOUS,
"%s: Request was disconnected from state",
__FUNCTION__);
if (ke->md)
release_md(ke->md);
return;
}
/* XXX should check out ugh */
passert(ugh == NULL);
passert(cur_state == NULL);
passert(st != NULL);
passert(st->st_suspended_md == ke->md);
set_suspended(st, NULL); /* no longer connected or suspended */
set_cur_state(st);
st->st_calculating = FALSE;
e = ikev2_parent_inI1outR1_tail(pcrc, r);
if (ke->md != NULL) {
complete_v2_state_transition(&ke->md, e);
if (ke->md)
release_md(ke->md);
}
reset_globals();
}
| 166,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: xsltNumberFormat(xsltTransformContextPtr ctxt,
xsltNumberDataPtr data,
xmlNodePtr node)
{
xmlBufferPtr output = NULL;
int amount, i;
double number;
xsltFormat tokens;
int tempformat = 0;
if ((data->format == NULL) && (data->has_format != 0)) {
data->format = xsltEvalAttrValueTemplate(ctxt, data->node,
(const xmlChar *) "format",
XSLT_NAMESPACE);
tempformat = 1;
}
if (data->format == NULL) {
return;
}
output = xmlBufferCreate();
if (output == NULL)
goto XSLT_NUMBER_FORMAT_END;
xsltNumberFormatTokenize(data->format, &tokens);
/*
* Evaluate the XPath expression to find the value(s)
*/
if (data->value) {
amount = xsltNumberFormatGetValue(ctxt->xpathCtxt,
node,
data->value,
&number);
if (amount == 1) {
xsltNumberFormatInsertNumbers(data,
&number,
1,
&tokens,
output);
}
} else if (data->level) {
if (xmlStrEqual(data->level, (const xmlChar *) "single")) {
amount = xsltNumberFormatGetMultipleLevel(ctxt,
node,
data->countPat,
data->fromPat,
&number,
1,
data->doc,
data->node);
if (amount == 1) {
xsltNumberFormatInsertNumbers(data,
&number,
1,
&tokens,
output);
}
} else if (xmlStrEqual(data->level, (const xmlChar *) "multiple")) {
double numarray[1024];
int max = sizeof(numarray)/sizeof(numarray[0]);
amount = xsltNumberFormatGetMultipleLevel(ctxt,
node,
data->countPat,
data->fromPat,
numarray,
max,
data->doc,
data->node);
if (amount > 0) {
xsltNumberFormatInsertNumbers(data,
numarray,
amount,
&tokens,
output);
}
} else if (xmlStrEqual(data->level, (const xmlChar *) "any")) {
amount = xsltNumberFormatGetAnyLevel(ctxt,
node,
data->countPat,
data->fromPat,
&number,
data->doc,
data->node);
if (amount > 0) {
xsltNumberFormatInsertNumbers(data,
&number,
1,
&tokens,
output);
}
}
}
/* Insert number as text node */
xsltCopyTextString(ctxt, ctxt->insert, xmlBufferContent(output), 0);
if (tokens.start != NULL)
xmlFree(tokens.start);
if (tokens.end != NULL)
xmlFree(tokens.end);
for (i = 0;i < tokens.nTokens;i++) {
if (tokens.tokens[i].separator != NULL)
xmlFree(tokens.tokens[i].separator);
}
XSLT_NUMBER_FORMAT_END:
if (tempformat == 1) {
/* The format need to be recomputed each time */
data->format = NULL;
}
if (output != NULL)
xmlBufferFree(output);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | xsltNumberFormat(xsltTransformContextPtr ctxt,
xsltNumberDataPtr data,
xmlNodePtr node)
{
xmlBufferPtr output = NULL;
int amount, i;
double number;
xsltFormat tokens;
if (data->format != NULL) {
xsltNumberFormatTokenize(data->format, &tokens);
}
else {
xmlChar *format;
/* The format needs to be recomputed each time */
if (data->has_format == 0)
return;
format = xsltEvalAttrValueTemplate(ctxt, data->node,
(const xmlChar *) "format",
XSLT_NAMESPACE);
if (format == NULL)
return;
xsltNumberFormatTokenize(format, &tokens);
xmlFree(format);
}
output = xmlBufferCreate();
if (output == NULL)
goto XSLT_NUMBER_FORMAT_END;
/*
* Evaluate the XPath expression to find the value(s)
*/
if (data->value) {
amount = xsltNumberFormatGetValue(ctxt->xpathCtxt,
node,
data->value,
&number);
if (amount == 1) {
xsltNumberFormatInsertNumbers(data,
&number,
1,
&tokens,
output);
}
} else if (data->level) {
if (xmlStrEqual(data->level, (const xmlChar *) "single")) {
amount = xsltNumberFormatGetMultipleLevel(ctxt,
node,
data->countPat,
data->fromPat,
&number,
1);
if (amount == 1) {
xsltNumberFormatInsertNumbers(data,
&number,
1,
&tokens,
output);
}
} else if (xmlStrEqual(data->level, (const xmlChar *) "multiple")) {
double numarray[1024];
int max = sizeof(numarray)/sizeof(numarray[0]);
amount = xsltNumberFormatGetMultipleLevel(ctxt,
node,
data->countPat,
data->fromPat,
numarray,
max);
if (amount > 0) {
xsltNumberFormatInsertNumbers(data,
numarray,
amount,
&tokens,
output);
}
} else if (xmlStrEqual(data->level, (const xmlChar *) "any")) {
amount = xsltNumberFormatGetAnyLevel(ctxt,
node,
data->countPat,
data->fromPat,
&number);
if (amount > 0) {
xsltNumberFormatInsertNumbers(data,
&number,
1,
&tokens,
output);
}
}
}
/* Insert number as text node */
xsltCopyTextString(ctxt, ctxt->insert, xmlBufferContent(output), 0);
xmlBufferFree(output);
XSLT_NUMBER_FORMAT_END:
if (tokens.start != NULL)
xmlFree(tokens.start);
if (tokens.end != NULL)
xmlFree(tokens.end);
for (i = 0;i < tokens.nTokens;i++) {
if (tokens.tokens[i].separator != NULL)
xmlFree(tokens.tokens[i].separator);
}
}
| 173,306 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void LogoService::SetClockForTests(std::unique_ptr<base::Clock> clock) {
clock_for_test_ = std::move(clock);
}
Commit Message: Local NTP: add smoke tests for doodles
Split LogoService into LogoService interface and LogoServiceImpl to make
it easier to provide fake data to the test.
Bug: 768419
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I84639189d2db1b24a2e139936c99369352bab587
Reviewed-on: https://chromium-review.googlesource.com/690198
Reviewed-by: Sylvain Defresne <[email protected]>
Reviewed-by: Marc Treib <[email protected]>
Commit-Queue: Chris Pickel <[email protected]>
Cr-Commit-Position: refs/heads/master@{#505374}
CWE ID: CWE-119 | void LogoService::SetClockForTests(std::unique_ptr<base::Clock> clock) {
| 171,959 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AudioRendererHost::OnCreateStream(
int stream_id, const media::AudioParameters& params, int input_channels) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK(LookupById(stream_id) == NULL);
media::AudioParameters audio_params(params);
uint32 buffer_size = media::AudioBus::CalculateMemorySize(audio_params);
DCHECK_GT(buffer_size, 0U);
DCHECK_LE(buffer_size,
static_cast<uint32>(media::limits::kMaxPacketSizeInBytes));
DCHECK_GE(input_channels, 0);
DCHECK_LT(input_channels, media::limits::kMaxChannels);
int output_memory_size = AudioBus::CalculateMemorySize(audio_params);
DCHECK_GT(output_memory_size, 0);
int frames = audio_params.frames_per_buffer();
int input_memory_size =
AudioBus::CalculateMemorySize(input_channels, frames);
DCHECK_GE(input_memory_size, 0);
scoped_ptr<AudioEntry> entry(new AudioEntry());
uint32 io_buffer_size = output_memory_size + input_memory_size;
uint32 shared_memory_size =
media::TotalSharedMemorySizeInBytes(io_buffer_size);
if (!entry->shared_memory.CreateAndMapAnonymous(shared_memory_size)) {
SendErrorMessage(stream_id);
return;
}
scoped_ptr<AudioSyncReader> reader(
new AudioSyncReader(&entry->shared_memory, params, input_channels));
if (!reader->Init()) {
SendErrorMessage(stream_id);
return;
}
entry->reader.reset(reader.release());
entry->controller = media::AudioOutputController::Create(
audio_manager_, this, audio_params, entry->reader.get());
if (!entry->controller) {
SendErrorMessage(stream_id);
return;
}
entry->stream_id = stream_id;
audio_entries_.insert(std::make_pair(stream_id, entry.release()));
if (media_observer_)
media_observer_->OnSetAudioStreamStatus(this, stream_id, "created");
}
Commit Message: Improve validation when creating audio streams.
BUG=166795
Review URL: https://codereview.chromium.org/11647012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173981 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | void AudioRendererHost::OnCreateStream(
int stream_id, const media::AudioParameters& params, int input_channels) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// media::AudioParameters is validated in the deserializer.
if (input_channels < 0 ||
input_channels > media::limits::kMaxChannels ||
LookupById(stream_id) != NULL) {
SendErrorMessage(stream_id);
return;
}
media::AudioParameters audio_params(params);
int output_memory_size = AudioBus::CalculateMemorySize(audio_params);
int frames = audio_params.frames_per_buffer();
int input_memory_size =
AudioBus::CalculateMemorySize(input_channels, frames);
scoped_ptr<AudioEntry> entry(new AudioEntry());
uint32 io_buffer_size = output_memory_size + input_memory_size;
uint32 shared_memory_size =
media::TotalSharedMemorySizeInBytes(io_buffer_size);
if (!entry->shared_memory.CreateAndMapAnonymous(shared_memory_size)) {
SendErrorMessage(stream_id);
return;
}
scoped_ptr<AudioSyncReader> reader(
new AudioSyncReader(&entry->shared_memory, params, input_channels));
if (!reader->Init()) {
SendErrorMessage(stream_id);
return;
}
entry->reader.reset(reader.release());
entry->controller = media::AudioOutputController::Create(
audio_manager_, this, audio_params, entry->reader.get());
if (!entry->controller) {
SendErrorMessage(stream_id);
return;
}
entry->stream_id = stream_id;
audio_entries_.insert(std::make_pair(stream_id, entry.release()));
if (media_observer_)
media_observer_->OnSetAudioStreamStatus(this, stream_id, "created");
}
| 171,525 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void setup_format_params(int track)
{
int n;
int il;
int count;
int head_shift;
int track_shift;
struct fparm {
unsigned char track, head, sect, size;
} *here = (struct fparm *)floppy_track_buffer;
raw_cmd = &default_raw_cmd;
raw_cmd->track = track;
raw_cmd->flags = (FD_RAW_WRITE | FD_RAW_INTR | FD_RAW_SPIN |
FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK);
raw_cmd->rate = _floppy->rate & 0x43;
raw_cmd->cmd_count = NR_F;
COMMAND = FM_MODE(_floppy, FD_FORMAT);
DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, format_req.head);
F_SIZECODE = FD_SIZECODE(_floppy);
F_SECT_PER_TRACK = _floppy->sect << 2 >> F_SIZECODE;
F_GAP = _floppy->fmt_gap;
F_FILL = FD_FILL_BYTE;
raw_cmd->kernel_data = floppy_track_buffer;
raw_cmd->length = 4 * F_SECT_PER_TRACK;
/* allow for about 30ms for data transport per track */
head_shift = (F_SECT_PER_TRACK + 5) / 6;
/* a ``cylinder'' is two tracks plus a little stepping time */
track_shift = 2 * head_shift + 3;
/* position of logical sector 1 on this track */
n = (track_shift * format_req.track + head_shift * format_req.head)
% F_SECT_PER_TRACK;
/* determine interleave */
il = 1;
if (_floppy->fmt_gap < 0x22)
il++;
/* initialize field */
for (count = 0; count < F_SECT_PER_TRACK; ++count) {
here[count].track = format_req.track;
here[count].head = format_req.head;
here[count].sect = 0;
here[count].size = F_SIZECODE;
}
/* place logical sectors */
for (count = 1; count <= F_SECT_PER_TRACK; ++count) {
here[n].sect = count;
n = (n + il) % F_SECT_PER_TRACK;
if (here[n].sect) { /* sector busy, find next free sector */
++n;
if (n >= F_SECT_PER_TRACK) {
n -= F_SECT_PER_TRACK;
while (here[n].sect)
++n;
}
}
}
if (_floppy->stretch & FD_SECTBASEMASK) {
for (count = 0; count < F_SECT_PER_TRACK; count++)
here[count].sect += FD_SECTBASE(_floppy) - 1;
}
}
Commit Message: floppy: fix div-by-zero in setup_format_params
This fixes a divide by zero error in the setup_format_params function of
the floppy driver.
Two consecutive ioctls can trigger the bug: The first one should set the
drive geometry with such .sect and .rate values for the F_SECT_PER_TRACK
to become zero. Next, the floppy format operation should be called.
A floppy disk is not required to be inserted. An unprivileged user
could trigger the bug if the device is accessible.
The patch checks F_SECT_PER_TRACK for a non-zero value in the
set_geometry function. The proper check should involve a reasonable
upper limit for the .sect and .rate fields, but it could change the
UAPI.
The patch also checks F_SECT_PER_TRACK in the setup_format_params, and
cancels the formatting operation in case of zero.
The bug was found by syzkaller.
Signed-off-by: Denis Efremov <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-369 | static void setup_format_params(int track)
{
int n;
int il;
int count;
int head_shift;
int track_shift;
struct fparm {
unsigned char track, head, sect, size;
} *here = (struct fparm *)floppy_track_buffer;
raw_cmd = &default_raw_cmd;
raw_cmd->track = track;
raw_cmd->flags = (FD_RAW_WRITE | FD_RAW_INTR | FD_RAW_SPIN |
FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK);
raw_cmd->rate = _floppy->rate & 0x43;
raw_cmd->cmd_count = NR_F;
COMMAND = FM_MODE(_floppy, FD_FORMAT);
DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, format_req.head);
F_SIZECODE = FD_SIZECODE(_floppy);
F_SECT_PER_TRACK = _floppy->sect << 2 >> F_SIZECODE;
F_GAP = _floppy->fmt_gap;
F_FILL = FD_FILL_BYTE;
raw_cmd->kernel_data = floppy_track_buffer;
raw_cmd->length = 4 * F_SECT_PER_TRACK;
if (!F_SECT_PER_TRACK)
return;
/* allow for about 30ms for data transport per track */
head_shift = (F_SECT_PER_TRACK + 5) / 6;
/* a ``cylinder'' is two tracks plus a little stepping time */
track_shift = 2 * head_shift + 3;
/* position of logical sector 1 on this track */
n = (track_shift * format_req.track + head_shift * format_req.head)
% F_SECT_PER_TRACK;
/* determine interleave */
il = 1;
if (_floppy->fmt_gap < 0x22)
il++;
/* initialize field */
for (count = 0; count < F_SECT_PER_TRACK; ++count) {
here[count].track = format_req.track;
here[count].head = format_req.head;
here[count].sect = 0;
here[count].size = F_SIZECODE;
}
/* place logical sectors */
for (count = 1; count <= F_SECT_PER_TRACK; ++count) {
here[n].sect = count;
n = (n + il) % F_SECT_PER_TRACK;
if (here[n].sect) { /* sector busy, find next free sector */
++n;
if (n >= F_SECT_PER_TRACK) {
n -= F_SECT_PER_TRACK;
while (here[n].sect)
++n;
}
}
}
if (_floppy->stretch & FD_SECTBASEMASK) {
for (count = 0; count < F_SECT_PER_TRACK; count++)
here[count].sect += FD_SECTBASE(_floppy) - 1;
}
}
| 169,586 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t StreamingProcessor::processRecordingFrame() {
ATRACE_CALL();
status_t res;
sp<Camera2Heap> recordingHeap;
size_t heapIdx = 0;
nsecs_t timestamp;
sp<Camera2Client> client = mClient.promote();
if (client == 0) {
BufferItem imgBuffer;
res = mRecordingConsumer->acquireBuffer(&imgBuffer, 0);
if (res != OK) {
if (res != BufferItemConsumer::NO_BUFFER_AVAILABLE) {
ALOGE("%s: Camera %d: Can't acquire recording buffer: %s (%d)",
__FUNCTION__, mId, strerror(-res), res);
}
return res;
}
mRecordingConsumer->releaseBuffer(imgBuffer);
return OK;
}
{
/* acquire SharedParameters before mMutex so we don't dead lock
with Camera2Client code calling into StreamingProcessor */
SharedParameters::Lock l(client->getParameters());
Mutex::Autolock m(mMutex);
BufferItem imgBuffer;
res = mRecordingConsumer->acquireBuffer(&imgBuffer, 0);
if (res != OK) {
if (res != BufferItemConsumer::NO_BUFFER_AVAILABLE) {
ALOGE("%s: Camera %d: Can't acquire recording buffer: %s (%d)",
__FUNCTION__, mId, strerror(-res), res);
}
return res;
}
timestamp = imgBuffer.mTimestamp;
mRecordingFrameCount++;
ALOGVV("OnRecordingFrame: Frame %d", mRecordingFrameCount);
if (l.mParameters.state != Parameters::RECORD &&
l.mParameters.state != Parameters::VIDEO_SNAPSHOT) {
ALOGV("%s: Camera %d: Discarding recording image buffers "
"received after recording done", __FUNCTION__,
mId);
mRecordingConsumer->releaseBuffer(imgBuffer);
return INVALID_OPERATION;
}
if (mRecordingHeap == 0) {
size_t payloadSize = sizeof(VideoNativeMetadata);
ALOGV("%s: Camera %d: Creating recording heap with %zu buffers of "
"size %zu bytes", __FUNCTION__, mId,
mRecordingHeapCount, payloadSize);
mRecordingHeap = new Camera2Heap(payloadSize, mRecordingHeapCount,
"Camera2Client::RecordingHeap");
if (mRecordingHeap->mHeap->getSize() == 0) {
ALOGE("%s: Camera %d: Unable to allocate memory for recording",
__FUNCTION__, mId);
mRecordingConsumer->releaseBuffer(imgBuffer);
return NO_MEMORY;
}
for (size_t i = 0; i < mRecordingBuffers.size(); i++) {
if (mRecordingBuffers[i].mBuf !=
BufferItemConsumer::INVALID_BUFFER_SLOT) {
ALOGE("%s: Camera %d: Non-empty recording buffers list!",
__FUNCTION__, mId);
}
}
mRecordingBuffers.clear();
mRecordingBuffers.setCapacity(mRecordingHeapCount);
mRecordingBuffers.insertAt(0, mRecordingHeapCount);
mRecordingHeapHead = 0;
mRecordingHeapFree = mRecordingHeapCount;
}
if (mRecordingHeapFree == 0) {
ALOGE("%s: Camera %d: No free recording buffers, dropping frame",
__FUNCTION__, mId);
mRecordingConsumer->releaseBuffer(imgBuffer);
return NO_MEMORY;
}
heapIdx = mRecordingHeapHead;
mRecordingHeapHead = (mRecordingHeapHead + 1) % mRecordingHeapCount;
mRecordingHeapFree--;
ALOGVV("%s: Camera %d: Timestamp %lld",
__FUNCTION__, mId, timestamp);
ssize_t offset;
size_t size;
sp<IMemoryHeap> heap =
mRecordingHeap->mBuffers[heapIdx]->getMemory(&offset,
&size);
VideoNativeMetadata *payload = reinterpret_cast<VideoNativeMetadata*>(
(uint8_t*)heap->getBase() + offset);
payload->eType = kMetadataBufferTypeANWBuffer;
payload->pBuffer = imgBuffer.mGraphicBuffer->getNativeBuffer();
payload->nFenceFd = -1;
ALOGVV("%s: Camera %d: Sending out ANWBuffer %p",
__FUNCTION__, mId, payload->pBuffer);
mRecordingBuffers.replaceAt(imgBuffer, heapIdx);
recordingHeap = mRecordingHeap;
}
Camera2Client::SharedCameraCallbacks::Lock l(client->mSharedCameraCallbacks);
if (l.mRemoteCallback != 0) {
l.mRemoteCallback->dataCallbackTimestamp(timestamp,
CAMERA_MSG_VIDEO_FRAME,
recordingHeap->mBuffers[heapIdx]);
} else {
ALOGW("%s: Camera %d: Remote callback gone", __FUNCTION__, mId);
}
return OK;
}
Commit Message: DO NOT MERGE: Camera: Adjust pointers to ANW buffers to avoid infoleak
Subtract address of a random static object from pointers being routed
through app process.
Bug: 28466701
Change-Id: Idcbfe81e9507433769672f3dc6d67db5eeed4e04
CWE ID: CWE-200 | status_t StreamingProcessor::processRecordingFrame() {
ATRACE_CALL();
status_t res;
sp<Camera2Heap> recordingHeap;
size_t heapIdx = 0;
nsecs_t timestamp;
sp<Camera2Client> client = mClient.promote();
if (client == 0) {
BufferItem imgBuffer;
res = mRecordingConsumer->acquireBuffer(&imgBuffer, 0);
if (res != OK) {
if (res != BufferItemConsumer::NO_BUFFER_AVAILABLE) {
ALOGE("%s: Camera %d: Can't acquire recording buffer: %s (%d)",
__FUNCTION__, mId, strerror(-res), res);
}
return res;
}
mRecordingConsumer->releaseBuffer(imgBuffer);
return OK;
}
{
/* acquire SharedParameters before mMutex so we don't dead lock
with Camera2Client code calling into StreamingProcessor */
SharedParameters::Lock l(client->getParameters());
Mutex::Autolock m(mMutex);
BufferItem imgBuffer;
res = mRecordingConsumer->acquireBuffer(&imgBuffer, 0);
if (res != OK) {
if (res != BufferItemConsumer::NO_BUFFER_AVAILABLE) {
ALOGE("%s: Camera %d: Can't acquire recording buffer: %s (%d)",
__FUNCTION__, mId, strerror(-res), res);
}
return res;
}
timestamp = imgBuffer.mTimestamp;
mRecordingFrameCount++;
ALOGVV("OnRecordingFrame: Frame %d", mRecordingFrameCount);
if (l.mParameters.state != Parameters::RECORD &&
l.mParameters.state != Parameters::VIDEO_SNAPSHOT) {
ALOGV("%s: Camera %d: Discarding recording image buffers "
"received after recording done", __FUNCTION__,
mId);
mRecordingConsumer->releaseBuffer(imgBuffer);
return INVALID_OPERATION;
}
if (mRecordingHeap == 0) {
size_t payloadSize = sizeof(VideoNativeMetadata);
ALOGV("%s: Camera %d: Creating recording heap with %zu buffers of "
"size %zu bytes", __FUNCTION__, mId,
mRecordingHeapCount, payloadSize);
mRecordingHeap = new Camera2Heap(payloadSize, mRecordingHeapCount,
"Camera2Client::RecordingHeap");
if (mRecordingHeap->mHeap->getSize() == 0) {
ALOGE("%s: Camera %d: Unable to allocate memory for recording",
__FUNCTION__, mId);
mRecordingConsumer->releaseBuffer(imgBuffer);
return NO_MEMORY;
}
for (size_t i = 0; i < mRecordingBuffers.size(); i++) {
if (mRecordingBuffers[i].mBuf !=
BufferItemConsumer::INVALID_BUFFER_SLOT) {
ALOGE("%s: Camera %d: Non-empty recording buffers list!",
__FUNCTION__, mId);
}
}
mRecordingBuffers.clear();
mRecordingBuffers.setCapacity(mRecordingHeapCount);
mRecordingBuffers.insertAt(0, mRecordingHeapCount);
mRecordingHeapHead = 0;
mRecordingHeapFree = mRecordingHeapCount;
}
if (mRecordingHeapFree == 0) {
ALOGE("%s: Camera %d: No free recording buffers, dropping frame",
__FUNCTION__, mId);
mRecordingConsumer->releaseBuffer(imgBuffer);
return NO_MEMORY;
}
heapIdx = mRecordingHeapHead;
mRecordingHeapHead = (mRecordingHeapHead + 1) % mRecordingHeapCount;
mRecordingHeapFree--;
ALOGVV("%s: Camera %d: Timestamp %lld",
__FUNCTION__, mId, timestamp);
ssize_t offset;
size_t size;
sp<IMemoryHeap> heap =
mRecordingHeap->mBuffers[heapIdx]->getMemory(&offset,
&size);
VideoNativeMetadata *payload = reinterpret_cast<VideoNativeMetadata*>(
(uint8_t*)heap->getBase() + offset);
payload->eType = kMetadataBufferTypeANWBuffer;
payload->pBuffer = imgBuffer.mGraphicBuffer->getNativeBuffer();
// b/28466701
payload->pBuffer = (ANativeWindowBuffer*)((uint8_t*)payload->pBuffer -
ICameraRecordingProxy::getCommonBaseAddress());
payload->nFenceFd = -1;
ALOGVV("%s: Camera %d: Sending out ANWBuffer %p",
__FUNCTION__, mId, payload->pBuffer);
mRecordingBuffers.replaceAt(imgBuffer, heapIdx);
recordingHeap = mRecordingHeap;
}
Camera2Client::SharedCameraCallbacks::Lock l(client->mSharedCameraCallbacks);
if (l.mRemoteCallback != 0) {
l.mRemoteCallback->dataCallbackTimestamp(timestamp,
CAMERA_MSG_VIDEO_FRAME,
recordingHeap->mBuffers[heapIdx]);
} else {
ALOGW("%s: Camera %d: Remote callback gone", __FUNCTION__, mId);
}
return OK;
}
| 173,511 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void comps_objmrtree_unite(COMPS_ObjMRTree *rt1, COMPS_ObjMRTree *rt2) {
COMPS_HSList *tmplist, *tmp_subnodes;
COMPS_HSListItem *it;
COMPS_ObjListIt *it2;
struct Pair {
COMPS_HSList * subnodes;
char * key;
char added;
} *pair, *parent_pair;
pair = malloc(sizeof(struct Pair));
pair->subnodes = rt2->subnodes;
pair->key = NULL;
tmplist = comps_hslist_create();
comps_hslist_init(tmplist, NULL, NULL, &free);
comps_hslist_append(tmplist, pair, 0);
while (tmplist->first != NULL) {
it = tmplist->first;
comps_hslist_remove(tmplist, tmplist->first);
tmp_subnodes = ((struct Pair*)it->data)->subnodes;
parent_pair = (struct Pair*) it->data;
free(it);
pair->added = 0;
for (it = tmp_subnodes->first; it != NULL; it=it->next) {
pair = malloc(sizeof(struct Pair));
pair->subnodes = ((COMPS_ObjMRTreeData*)it->data)->subnodes;
if (parent_pair->key != NULL) {
pair->key =
malloc(sizeof(char)
* (strlen(((COMPS_ObjMRTreeData*)it->data)->key)
+ strlen(parent_pair->key) + 1));
memcpy(pair->key, parent_pair->key,
sizeof(char) * strlen(parent_pair->key));
memcpy(pair->key+strlen(parent_pair->key),
((COMPS_ObjMRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_ObjMRTreeData*)it->data)->key)+1));
} else {
pair->key = malloc(sizeof(char)*
(strlen(((COMPS_ObjMRTreeData*)it->data)->key) +
1));
memcpy(pair->key, ((COMPS_ObjMRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_ObjMRTreeData*)it->data)->key)+1));
}
/* current node has data */
if (((COMPS_ObjMRTreeData*)it->data)->data->first != NULL) {
for (it2 = ((COMPS_ObjMRTreeData*)it->data)->data->first;
it2 != NULL; it2 = it2->next) {
comps_objmrtree_set(rt1, pair->key, it2->comps_obj);
}
if (((COMPS_ObjMRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair->key);
free(pair);
}
/* current node hasn't data */
} else {
if (((COMPS_ObjMRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair->key);
free(pair);
}
}
}
free(parent_pair->key);
free(parent_pair);
}
comps_hslist_destroy(&tmplist);
}
Commit Message: Fix UAF in comps_objmrtree_unite function
The added field is not used at all in many places and it is probably the
left-over of some copy-paste.
CWE ID: CWE-416 | void comps_objmrtree_unite(COMPS_ObjMRTree *rt1, COMPS_ObjMRTree *rt2) {
COMPS_HSList *tmplist, *tmp_subnodes;
COMPS_HSListItem *it;
COMPS_ObjListIt *it2;
struct Pair {
COMPS_HSList * subnodes;
char * key;
} *pair, *parent_pair;
pair = malloc(sizeof(struct Pair));
pair->subnodes = rt2->subnodes;
pair->key = NULL;
tmplist = comps_hslist_create();
comps_hslist_init(tmplist, NULL, NULL, &free);
comps_hslist_append(tmplist, pair, 0);
while (tmplist->first != NULL) {
it = tmplist->first;
comps_hslist_remove(tmplist, tmplist->first);
tmp_subnodes = ((struct Pair*)it->data)->subnodes;
parent_pair = (struct Pair*) it->data;
free(it);
for (it = tmp_subnodes->first; it != NULL; it=it->next) {
pair = malloc(sizeof(struct Pair));
pair->subnodes = ((COMPS_ObjMRTreeData*)it->data)->subnodes;
if (parent_pair->key != NULL) {
pair->key =
malloc(sizeof(char)
* (strlen(((COMPS_ObjMRTreeData*)it->data)->key)
+ strlen(parent_pair->key) + 1));
memcpy(pair->key, parent_pair->key,
sizeof(char) * strlen(parent_pair->key));
memcpy(pair->key+strlen(parent_pair->key),
((COMPS_ObjMRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_ObjMRTreeData*)it->data)->key)+1));
} else {
pair->key = malloc(sizeof(char)*
(strlen(((COMPS_ObjMRTreeData*)it->data)->key) +
1));
memcpy(pair->key, ((COMPS_ObjMRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_ObjMRTreeData*)it->data)->key)+1));
}
/* current node has data */
if (((COMPS_ObjMRTreeData*)it->data)->data->first != NULL) {
for (it2 = ((COMPS_ObjMRTreeData*)it->data)->data->first;
it2 != NULL; it2 = it2->next) {
comps_objmrtree_set(rt1, pair->key, it2->comps_obj);
}
if (((COMPS_ObjMRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair->key);
free(pair);
}
/* current node hasn't data */
} else {
if (((COMPS_ObjMRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair->key);
free(pair);
}
}
}
free(parent_pair->key);
free(parent_pair);
}
comps_hslist_destroy(&tmplist);
}
| 169,751 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.