instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer(
const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params) {
TRACE_EVENT0("renderer",
"GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer");
ScopedSendOnIOThread delayed_send(
host_id_,
new AcceleratedSurfaceMsg_BufferPresented(params.route_id, false, 0));
RenderWidgetHostViewPort* view =
GetRenderWidgetHostViewFromSurfaceID(params.surface_id);
if (!view)
return;
delayed_send.Cancel();
view->AcceleratedSurfacePostSubBuffer(params, host_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 GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer(
const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params) {
TRACE_EVENT0("renderer",
"GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer");
ScopedSendOnIOThread delayed_send(
host_id_,
new AcceleratedSurfaceMsg_BufferPresented(params.route_id,
params.surface_handle,
0));
RenderWidgetHostViewPort* view =
GetRenderWidgetHostViewFromSurfaceID(params.surface_id);
if (!view)
return;
delayed_send.Cancel();
view->AcceleratedSurfacePostSubBuffer(params, host_id_);
}
| 171,359 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long Block::Parse(const Cluster* pCluster)
{
if (pCluster == NULL)
return -1;
if (pCluster->m_pSegment == NULL)
return -1;
assert(m_start >= 0);
assert(m_size >= 0);
assert(m_track <= 0);
assert(m_frames == NULL);
assert(m_frame_count <= 0);
long long pos = m_start;
const long long stop = m_start + m_size;
long len;
IMkvReader* const pReader = pCluster->m_pSegment->m_pReader;
m_track = ReadUInt(pReader, pos, len);
if (m_track <= 0)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > stop)
return E_FILE_FORMAT_INVALID;
pos += len; //consume track number
if ((stop - pos) < 2)
return E_FILE_FORMAT_INVALID;
long status;
long long value;
status = UnserializeInt(pReader, pos, 2, value);
if (status)
return E_FILE_FORMAT_INVALID;
if (value < SHRT_MIN)
return E_FILE_FORMAT_INVALID;
if (value > SHRT_MAX)
return E_FILE_FORMAT_INVALID;
m_timecode = static_cast<short>(value);
pos += 2;
if ((stop - pos) <= 0)
return E_FILE_FORMAT_INVALID;
status = pReader->Read(pos, 1, &m_flags);
if (status)
return E_FILE_FORMAT_INVALID;
const int lacing = int(m_flags & 0x06) >> 1;
++pos; //consume flags byte
if (lacing == 0) //no lacing
{
if (pos > stop)
return E_FILE_FORMAT_INVALID;
m_frame_count = 1;
m_frames = new Frame[m_frame_count];
Frame& f = m_frames[0];
f.pos = pos;
const long long frame_size = stop - pos;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
f.len = static_cast<long>(frame_size);
return 0; //success
}
if (pos >= stop)
return E_FILE_FORMAT_INVALID;
unsigned char biased_count;
status = pReader->Read(pos, 1, &biased_count);
if (status)
return E_FILE_FORMAT_INVALID;
++pos; //consume frame count
assert(pos <= stop);
m_frame_count = int(biased_count) + 1;
m_frames = new Frame[m_frame_count];
assert(m_frames);
if (lacing == 1) //Xiph
{
Frame* pf = m_frames;
Frame* const pf_end = pf + m_frame_count;
long size = 0;
int frame_count = m_frame_count;
while (frame_count > 1)
{
long frame_size = 0;
for (;;)
{
unsigned char val;
if (pos >= stop)
return E_FILE_FORMAT_INVALID;
status = pReader->Read(pos, 1, &val);
if (status)
return E_FILE_FORMAT_INVALID;
++pos; //consume xiph size byte
frame_size += val;
if (val < 255)
break;
}
Frame& f = *pf++;
assert(pf < pf_end);
f.pos = 0; //patch later
f.len = frame_size;
size += frame_size; //contribution of this frame
--frame_count;
}
assert(pf < pf_end);
assert(pos <= stop);
{
Frame& f = *pf++;
if (pf != pf_end)
return E_FILE_FORMAT_INVALID;
f.pos = 0; //patch later
const long long total_size = stop - pos;
if (total_size < size)
return E_FILE_FORMAT_INVALID;
const long long frame_size = total_size - size;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
f.len = static_cast<long>(frame_size);
}
pf = m_frames;
while (pf != pf_end)
{
Frame& f = *pf++;
assert((pos + f.len) <= stop);
f.pos = pos;
pos += f.len;
}
assert(pos == stop);
}
else if (lacing == 2) //fixed-size lacing
{
const long long total_size = stop - pos;
if ((total_size % m_frame_count) != 0)
return E_FILE_FORMAT_INVALID;
const long long frame_size = total_size / m_frame_count;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
Frame* pf = m_frames;
Frame* const pf_end = pf + m_frame_count;
while (pf != pf_end)
{
assert((pos + frame_size) <= stop);
Frame& f = *pf++;
f.pos = pos;
f.len = static_cast<long>(frame_size);
pos += frame_size;
}
assert(pos == stop);
}
else
{
assert(lacing == 3); //EBML lacing
if (pos >= stop)
return E_FILE_FORMAT_INVALID;
long size = 0;
int frame_count = m_frame_count;
long long frame_size = ReadUInt(pReader, pos, len);
if (frame_size < 0)
return E_FILE_FORMAT_INVALID;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > stop)
return E_FILE_FORMAT_INVALID;
pos += len; //consume length of size of first frame
if ((pos + frame_size) > stop)
return E_FILE_FORMAT_INVALID;
Frame* pf = m_frames;
Frame* const pf_end = pf + m_frame_count;
{
Frame& curr = *pf;
curr.pos = 0; //patch later
curr.len = static_cast<long>(frame_size);
size += curr.len; //contribution of this frame
}
--frame_count;
while (frame_count > 1)
{
if (pos >= stop)
return E_FILE_FORMAT_INVALID;
assert(pf < pf_end);
const Frame& prev = *pf++;
assert(prev.len == frame_size);
if (prev.len != frame_size)
return E_FILE_FORMAT_INVALID;
assert(pf < pf_end);
Frame& curr = *pf;
curr.pos = 0; //patch later
const long long delta_size_ = ReadUInt(pReader, pos, len);
if (delta_size_ < 0)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > stop)
return E_FILE_FORMAT_INVALID;
pos += len; //consume length of (delta) size
assert(pos <= stop);
const int exp = 7*len - 1;
const long long bias = (1LL << exp) - 1LL;
const long long delta_size = delta_size_ - bias;
frame_size += delta_size;
if (frame_size < 0)
return E_FILE_FORMAT_INVALID;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
curr.len = static_cast<long>(frame_size);
size += curr.len; //contribution of this frame
--frame_count;
}
{
assert(pos <= stop);
assert(pf < pf_end);
const Frame& prev = *pf++;
assert(prev.len == frame_size);
if (prev.len != frame_size)
return E_FILE_FORMAT_INVALID;
assert(pf < pf_end);
Frame& curr = *pf++;
assert(pf == pf_end);
curr.pos = 0; //patch later
const long long total_size = stop - pos;
if (total_size < size)
return E_FILE_FORMAT_INVALID;
frame_size = total_size - size;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
curr.len = static_cast<long>(frame_size);
}
pf = m_frames;
while (pf != pf_end)
{
Frame& f = *pf++;
assert((pos + f.len) <= stop);
f.pos = pos;
pos += f.len;
}
assert(pos == stop);
}
return 0; //success
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
long Block::Parse(const Cluster* pCluster)
m_track = ReadUInt(pReader, pos, len);
if (m_track <= 0)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > stop)
return E_FILE_FORMAT_INVALID;
pos += len; // consume track number
if ((stop - pos) < 2)
return E_FILE_FORMAT_INVALID;
long status;
long long value;
status = UnserializeInt(pReader, pos, 2, value);
if (status)
return E_FILE_FORMAT_INVALID;
if (value < SHRT_MIN)
return E_FILE_FORMAT_INVALID;
if (value > SHRT_MAX)
return E_FILE_FORMAT_INVALID;
m_timecode = static_cast<short>(value);
pos += 2;
if ((stop - pos) <= 0)
return E_FILE_FORMAT_INVALID;
status = pReader->Read(pos, 1, &m_flags);
if (status)
return E_FILE_FORMAT_INVALID;
const int lacing = int(m_flags & 0x06) >> 1;
++pos; // consume flags byte
if (lacing == 0) { // no lacing
if (pos > stop)
return E_FILE_FORMAT_INVALID;
m_frame_count = 1;
m_frames = new Frame[m_frame_count];
Frame& f = m_frames[0];
f.pos = pos;
const long long frame_size = stop - pos;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
f.len = static_cast<long>(frame_size);
return 0; // success
}
if (pos >= stop)
return E_FILE_FORMAT_INVALID;
unsigned char biased_count;
status = pReader->Read(pos, 1, &biased_count);
if (status)
return E_FILE_FORMAT_INVALID;
++pos; // consume frame count
assert(pos <= stop);
m_frame_count = int(biased_count) + 1;
m_frames = new Frame[m_frame_count];
assert(m_frames);
if (lacing == 1) { // Xiph
Frame* pf = m_frames;
Frame* const pf_end = pf + m_frame_count;
long size = 0;
int frame_count = m_frame_count;
while (frame_count > 1) {
long frame_size = 0;
for (;;) {
unsigned char val;
if (pos >= stop)
return E_FILE_FORMAT_INVALID;
status = pReader->Read(pos, 1, &val);
if (status)
return E_FILE_FORMAT_INVALID;
++pos; // consume xiph size byte
frame_size += val;
if (val < 255)
break;
}
Frame& f = *pf++;
assert(pf < pf_end);
f.pos = 0; // patch later
f.len = frame_size;
size += frame_size; // contribution of this frame
--frame_count;
}
assert(pf < pf_end);
assert(pos <= stop);
{
Frame& f = *pf++;
if (pf != pf_end)
return E_FILE_FORMAT_INVALID;
f.pos = 0; // patch later
const long long total_size = stop - pos;
if (total_size < size)
return E_FILE_FORMAT_INVALID;
const long long frame_size = total_size - size;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
f.len = static_cast<long>(frame_size);
}
pf = m_frames;
while (pf != pf_end) {
Frame& f = *pf++;
assert((pos + f.len) <= stop);
f.pos = pos;
pos += f.len;
}
assert(pos == stop);
} else if (lacing == 2) { // fixed-size lacing
const long long total_size = stop - pos;
if ((total_size % m_frame_count) != 0)
return E_FILE_FORMAT_INVALID;
const long long frame_size = total_size / m_frame_count;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
Frame* pf = m_frames;
Frame* const pf_end = pf + m_frame_count;
while (pf != pf_end) {
assert((pos + frame_size) <= stop);
Frame& f = *pf++;
f.pos = pos;
f.len = static_cast<long>(frame_size);
pos += frame_size;
}
assert(pos == stop);
} else {
assert(lacing == 3); // EBML lacing
if (pos >= stop)
return E_FILE_FORMAT_INVALID;
long size = 0;
int frame_count = m_frame_count;
long long frame_size = ReadUInt(pReader, pos, len);
if (frame_size < 0)
return E_FILE_FORMAT_INVALID;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > stop)
return E_FILE_FORMAT_INVALID;
pos += len; // consume length of size of first frame
if ((pos + frame_size) > stop)
return E_FILE_FORMAT_INVALID;
Frame* pf = m_frames;
Frame* const pf_end = pf + m_frame_count;
{
Frame& curr = *pf;
curr.pos = 0; // patch later
curr.len = static_cast<long>(frame_size);
size += curr.len; // contribution of this frame
}
--frame_count;
while (frame_count > 1) {
if (pos >= stop)
return E_FILE_FORMAT_INVALID;
assert(pf < pf_end);
const Frame& prev = *pf++;
assert(prev.len == frame_size);
if (prev.len != frame_size)
return E_FILE_FORMAT_INVALID;
assert(pf < pf_end);
Frame& curr = *pf;
curr.pos = 0; // patch later
const long long delta_size_ = ReadUInt(pReader, pos, len);
if (delta_size_ < 0)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > stop)
return E_FILE_FORMAT_INVALID;
pos += len; // consume length of (delta) size
assert(pos <= stop);
const int exp = 7 * len - 1;
const long long bias = (1LL << exp) - 1LL;
const long long delta_size = delta_size_ - bias;
frame_size += delta_size;
if (frame_size < 0)
return E_FILE_FORMAT_INVALID;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
curr.len = static_cast<long>(frame_size);
size += curr.len; // contribution of this frame
--frame_count;
}
{
assert(pos <= stop);
assert(pf < pf_end);
const Frame& prev = *pf++;
assert(prev.len == frame_size);
if (prev.len != frame_size)
return E_FILE_FORMAT_INVALID;
assert(pf < pf_end);
Frame& curr = *pf++;
assert(pf == pf_end);
curr.pos = 0; // patch later
const long long total_size = stop - pos;
if (total_size < size)
return E_FILE_FORMAT_INVALID;
frame_size = total_size - size;
if (frame_size > LONG_MAX)
return E_FILE_FORMAT_INVALID;
curr.len = static_cast<long>(frame_size);
}
pf = m_frames;
while (pf != pf_end) {
Frame& f = *pf++;
assert((pos + f.len) <= stop);
f.pos = pos;
pos += f.len;
}
assert(pos == stop);
}
return 0; // success
}
| 174,412 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void VRDisplay::ProcessScheduledAnimations(double timestamp) {
Document* doc = this->GetDocument();
if (!doc || display_blurred_ || !scripted_animation_controller_)
return;
TRACE_EVENT1("gpu", "VRDisplay::OnVSync", "frame", vr_frame_id_);
AutoReset<bool> animating(&in_animation_frame_, true);
pending_raf_ = false;
scripted_animation_controller_->ServiceScriptedAnimations(timestamp);
if (is_presenting_ && !capabilities_->hasExternalDisplay()) {
Platform::Current()->CurrentThread()->GetWebTaskRunner()->PostTask(
BLINK_FROM_HERE, WTF::Bind(&VRDisplay::ProcessScheduledWindowAnimations,
WrapWeakPersistent(this), timestamp));
}
}
Commit Message: WebVR: fix initial vsync
Applications sometimes use window.rAF while not presenting, then switch to
vrDisplay.rAF after presentation starts. Depending on the animation loop's
timing, this can cause a race condition where presentation has been started
but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync
being processed after presentation starts so that a queued window.rAF
can run and schedule a vrDisplay.rAF.
BUG=711789
Review-Url: https://codereview.chromium.org/2848483003
Cr-Commit-Position: refs/heads/master@{#468167}
CWE ID:
|
void VRDisplay::ProcessScheduledAnimations(double timestamp) {
DVLOG(2) << __FUNCTION__;
Document* doc = this->GetDocument();
if (!doc || display_blurred_) {
DVLOG(2) << __FUNCTION__ << ": early exit, doc=" << doc
<< " display_blurred_=" << display_blurred_;
return;
}
TRACE_EVENT1("gpu", "VRDisplay::OnVSync", "frame", vr_frame_id_);
if (pending_vrdisplay_raf_ && scripted_animation_controller_) {
// Run the callback, making sure that in_animation_frame_ is only
// true for the vrDisplay rAF and not for a legacy window rAF
// that may be called later.
AutoReset<bool> animating(&in_animation_frame_, true);
pending_vrdisplay_raf_ = false;
scripted_animation_controller_->ServiceScriptedAnimations(timestamp);
}
if (is_presenting_ && !capabilities_->hasExternalDisplay()) {
Platform::Current()->CurrentThread()->GetWebTaskRunner()->PostTask(
BLINK_FROM_HERE, WTF::Bind(&VRDisplay::ProcessScheduledWindowAnimations,
WrapWeakPersistent(this), timestamp));
}
}
| 171,998 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: __reiserfs_set_acl(struct reiserfs_transaction_handle *th, struct inode *inode,
int type, struct posix_acl *acl)
{
char *name;
void *value = NULL;
size_t size = 0;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_equiv_mode(acl, &inode->i_mode);
if (error < 0)
return error;
else {
if (error == 0)
acl = NULL;
}
}
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = reiserfs_posix_acl_to_disk(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
error = reiserfs_xattr_set_handle(th, inode, name, value, size, 0);
/*
* Ensure that the inode gets dirtied if we're only using
* the mode bits and an old ACL didn't exist. We don't need
* to check if the inode is hashed here since we won't get
* called by reiserfs_inherit_default_acl().
*/
if (error == -ENODATA) {
error = 0;
if (type == ACL_TYPE_ACCESS) {
inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
}
}
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
Commit Message: posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Jeff Layton <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Andreas Gruenbacher <[email protected]>
CWE ID: CWE-285
|
__reiserfs_set_acl(struct reiserfs_transaction_handle *th, struct inode *inode,
int type, struct posix_acl *acl)
{
char *name;
void *value = NULL;
size_t size = 0;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_update_mode(inode, &inode->i_mode, &acl);
if (error)
return error;
}
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = reiserfs_posix_acl_to_disk(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
error = reiserfs_xattr_set_handle(th, inode, name, value, size, 0);
/*
* Ensure that the inode gets dirtied if we're only using
* the mode bits and an old ACL didn't exist. We don't need
* to check if the inode is hashed here since we won't get
* called by reiserfs_inherit_default_acl().
*/
if (error == -ENODATA) {
error = 0;
if (type == ACL_TYPE_ACCESS) {
inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
}
}
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
| 166,978 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: sp<IMemoryHeap> BpMemory::getMemory(ssize_t* offset, size_t* size) const
{
if (mHeap == 0) {
Parcel data, reply;
data.writeInterfaceToken(IMemory::getInterfaceDescriptor());
if (remote()->transact(GET_MEMORY, data, &reply) == NO_ERROR) {
sp<IBinder> heap = reply.readStrongBinder();
ssize_t o = reply.readInt32();
size_t s = reply.readInt32();
if (heap != 0) {
mHeap = interface_cast<IMemoryHeap>(heap);
if (mHeap != 0) {
mOffset = o;
mSize = s;
}
}
}
}
if (offset) *offset = mOffset;
if (size) *size = mSize;
return mHeap;
}
Commit Message: Sanity check IMemory access versus underlying mmap
Bug 26877992
Change-Id: Ibbf4b1061e4675e4e96bc944a865b53eaf6984fe
CWE ID: CWE-264
|
sp<IMemoryHeap> BpMemory::getMemory(ssize_t* offset, size_t* size) const
{
if (mHeap == 0) {
Parcel data, reply;
data.writeInterfaceToken(IMemory::getInterfaceDescriptor());
if (remote()->transact(GET_MEMORY, data, &reply) == NO_ERROR) {
sp<IBinder> heap = reply.readStrongBinder();
ssize_t o = reply.readInt32();
size_t s = reply.readInt32();
if (heap != 0) {
mHeap = interface_cast<IMemoryHeap>(heap);
if (mHeap != 0) {
size_t heapSize = mHeap->getSize();
if (s <= heapSize
&& o >= 0
&& (static_cast<size_t>(o) <= heapSize - s)) {
mOffset = o;
mSize = s;
} else {
// Hm.
android_errorWriteWithInfoLog(0x534e4554,
"26877992", -1, NULL, 0);
mOffset = 0;
mSize = 0;
}
}
}
}
}
if (offset) *offset = mOffset;
if (size) *size = mSize;
return (mSize > 0) ? mHeap : 0;
}
| 173,906 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int writepng_init(mainprog_info *mainprog_ptr)
{
png_structp png_ptr; /* note: temporary variables! */
png_infop info_ptr;
int color_type, interlace_type;
/* could also replace libpng warning-handler (final NULL), but no need: */
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr,
writepng_error_handler, NULL);
if (!png_ptr)
return 4; /* out of memory */
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, NULL);
return 4; /* out of memory */
}
/* setjmp() must be called in every function that calls a PNG-writing
* libpng function, unless an alternate error handler was installed--
* but compatible error handlers must either use longjmp() themselves
* (as in this program) or some other method to return control to
* application code, so here we go: */
if (setjmp(mainprog_ptr->jmpbuf)) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return 2;
}
/* make sure outfile is (re)opened in BINARY mode */
png_init_io(png_ptr, mainprog_ptr->outfile);
/* set the compression levels--in general, always want to leave filtering
* turned on (except for palette images) and allow all of the filters,
* which is the default; want 32K zlib window, unless entire image buffer
* is 16K or smaller (unknown here)--also the default; usually want max
* compression (NOT the default); and remaining compression flags should
* be left alone */
png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
/*
>> this is default for no filtering; Z_FILTERED is default otherwise:
png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY);
>> these are all defaults:
png_set_compression_mem_level(png_ptr, 8);
png_set_compression_window_bits(png_ptr, 15);
png_set_compression_method(png_ptr, 8);
*/
/* set the image parameters appropriately */
if (mainprog_ptr->pnmtype == 5)
color_type = PNG_COLOR_TYPE_GRAY;
else if (mainprog_ptr->pnmtype == 6)
color_type = PNG_COLOR_TYPE_RGB;
else if (mainprog_ptr->pnmtype == 8)
color_type = PNG_COLOR_TYPE_RGB_ALPHA;
else {
png_destroy_write_struct(&png_ptr, &info_ptr);
return 11;
}
interlace_type = mainprog_ptr->interlaced? PNG_INTERLACE_ADAM7 :
PNG_INTERLACE_NONE;
png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height,
mainprog_ptr->sample_depth, color_type, interlace_type,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
if (mainprog_ptr->gamma > 0.0)
png_set_gAMA(png_ptr, info_ptr, mainprog_ptr->gamma);
if (mainprog_ptr->have_bg) { /* we know it's RGBA, not gray+alpha */
png_color_16 background;
background.red = mainprog_ptr->bg_red;
background.green = mainprog_ptr->bg_green;
background.blue = mainprog_ptr->bg_blue;
png_set_bKGD(png_ptr, info_ptr, &background);
}
if (mainprog_ptr->have_time) {
png_time modtime;
png_convert_from_time_t(&modtime, mainprog_ptr->modtime);
png_set_tIME(png_ptr, info_ptr, &modtime);
}
if (mainprog_ptr->have_text) {
png_text text[6];
int num_text = 0;
if (mainprog_ptr->have_text & TEXT_TITLE) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Title";
text[num_text].text = mainprog_ptr->title;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_AUTHOR) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Author";
text[num_text].text = mainprog_ptr->author;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_DESC) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Description";
text[num_text].text = mainprog_ptr->desc;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_COPY) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Copyright";
text[num_text].text = mainprog_ptr->copyright;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_EMAIL) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "E-mail";
text[num_text].text = mainprog_ptr->email;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_URL) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "URL";
text[num_text].text = mainprog_ptr->url;
++num_text;
}
png_set_text(png_ptr, info_ptr, text, num_text);
}
/* write all chunks up to (but not including) first IDAT */
png_write_info(png_ptr, info_ptr);
/* if we wanted to write any more text info *after* the image data, we
* would set up text struct(s) here and call png_set_text() again, with
* just the new data; png_set_tIME() could also go here, but it would
* have no effect since we already called it above (only one tIME chunk
* allowed) */
/* set up the transformations: for now, just pack low-bit-depth pixels
* into bytes (one, two or four pixels per byte) */
png_set_packing(png_ptr);
/* png_set_shift(png_ptr, &sig_bit); to scale low-bit-depth values */
/* make sure we save our pointers for use in writepng_encode_image() */
mainprog_ptr->png_ptr = png_ptr;
mainprog_ptr->info_ptr = info_ptr;
/* OK, that's all we need to do for now; return happy */
return 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
int writepng_init(mainprog_info *mainprog_ptr)
{
png_structp png_ptr; /* note: temporary variables! */
png_infop info_ptr;
int color_type, interlace_type;
/* could also replace libpng warning-handler (final NULL), but no need: */
png_ptr = png_create_write_struct(png_get_libpng_ver(NULL), mainprog_ptr,
writepng_error_handler, NULL);
if (!png_ptr)
return 4; /* out of memory */
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, NULL);
return 4; /* out of memory */
}
/* setjmp() must be called in every function that calls a PNG-writing
* libpng function, unless an alternate error handler was installed--
* but compatible error handlers must either use longjmp() themselves
* (as in this program) or some other method to return control to
* application code, so here we go: */
if (setjmp(mainprog_ptr->jmpbuf)) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return 2;
}
/* make sure outfile is (re)opened in BINARY mode */
png_init_io(png_ptr, mainprog_ptr->outfile);
/* set the compression levels--in general, always want to leave filtering
* turned on (except for palette images) and allow all of the filters,
* which is the default; want 32K zlib window, unless entire image buffer
* is 16K or smaller (unknown here)--also the default; usually want max
* compression (NOT the default); and remaining compression flags should
* be left alone */
png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
/*
>> this is default for no filtering; Z_FILTERED is default otherwise:
png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY);
>> these are all defaults:
png_set_compression_mem_level(png_ptr, 8);
png_set_compression_window_bits(png_ptr, 15);
png_set_compression_method(png_ptr, 8);
*/
/* set the image parameters appropriately */
if (mainprog_ptr->pnmtype == 5)
color_type = PNG_COLOR_TYPE_GRAY;
else if (mainprog_ptr->pnmtype == 6)
color_type = PNG_COLOR_TYPE_RGB;
else if (mainprog_ptr->pnmtype == 8)
color_type = PNG_COLOR_TYPE_RGB_ALPHA;
else {
png_destroy_write_struct(&png_ptr, &info_ptr);
return 11;
}
interlace_type = mainprog_ptr->interlaced? PNG_INTERLACE_ADAM7 :
PNG_INTERLACE_NONE;
png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height,
mainprog_ptr->sample_depth, color_type, interlace_type,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
if (mainprog_ptr->gamma > 0.0)
png_set_gAMA(png_ptr, info_ptr, mainprog_ptr->gamma);
if (mainprog_ptr->have_bg) { /* we know it's RGBA, not gray+alpha */
png_color_16 background;
background.red = mainprog_ptr->bg_red;
background.green = mainprog_ptr->bg_green;
background.blue = mainprog_ptr->bg_blue;
png_set_bKGD(png_ptr, info_ptr, &background);
}
if (mainprog_ptr->have_time) {
png_time modtime;
png_convert_from_time_t(&modtime, mainprog_ptr->modtime);
png_set_tIME(png_ptr, info_ptr, &modtime);
}
if (mainprog_ptr->have_text) {
png_text text[6];
int num_text = 0;
if (mainprog_ptr->have_text & TEXT_TITLE) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Title";
text[num_text].text = mainprog_ptr->title;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_AUTHOR) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Author";
text[num_text].text = mainprog_ptr->author;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_DESC) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Description";
text[num_text].text = mainprog_ptr->desc;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_COPY) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Copyright";
text[num_text].text = mainprog_ptr->copyright;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_EMAIL) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "E-mail";
text[num_text].text = mainprog_ptr->email;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_URL) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "URL";
text[num_text].text = mainprog_ptr->url;
++num_text;
}
png_set_text(png_ptr, info_ptr, text, num_text);
}
/* write all chunks up to (but not including) first IDAT */
png_write_info(png_ptr, info_ptr);
/* if we wanted to write any more text info *after* the image data, we
* would set up text struct(s) here and call png_set_text() again, with
* just the new data; png_set_tIME() could also go here, but it would
* have no effect since we already called it above (only one tIME chunk
* allowed) */
/* set up the transformations: for now, just pack low-bit-depth pixels
* into bytes (one, two or four pixels per byte) */
png_set_packing(png_ptr);
/* png_set_shift(png_ptr, &sig_bit); to scale low-bit-depth values */
/* make sure we save our pointers for use in writepng_encode_image() */
mainprog_ptr->png_ptr = png_ptr;
mainprog_ptr->info_ptr = info_ptr;
/* OK, that's all we need to do for now; return happy */
return 0;
}
| 173,576 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void skb_complete_tx_timestamp(struct sk_buff *skb,
struct skb_shared_hwtstamps *hwtstamps)
{
struct sock *sk = skb->sk;
if (!skb_may_tx_timestamp(sk, false))
return;
/* Take a reference to prevent skb_orphan() from freeing the socket,
* but only if the socket refcount is not zero.
*/
if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {
*skb_hwtstamps(skb) = *hwtstamps;
__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND);
sock_put(sk);
}
}
Commit Message: tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS
SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled
while packets are collected on the error queue.
So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags
is not enough to safely assume that the skb contains
OPT_STATS data.
Add a bit in sock_exterr_skb to indicate whether the
skb contains opt_stats data.
Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING")
Reported-by: JongHwan Kim <[email protected]>
Signed-off-by: Soheil Hassas Yeganeh <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: Willem de Bruijn <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-125
|
void skb_complete_tx_timestamp(struct sk_buff *skb,
struct skb_shared_hwtstamps *hwtstamps)
{
struct sock *sk = skb->sk;
if (!skb_may_tx_timestamp(sk, false))
return;
/* Take a reference to prevent skb_orphan() from freeing the socket,
* but only if the socket refcount is not zero.
*/
if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {
*skb_hwtstamps(skb) = *hwtstamps;
__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
sock_put(sk);
}
}
| 170,073 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static Image *ReadGIFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define BitSet(byte,bit) (((byte) & (bit)) == (bit))
#define LSBFirstOrder(x,y) (((y) << 8) | (x))
Image
*image,
*meta_image;
int
number_extensionss=0;
MagickBooleanType
status;
RectangleInfo
page;
register ssize_t
i;
register unsigned char
*p;
size_t
delay,
dispose,
duration,
global_colors,
image_count,
iterations,
one;
ssize_t
count,
opacity;
unsigned char
background,
c,
flag,
*global_colormap,
header[MaxTextExtent],
magick[12];
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Determine if this a GIF file.
*/
count=ReadBlob(image,6,magick);
if ((count != 6) || ((LocaleNCompare((char *) magick,"GIF87",5) != 0) &&
(LocaleNCompare((char *) magick,"GIF89",5) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
page.width=ReadBlobLSBShort(image);
page.height=ReadBlobLSBShort(image);
flag=(unsigned char) ReadBlobByte(image);
background=(unsigned char) ReadBlobByte(image);
c=(unsigned char) ReadBlobByte(image); /* reserved */
one=1;
global_colors=one << (((size_t) flag & 0x07)+1);
global_colormap=(unsigned char *) AcquireQuantumMemory((size_t)
MagickMax(global_colors,256),3UL*sizeof(*global_colormap));
if (global_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (BitSet((int) flag,0x80) != 0)
count=ReadBlob(image,(size_t) (3*global_colors),global_colormap);
delay=0;
dispose=0;
duration=0;
iterations=1;
opacity=(-1);
image_count=0;
meta_image=AcquireImage(image_info); /* metadata container */
for ( ; ; )
{
count=ReadBlob(image,1,&c);
if (count != 1)
break;
if (c == (unsigned char) ';')
break; /* terminator */
if (c == (unsigned char) '!')
{
/*
GIF Extension block.
*/
count=ReadBlob(image,1,&c);
if (count != 1)
{
global_colormap=(unsigned char *) RelinquishMagickMemory(
global_colormap);
ThrowReaderException(CorruptImageError,"UnableToReadExtensionBlock");
}
switch (c)
{
case 0xf9:
{
/*
Read graphics control extension.
*/
while (ReadBlobBlock(image,header) != 0) ;
dispose=(size_t) (header[0] >> 2);
delay=(size_t) ((header[2] << 8) | header[1]);
if ((ssize_t) (header[0] & 0x01) == 0x01)
opacity=(ssize_t) header[3];
break;
}
case 0xfe:
{
char
*comments;
size_t
length;
/*
Read comment extension.
*/
comments=AcquireString((char *) NULL);
for (length=0; ; length+=count)
{
count=(ssize_t) ReadBlobBlock(image,header);
if (count == 0)
break;
header[count]='\0';
(void) ConcatenateString(&comments,(const char *) header);
}
(void) SetImageProperty(meta_image,"comment",comments);
comments=DestroyString(comments);
break;
}
case 0xff:
{
MagickBooleanType
loop;
/*
Read Netscape Loop extension.
*/
loop=MagickFalse;
if (ReadBlobBlock(image,header) != 0)
loop=LocaleNCompare((char *) header,"NETSCAPE2.0",11) == 0 ?
MagickTrue : MagickFalse;
if (loop != MagickFalse)
{
while (ReadBlobBlock(image,header) != 0)
iterations=(size_t) ((header[2] << 8) | header[1]);
break;
}
else
{
char
name[MaxTextExtent];
int
block_length,
info_length,
reserved_length;
MagickBooleanType
i8bim,
icc,
iptc,
magick;
StringInfo
*profile;
unsigned char
*info;
/*
Store GIF application extension as a generic profile.
*/
icc=LocaleNCompare((char *) header,"ICCRGBG1012",11) == 0 ?
MagickTrue : MagickFalse;
magick=LocaleNCompare((char *) header,"ImageMagick",11) == 0 ?
MagickTrue : MagickFalse;
i8bim=LocaleNCompare((char *) header,"MGK8BIM0000",11) == 0 ?
MagickTrue : MagickFalse;
iptc=LocaleNCompare((char *) header,"MGKIPTC0000",11) == 0 ?
MagickTrue : MagickFalse;
number_extensionss++;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading GIF application extension");
info=(unsigned char *) AcquireQuantumMemory(255UL,sizeof(*info));
reserved_length=255;
for (info_length=0; ; )
{
block_length=(int) ReadBlobBlock(image,&info[info_length]);
if (block_length == 0)
break;
info_length+=block_length;
if (info_length > (reserved_length-255))
{
reserved_length+=4096;
info=(unsigned char *) ResizeQuantumMemory(info,(size_t)
reserved_length,sizeof(*info));
if (info == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
}
profile=BlobToStringInfo(info,(size_t) info_length);
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
if (i8bim != MagickFalse)
(void) CopyMagickString(name,"8bim",sizeof(name));
else if (icc != MagickFalse)
(void) CopyMagickString(name,"icc",sizeof(name));
else if (iptc != MagickFalse)
(void) CopyMagickString(name,"iptc",sizeof(name));
else if (magick != MagickFalse)
{
(void) CopyMagickString(name,"magick",sizeof(name));
image->gamma=StringToDouble((char *) info+6,(char **) NULL);
}
else
(void) FormatLocaleString(name,sizeof(name),"gif:%.11s",
header);
info=(unsigned char *) RelinquishMagickMemory(info);
if (magick == MagickFalse)
(void) SetImageProfile(meta_image,name,profile);
profile=DestroyStringInfo(profile);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" profile name=%s",name);
}
break;
}
default:
{
while (ReadBlobBlock(image,header) != 0) ;
break;
}
}
}
if (c != (unsigned char) ',')
continue;
if (image_count != 0)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
global_colormap=(unsigned char *) RelinquishMagickMemory(
global_colormap);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
}
image_count++;
/*
Read image attributes.
*/
meta_image->scene=image->scene;
CloneImageProperties(image,meta_image);
DestroyImageProperties(meta_image);
CloneImageProfiles(image,meta_image);
DestroyImageProfiles(meta_image);
image->storage_class=PseudoClass;
image->compression=LZWCompression;
page.x=(ssize_t) ReadBlobLSBShort(image);
page.y=(ssize_t) ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
image->depth=8;
flag=(unsigned char) ReadBlobByte(image);
image->interlace=BitSet((int) flag,0x40) != 0 ? GIFInterlace : NoInterlace;
image->colors=BitSet((int) flag,0x80) == 0 ? global_colors :
one << ((size_t) (flag & 0x07)+1);
if (opacity >= (ssize_t) image->colors)
opacity=(-1);
image->page.width=page.width;
image->page.height=page.height;
image->page.y=page.y;
image->page.x=page.x;
image->delay=delay;
image->iterations=iterations;
image->ticks_per_second=100;
image->dispose=(DisposeType) dispose;
image->matte=opacity >= 0 ? MagickTrue : MagickFalse;
delay=0;
dispose=0;
if ((image->columns == 0) || (image->rows == 0))
{
global_colormap=(unsigned char *) RelinquishMagickMemory(
global_colormap);
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
}
/*
Inititialize colormap.
*/
if (AcquireImageColormap(image,image->colors) == MagickFalse)
{
global_colormap=(unsigned char *) RelinquishMagickMemory(global_colormap);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (BitSet((int) flag,0x80) == 0)
{
/*
Use global colormap.
*/
p=global_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p++);
image->colormap[i].green=ScaleCharToQuantum(*p++);
image->colormap[i].blue=ScaleCharToQuantum(*p++);
if (i == opacity)
{
image->colormap[i].opacity=(Quantum) TransparentOpacity;
image->transparent_color=image->colormap[opacity];
}
}
image->background_color=image->colormap[MagickMin(background,
image->colors-1)];
}
else
{
unsigned char
*colormap;
/*
Read local colormap.
*/
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,3*
sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
{
global_colormap=(unsigned char *) RelinquishMagickMemory(
global_colormap);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
count=ReadBlob(image,(3*image->colors)*sizeof(*colormap),colormap);
if (count != (ssize_t) (3*image->colors))
{
global_colormap=(unsigned char *) RelinquishMagickMemory(
global_colormap);
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
p=colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p++);
image->colormap[i].green=ScaleCharToQuantum(*p++);
image->colormap[i].blue=ScaleCharToQuantum(*p++);
if (i == opacity)
image->colormap[i].opacity=(Quantum) TransparentOpacity;
}
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
}
if (image->gamma == 1.0)
{
for (i=0; i < (ssize_t) image->colors; i++)
if (IsGrayPixel(image->colormap+i) == MagickFalse)
break;
(void) SetImageColorspace(image,i == (ssize_t) image->colors ?
GRAYColorspace : RGBColorspace);
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
/*
Decode image.
*/
if (image_info->ping != MagickFalse)
status=PingGIFImage(image);
else
status=DecodeImage(image,opacity);
if ((image_info->ping == MagickFalse) && (status == MagickFalse))
{
global_colormap=(unsigned char *) RelinquishMagickMemory(
global_colormap);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
duration+=image->delay*image->iterations;
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
opacity=(-1);
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) image->scene-1,
image->scene);
if (status == MagickFalse)
break;
}
image->duration=duration;
meta_image=DestroyImage(meta_image);
global_colormap=(unsigned char *) RelinquishMagickMemory(global_colormap);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
|
static Image *ReadGIFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define BitSet(byte,bit) (((byte) & (bit)) == (bit))
#define LSBFirstOrder(x,y) (((y) << 8) | (x))
Image
*image,
*meta_image;
int
number_extensionss=0;
MagickBooleanType
status;
RectangleInfo
page;
register ssize_t
i;
register unsigned char
*p;
size_t
delay,
dispose,
duration,
global_colors,
image_count,
iterations,
one;
ssize_t
count,
opacity;
unsigned char
background,
c,
flag,
*global_colormap,
header[MaxTextExtent],
magick[12];
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Determine if this a GIF file.
*/
count=ReadBlob(image,6,magick);
if ((count != 6) || ((LocaleNCompare((char *) magick,"GIF87",5) != 0) &&
(LocaleNCompare((char *) magick,"GIF89",5) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
page.width=ReadBlobLSBShort(image);
page.height=ReadBlobLSBShort(image);
flag=(unsigned char) ReadBlobByte(image);
background=(unsigned char) ReadBlobByte(image);
c=(unsigned char) ReadBlobByte(image); /* reserved */
one=1;
global_colors=one << (((size_t) flag & 0x07)+1);
global_colormap=(unsigned char *) AcquireQuantumMemory((size_t)
MagickMax(global_colors,256),3UL*sizeof(*global_colormap));
if (global_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (BitSet((int) flag,0x80) != 0)
count=ReadBlob(image,(size_t) (3*global_colors),global_colormap);
delay=0;
dispose=0;
duration=0;
iterations=1;
opacity=(-1);
image_count=0;
meta_image=AcquireImage(image_info); /* metadata container */
for ( ; ; )
{
count=ReadBlob(image,1,&c);
if (count != 1)
break;
if (c == (unsigned char) ';')
break; /* terminator */
if (c == (unsigned char) '!')
{
/*
GIF Extension block.
*/
count=ReadBlob(image,1,&c);
if (count != 1)
{
global_colormap=(unsigned char *) RelinquishMagickMemory(
global_colormap);
ThrowReaderException(CorruptImageError,"UnableToReadExtensionBlock");
}
switch (c)
{
case 0xf9:
{
/*
Read graphics control extension.
*/
while (ReadBlobBlock(image,header) != 0) ;
dispose=(size_t) (header[0] >> 2);
delay=(size_t) ((header[2] << 8) | header[1]);
if ((ssize_t) (header[0] & 0x01) == 0x01)
opacity=(ssize_t) header[3];
break;
}
case 0xfe:
{
char
*comments;
size_t
length;
/*
Read comment extension.
*/
comments=AcquireString((char *) NULL);
for (length=0; ; length+=count)
{
count=(ssize_t) ReadBlobBlock(image,header);
if (count == 0)
break;
header[count]='\0';
(void) ConcatenateString(&comments,(const char *) header);
}
(void) SetImageProperty(meta_image,"comment",comments);
comments=DestroyString(comments);
break;
}
case 0xff:
{
MagickBooleanType
loop;
/*
Read Netscape Loop extension.
*/
loop=MagickFalse;
if (ReadBlobBlock(image,header) != 0)
loop=LocaleNCompare((char *) header,"NETSCAPE2.0",11) == 0 ?
MagickTrue : MagickFalse;
if (loop != MagickFalse)
{
while (ReadBlobBlock(image,header) != 0)
iterations=(size_t) ((header[2] << 8) | header[1]);
break;
}
else
{
char
name[MaxTextExtent];
int
block_length,
info_length,
reserved_length;
MagickBooleanType
i8bim,
icc,
iptc,
magick;
StringInfo
*profile;
unsigned char
*info;
/*
Store GIF application extension as a generic profile.
*/
icc=LocaleNCompare((char *) header,"ICCRGBG1012",11) == 0 ?
MagickTrue : MagickFalse;
magick=LocaleNCompare((char *) header,"ImageMagick",11) == 0 ?
MagickTrue : MagickFalse;
i8bim=LocaleNCompare((char *) header,"MGK8BIM0000",11) == 0 ?
MagickTrue : MagickFalse;
iptc=LocaleNCompare((char *) header,"MGKIPTC0000",11) == 0 ?
MagickTrue : MagickFalse;
number_extensionss++;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading GIF application extension");
info=(unsigned char *) AcquireQuantumMemory(255UL,sizeof(*info));
reserved_length=255;
for (info_length=0; ; )
{
block_length=(int) ReadBlobBlock(image,&info[info_length]);
if (block_length == 0)
break;
info_length+=block_length;
if (info_length > (reserved_length-255))
{
reserved_length+=4096;
info=(unsigned char *) ResizeQuantumMemory(info,(size_t)
reserved_length,sizeof(*info));
if (info == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
}
profile=BlobToStringInfo(info,(size_t) info_length);
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
if (i8bim != MagickFalse)
(void) CopyMagickString(name,"8bim",sizeof(name));
else if (icc != MagickFalse)
(void) CopyMagickString(name,"icc",sizeof(name));
else if (iptc != MagickFalse)
(void) CopyMagickString(name,"iptc",sizeof(name));
else if (magick != MagickFalse)
{
(void) CopyMagickString(name,"magick",sizeof(name));
image->gamma=StringToDouble((char *) info+6,(char **) NULL);
}
else
(void) FormatLocaleString(name,sizeof(name),"gif:%.11s",
header);
info=(unsigned char *) RelinquishMagickMemory(info);
if (magick == MagickFalse)
(void) SetImageProfile(meta_image,name,profile);
profile=DestroyStringInfo(profile);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" profile name=%s",name);
}
break;
}
default:
{
while (ReadBlobBlock(image,header) != 0) ;
break;
}
}
}
if (c != (unsigned char) ',')
continue;
if (image_count != 0)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
global_colormap=(unsigned char *) RelinquishMagickMemory(
global_colormap);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
}
image_count++;
/*
Read image attributes.
*/
meta_image->scene=image->scene;
CloneImageProperties(image,meta_image);
DestroyImageProperties(meta_image);
CloneImageProfiles(image,meta_image);
DestroyImageProfiles(meta_image);
image->storage_class=PseudoClass;
image->compression=LZWCompression;
page.x=(ssize_t) ReadBlobLSBShort(image);
page.y=(ssize_t) ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
image->depth=8;
flag=(unsigned char) ReadBlobByte(image);
image->interlace=BitSet((int) flag,0x40) != 0 ? GIFInterlace : NoInterlace;
image->colors=BitSet((int) flag,0x80) == 0 ? global_colors :
one << ((size_t) (flag & 0x07)+1);
if (opacity >= (ssize_t) image->colors)
opacity=(-1);
image->page.width=page.width;
image->page.height=page.height;
image->page.y=page.y;
image->page.x=page.x;
image->delay=delay;
image->iterations=iterations;
image->ticks_per_second=100;
image->dispose=(DisposeType) dispose;
image->matte=opacity >= 0 ? MagickTrue : MagickFalse;
delay=0;
dispose=0;
if ((image->columns == 0) || (image->rows == 0))
{
global_colormap=(unsigned char *) RelinquishMagickMemory(
global_colormap);
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
}
/*
Inititialize colormap.
*/
if (AcquireImageColormap(image,image->colors) == MagickFalse)
{
global_colormap=(unsigned char *) RelinquishMagickMemory(global_colormap);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (BitSet((int) flag,0x80) == 0)
{
/*
Use global colormap.
*/
p=global_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p++);
image->colormap[i].green=ScaleCharToQuantum(*p++);
image->colormap[i].blue=ScaleCharToQuantum(*p++);
if (i == opacity)
{
image->colormap[i].opacity=(Quantum) TransparentOpacity;
image->transparent_color=image->colormap[opacity];
}
}
image->background_color=image->colormap[MagickMin(background,
image->colors-1)];
}
else
{
unsigned char
*colormap;
/*
Read local colormap.
*/
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,3*
sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
{
global_colormap=(unsigned char *) RelinquishMagickMemory(
global_colormap);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
count=ReadBlob(image,(3*image->colors)*sizeof(*colormap),colormap);
if (count != (ssize_t) (3*image->colors))
{
global_colormap=(unsigned char *) RelinquishMagickMemory(
global_colormap);
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
p=colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p++);
image->colormap[i].green=ScaleCharToQuantum(*p++);
image->colormap[i].blue=ScaleCharToQuantum(*p++);
if (i == opacity)
image->colormap[i].opacity=(Quantum) TransparentOpacity;
}
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
}
if (image->gamma == 1.0)
{
for (i=0; i < (ssize_t) image->colors; i++)
if (IsGrayPixel(image->colormap+i) == MagickFalse)
break;
(void) SetImageColorspace(image,i == (ssize_t) image->colors ?
GRAYColorspace : RGBColorspace);
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Decode image.
*/
if (image_info->ping != MagickFalse)
status=PingGIFImage(image);
else
status=DecodeImage(image,opacity);
if ((image_info->ping == MagickFalse) && (status == MagickFalse))
{
global_colormap=(unsigned char *) RelinquishMagickMemory(
global_colormap);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
duration+=image->delay*image->iterations;
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
opacity=(-1);
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) image->scene-1,
image->scene);
if (status == MagickFalse)
break;
}
image->duration=duration;
meta_image=DestroyImage(meta_image);
global_colormap=(unsigned char *) RelinquishMagickMemory(global_colormap);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,567 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int http_RecvPostMessage(
/*! HTTP Parser object. */
http_parser_t *parser,
/*! [in] Socket Information object. */
SOCKINFO *info,
/*! File where received data is copied to. */
char *filename,
/*! Send Instruction object which gives information whether the file
* is a virtual file or not. */
struct SendInstruction *Instr)
{
size_t Data_Buf_Size = 1024;
char Buf[1024];
int Timeout = -1;
FILE *Fp;
parse_status_t status = PARSE_OK;
int ok_on_close = FALSE;
size_t entity_offset = 0;
int num_read = 0;
int ret_code = HTTP_OK;
if (Instr && Instr->IsVirtualFile) {
Fp = (virtualDirCallback.open) (filename, UPNP_WRITE);
if (Fp == NULL)
return HTTP_INTERNAL_SERVER_ERROR;
} else {
Fp = fopen(filename, "wb");
if (Fp == NULL)
return HTTP_UNAUTHORIZED;
}
parser->position = POS_ENTITY;
do {
/* first parse what has already been gotten */
if (parser->position != POS_COMPLETE)
status = parser_parse_entity(parser);
if (status == PARSE_INCOMPLETE_ENTITY) {
/* read until close */
ok_on_close = TRUE;
} else if ((status != PARSE_SUCCESS)
&& (status != PARSE_CONTINUE_1)
&& (status != PARSE_INCOMPLETE)) {
/* error */
ret_code = HTTP_BAD_REQUEST;
goto ExitFunction;
}
/* read more if necessary entity */
while (entity_offset + Data_Buf_Size > parser->msg.entity.length &&
parser->position != POS_COMPLETE) {
num_read = sock_read(info, Buf, sizeof(Buf), &Timeout);
if (num_read > 0) {
/* append data to buffer */
if (membuffer_append(&parser->msg.msg,
Buf, (size_t)num_read) != 0) {
/* set failure status */
parser->http_error_code =
HTTP_INTERNAL_SERVER_ERROR;
ret_code = HTTP_INTERNAL_SERVER_ERROR;
goto ExitFunction;
}
status = parser_parse_entity(parser);
if (status == PARSE_INCOMPLETE_ENTITY) {
/* read until close */
ok_on_close = TRUE;
} else if ((status != PARSE_SUCCESS)
&& (status != PARSE_CONTINUE_1)
&& (status != PARSE_INCOMPLETE)) {
ret_code = HTTP_BAD_REQUEST;
goto ExitFunction;
}
} else if (num_read == 0) {
if (ok_on_close) {
UpnpPrintf(UPNP_INFO, HTTP, __FILE__, __LINE__,
"<<< (RECVD) <<<\n%s\n-----------------\n",
parser->msg.msg.buf);
print_http_headers(&parser->msg);
parser->position = POS_COMPLETE;
} else {
/* partial msg or response */
parser->http_error_code = HTTP_BAD_REQUEST;
ret_code = HTTP_BAD_REQUEST;
goto ExitFunction;
}
} else {
ret_code = HTTP_SERVICE_UNAVAILABLE;
goto ExitFunction;
}
}
if ((entity_offset + Data_Buf_Size) > parser->msg.entity.length) {
Data_Buf_Size =
parser->msg.entity.length - entity_offset;
}
memcpy(Buf,
&parser->msg.msg.buf[parser->entity_start_position + entity_offset],
Data_Buf_Size);
entity_offset += Data_Buf_Size;
if (Instr && Instr->IsVirtualFile) {
int n = virtualDirCallback.write(Fp, Buf, Data_Buf_Size);
if (n < 0) {
ret_code = HTTP_INTERNAL_SERVER_ERROR;
goto ExitFunction;
}
} else {
size_t n = fwrite(Buf, 1, Data_Buf_Size, Fp);
if (n != Data_Buf_Size) {
ret_code = HTTP_INTERNAL_SERVER_ERROR;
goto ExitFunction;
}
}
} while (parser->position != POS_COMPLETE ||
entity_offset != parser->msg.entity.length);
ExitFunction:
if (Instr && Instr->IsVirtualFile) {
virtualDirCallback.close(Fp);
} else {
fclose(Fp);
}
return ret_code;
}
Commit Message: Don't allow unhandled POSTs to write to the filesystem by default
If there's no registered handler for a POST request, the default behaviour
is to write it to the filesystem. Several million deployed devices appear
to have this behaviour, making it possible to (at least) store arbitrary
data on them. Add a configure option that enables this behaviour, and change
the default to just drop POSTs that aren't directly handled.
CWE ID: CWE-284
|
static int http_RecvPostMessage(
/*! HTTP Parser object. */
http_parser_t *parser,
/*! [in] Socket Information object. */
SOCKINFO *info,
/*! File where received data is copied to. */
char *filename,
/*! Send Instruction object which gives information whether the file
* is a virtual file or not. */
struct SendInstruction *Instr)
{
size_t Data_Buf_Size = 1024;
char Buf[1024];
int Timeout = -1;
FILE *Fp;
parse_status_t status = PARSE_OK;
int ok_on_close = FALSE;
size_t entity_offset = 0;
int num_read = 0;
int ret_code = HTTP_OK;
if (Instr && Instr->IsVirtualFile) {
Fp = (virtualDirCallback.open) (filename, UPNP_WRITE);
if (Fp == NULL)
return HTTP_INTERNAL_SERVER_ERROR;
} else {
#ifdef UPNP_ENABLE_POST_WRITE
Fp = fopen(filename, "wb");
if (Fp == NULL)
return HTTP_UNAUTHORIZED;
#else
return HTTP_NOT_FOUND;
#endif
}
parser->position = POS_ENTITY;
do {
/* first parse what has already been gotten */
if (parser->position != POS_COMPLETE)
status = parser_parse_entity(parser);
if (status == PARSE_INCOMPLETE_ENTITY) {
/* read until close */
ok_on_close = TRUE;
} else if ((status != PARSE_SUCCESS)
&& (status != PARSE_CONTINUE_1)
&& (status != PARSE_INCOMPLETE)) {
/* error */
ret_code = HTTP_BAD_REQUEST;
goto ExitFunction;
}
/* read more if necessary entity */
while (entity_offset + Data_Buf_Size > parser->msg.entity.length &&
parser->position != POS_COMPLETE) {
num_read = sock_read(info, Buf, sizeof(Buf), &Timeout);
if (num_read > 0) {
/* append data to buffer */
if (membuffer_append(&parser->msg.msg,
Buf, (size_t)num_read) != 0) {
/* set failure status */
parser->http_error_code =
HTTP_INTERNAL_SERVER_ERROR;
ret_code = HTTP_INTERNAL_SERVER_ERROR;
goto ExitFunction;
}
status = parser_parse_entity(parser);
if (status == PARSE_INCOMPLETE_ENTITY) {
/* read until close */
ok_on_close = TRUE;
} else if ((status != PARSE_SUCCESS)
&& (status != PARSE_CONTINUE_1)
&& (status != PARSE_INCOMPLETE)) {
ret_code = HTTP_BAD_REQUEST;
goto ExitFunction;
}
} else if (num_read == 0) {
if (ok_on_close) {
UpnpPrintf(UPNP_INFO, HTTP, __FILE__, __LINE__,
"<<< (RECVD) <<<\n%s\n-----------------\n",
parser->msg.msg.buf);
print_http_headers(&parser->msg);
parser->position = POS_COMPLETE;
} else {
/* partial msg or response */
parser->http_error_code = HTTP_BAD_REQUEST;
ret_code = HTTP_BAD_REQUEST;
goto ExitFunction;
}
} else {
ret_code = HTTP_SERVICE_UNAVAILABLE;
goto ExitFunction;
}
}
if ((entity_offset + Data_Buf_Size) > parser->msg.entity.length) {
Data_Buf_Size =
parser->msg.entity.length - entity_offset;
}
memcpy(Buf,
&parser->msg.msg.buf[parser->entity_start_position + entity_offset],
Data_Buf_Size);
entity_offset += Data_Buf_Size;
if (Instr && Instr->IsVirtualFile) {
int n = virtualDirCallback.write(Fp, Buf, Data_Buf_Size);
if (n < 0) {
ret_code = HTTP_INTERNAL_SERVER_ERROR;
goto ExitFunction;
}
} else {
size_t n = fwrite(Buf, 1, Data_Buf_Size, Fp);
if (n != Data_Buf_Size) {
ret_code = HTTP_INTERNAL_SERVER_ERROR;
goto ExitFunction;
}
}
} while (parser->position != POS_COMPLETE ||
entity_offset != parser->msg.entity.length);
ExitFunction:
if (Instr && Instr->IsVirtualFile) {
virtualDirCallback.close(Fp);
} else {
fclose(Fp);
}
return ret_code;
}
| 168,831 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: SYSCALL_DEFINE1(inotify_init1, int, flags)
{
struct fsnotify_group *group;
struct user_struct *user;
int ret;
/* Check the IN_* constants for consistency. */
BUILD_BUG_ON(IN_CLOEXEC != O_CLOEXEC);
BUILD_BUG_ON(IN_NONBLOCK != O_NONBLOCK);
if (flags & ~(IN_CLOEXEC | IN_NONBLOCK))
return -EINVAL;
user = get_current_user();
if (unlikely(atomic_read(&user->inotify_devs) >=
inotify_max_user_instances)) {
ret = -EMFILE;
goto out_free_uid;
}
/* fsnotify_obtain_group took a reference to group, we put this when we kill the file in the end */
group = inotify_new_group(user, inotify_max_queued_events);
if (IS_ERR(group)) {
ret = PTR_ERR(group);
goto out_free_uid;
}
atomic_inc(&user->inotify_devs);
ret = anon_inode_getfd("inotify", &inotify_fops, group,
O_RDONLY | flags);
if (ret >= 0)
return ret;
atomic_dec(&user->inotify_devs);
out_free_uid:
free_uid(user);
return ret;
}
Commit Message: inotify: stop kernel memory leak on file creation failure
If inotify_init is unable to allocate a new file for the new inotify
group we leak the new group. This patch drops the reference on the
group on file allocation failure.
Reported-by: Vegard Nossum <[email protected]>
cc: [email protected]
Signed-off-by: Eric Paris <[email protected]>
CWE ID: CWE-399
|
SYSCALL_DEFINE1(inotify_init1, int, flags)
{
struct fsnotify_group *group;
struct user_struct *user;
int ret;
/* Check the IN_* constants for consistency. */
BUILD_BUG_ON(IN_CLOEXEC != O_CLOEXEC);
BUILD_BUG_ON(IN_NONBLOCK != O_NONBLOCK);
if (flags & ~(IN_CLOEXEC | IN_NONBLOCK))
return -EINVAL;
user = get_current_user();
if (unlikely(atomic_read(&user->inotify_devs) >=
inotify_max_user_instances)) {
ret = -EMFILE;
goto out_free_uid;
}
/* fsnotify_obtain_group took a reference to group, we put this when we kill the file in the end */
group = inotify_new_group(user, inotify_max_queued_events);
if (IS_ERR(group)) {
ret = PTR_ERR(group);
goto out_free_uid;
}
atomic_inc(&user->inotify_devs);
ret = anon_inode_getfd("inotify", &inotify_fops, group,
O_RDONLY | flags);
if (ret >= 0)
return ret;
fsnotify_put_group(group);
atomic_dec(&user->inotify_devs);
out_free_uid:
free_uid(user);
return ret;
}
| 165,908 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: auth_select_file(struct sc_card *card, const struct sc_path *in_path,
struct sc_file **file_out)
{
struct sc_path path;
struct sc_file *tmp_file = NULL;
size_t offs, ii;
int rv;
LOG_FUNC_CALLED(card->ctx);
assert(card != NULL && in_path != NULL);
memcpy(&path, in_path, sizeof(struct sc_path));
sc_log(card->ctx, "in_path; type=%d, path=%s, out %p",
in_path->type, sc_print_path(in_path), file_out);
sc_log(card->ctx, "current path; type=%d, path=%s",
auth_current_df->path.type, sc_print_path(&auth_current_df->path));
if (auth_current_ef)
sc_log(card->ctx, "current file; type=%d, path=%s",
auth_current_ef->path.type, sc_print_path(&auth_current_ef->path));
if (path.type == SC_PATH_TYPE_PARENT || path.type == SC_PATH_TYPE_FILE_ID) {
sc_file_free(auth_current_ef);
auth_current_ef = NULL;
rv = iso_ops->select_file(card, &path, &tmp_file);
LOG_TEST_RET(card->ctx, rv, "select file failed");
if (!tmp_file)
return SC_ERROR_OBJECT_NOT_FOUND;
if (path.type == SC_PATH_TYPE_PARENT) {
memcpy(&tmp_file->path, &auth_current_df->path, sizeof(struct sc_path));
if (tmp_file->path.len > 2)
tmp_file->path.len -= 2;
sc_file_free(auth_current_df);
sc_file_dup(&auth_current_df, tmp_file);
}
else {
if (tmp_file->type == SC_FILE_TYPE_DF) {
sc_concatenate_path(&tmp_file->path, &auth_current_df->path, &path);
sc_file_free(auth_current_df);
sc_file_dup(&auth_current_df, tmp_file);
}
else {
sc_file_free(auth_current_ef);
sc_file_dup(&auth_current_ef, tmp_file);
sc_concatenate_path(&auth_current_ef->path, &auth_current_df->path, &path);
}
}
if (file_out)
sc_file_dup(file_out, tmp_file);
sc_file_free(tmp_file);
}
else if (path.type == SC_PATH_TYPE_DF_NAME) {
rv = iso_ops->select_file(card, &path, NULL);
if (rv) {
sc_file_free(auth_current_ef);
auth_current_ef = NULL;
}
LOG_TEST_RET(card->ctx, rv, "select file failed");
}
else {
for (offs = 0; offs < path.len && offs < auth_current_df->path.len; offs += 2)
if (path.value[offs] != auth_current_df->path.value[offs] ||
path.value[offs + 1] != auth_current_df->path.value[offs + 1])
break;
sc_log(card->ctx, "offs %"SC_FORMAT_LEN_SIZE_T"u", offs);
if (offs && offs < auth_current_df->path.len) {
size_t deep = auth_current_df->path.len - offs;
sc_log(card->ctx, "deep %"SC_FORMAT_LEN_SIZE_T"u",
deep);
for (ii=0; ii<deep; ii+=2) {
struct sc_path tmp_path;
memcpy(&tmp_path, &auth_current_df->path, sizeof(struct sc_path));
tmp_path.type = SC_PATH_TYPE_PARENT;
rv = auth_select_file (card, &tmp_path, file_out);
LOG_TEST_RET(card->ctx, rv, "select file failed");
}
}
if (path.len - offs > 0) {
struct sc_path tmp_path;
memset(&tmp_path, 0, sizeof(struct sc_path));
tmp_path.type = SC_PATH_TYPE_FILE_ID;
tmp_path.len = 2;
for (ii=0; ii < path.len - offs; ii+=2) {
memcpy(tmp_path.value, path.value + offs + ii, 2);
rv = auth_select_file(card, &tmp_path, file_out);
LOG_TEST_RET(card->ctx, rv, "select file failed");
}
}
else if (path.len - offs == 0 && file_out) {
if (sc_compare_path(&path, &auth_current_df->path))
sc_file_dup(file_out, auth_current_df);
else if (auth_current_ef)
sc_file_dup(file_out, auth_current_ef);
else
LOG_TEST_RET(card->ctx, SC_ERROR_INTERNAL, "No current EF");
}
}
LOG_FUNC_RETURN(card->ctx, 0);
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
|
auth_select_file(struct sc_card *card, const struct sc_path *in_path,
struct sc_file **file_out)
{
struct sc_path path;
struct sc_file *tmp_file = NULL;
size_t offs, ii;
int rv;
LOG_FUNC_CALLED(card->ctx);
assert(card != NULL && in_path != NULL);
memcpy(&path, in_path, sizeof(struct sc_path));
if (!auth_current_df)
return SC_ERROR_OBJECT_NOT_FOUND;
sc_log(card->ctx, "in_path; type=%d, path=%s, out %p",
in_path->type, sc_print_path(in_path), file_out);
sc_log(card->ctx, "current path; type=%d, path=%s",
auth_current_df->path.type, sc_print_path(&auth_current_df->path));
if (auth_current_ef)
sc_log(card->ctx, "current file; type=%d, path=%s",
auth_current_ef->path.type, sc_print_path(&auth_current_ef->path));
if (path.type == SC_PATH_TYPE_PARENT || path.type == SC_PATH_TYPE_FILE_ID) {
sc_file_free(auth_current_ef);
auth_current_ef = NULL;
rv = iso_ops->select_file(card, &path, &tmp_file);
LOG_TEST_RET(card->ctx, rv, "select file failed");
if (!tmp_file)
return SC_ERROR_OBJECT_NOT_FOUND;
if (path.type == SC_PATH_TYPE_PARENT) {
memcpy(&tmp_file->path, &auth_current_df->path, sizeof(struct sc_path));
if (tmp_file->path.len > 2)
tmp_file->path.len -= 2;
sc_file_free(auth_current_df);
sc_file_dup(&auth_current_df, tmp_file);
}
else {
if (tmp_file->type == SC_FILE_TYPE_DF) {
sc_concatenate_path(&tmp_file->path, &auth_current_df->path, &path);
sc_file_free(auth_current_df);
sc_file_dup(&auth_current_df, tmp_file);
}
else {
sc_file_free(auth_current_ef);
sc_file_dup(&auth_current_ef, tmp_file);
sc_concatenate_path(&auth_current_ef->path, &auth_current_df->path, &path);
}
}
if (file_out)
sc_file_dup(file_out, tmp_file);
sc_file_free(tmp_file);
}
else if (path.type == SC_PATH_TYPE_DF_NAME) {
rv = iso_ops->select_file(card, &path, NULL);
if (rv) {
sc_file_free(auth_current_ef);
auth_current_ef = NULL;
}
LOG_TEST_RET(card->ctx, rv, "select file failed");
}
else {
for (offs = 0; offs < path.len && offs < auth_current_df->path.len; offs += 2)
if (path.value[offs] != auth_current_df->path.value[offs] ||
path.value[offs + 1] != auth_current_df->path.value[offs + 1])
break;
sc_log(card->ctx, "offs %"SC_FORMAT_LEN_SIZE_T"u", offs);
if (offs && offs < auth_current_df->path.len) {
size_t deep = auth_current_df->path.len - offs;
sc_log(card->ctx, "deep %"SC_FORMAT_LEN_SIZE_T"u",
deep);
for (ii=0; ii<deep; ii+=2) {
struct sc_path tmp_path;
memcpy(&tmp_path, &auth_current_df->path, sizeof(struct sc_path));
tmp_path.type = SC_PATH_TYPE_PARENT;
rv = auth_select_file (card, &tmp_path, file_out);
LOG_TEST_RET(card->ctx, rv, "select file failed");
}
}
if (path.len - offs > 0) {
struct sc_path tmp_path;
memset(&tmp_path, 0, sizeof(struct sc_path));
tmp_path.type = SC_PATH_TYPE_FILE_ID;
tmp_path.len = 2;
for (ii=0; ii < path.len - offs; ii+=2) {
memcpy(tmp_path.value, path.value + offs + ii, 2);
rv = auth_select_file(card, &tmp_path, file_out);
LOG_TEST_RET(card->ctx, rv, "select file failed");
}
}
else if (path.len - offs == 0 && file_out) {
if (sc_compare_path(&path, &auth_current_df->path))
sc_file_dup(file_out, auth_current_df);
else if (auth_current_ef)
sc_file_dup(file_out, auth_current_ef);
else
LOG_TEST_RET(card->ctx, SC_ERROR_INTERNAL, "No current EF");
}
}
LOG_FUNC_RETURN(card->ctx, 0);
}
| 169,059 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void GLES2DecoderImpl::ClearUnclearedAttachments(
GLenum target, Framebuffer* framebuffer) {
if (target == GL_READ_FRAMEBUFFER_EXT) {
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0);
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, framebuffer->service_id());
}
GLbitfield clear_bits = 0;
if (framebuffer->HasUnclearedAttachment(GL_COLOR_ATTACHMENT0)) {
glClearColor(
0.0f, 0.0f, 0.0f,
(GLES2Util::GetChannelsForFormat(
framebuffer->GetColorAttachmentFormat()) & 0x0008) != 0 ? 0.0f :
1.0f);
state_.SetDeviceColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
clear_bits |= GL_COLOR_BUFFER_BIT;
}
if (framebuffer->HasUnclearedAttachment(GL_STENCIL_ATTACHMENT) ||
framebuffer->HasUnclearedAttachment(GL_DEPTH_STENCIL_ATTACHMENT)) {
glClearStencil(0);
state_.SetDeviceStencilMaskSeparate(GL_FRONT, -1);
state_.SetDeviceStencilMaskSeparate(GL_BACK, -1);
clear_bits |= GL_STENCIL_BUFFER_BIT;
}
if (framebuffer->HasUnclearedAttachment(GL_DEPTH_ATTACHMENT) ||
framebuffer->HasUnclearedAttachment(GL_DEPTH_STENCIL_ATTACHMENT)) {
glClearDepth(1.0f);
state_.SetDeviceDepthMask(GL_TRUE);
clear_bits |= GL_DEPTH_BUFFER_BIT;
}
state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false);
glClear(clear_bits);
framebuffer_manager()->MarkAttachmentsAsCleared(
framebuffer, renderbuffer_manager(), texture_manager());
RestoreClearState();
if (target == GL_READ_FRAMEBUFFER_EXT) {
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, framebuffer->service_id());
Framebuffer* draw_framebuffer =
GetFramebufferInfoForTarget(GL_DRAW_FRAMEBUFFER_EXT);
GLuint service_id = draw_framebuffer ? draw_framebuffer->service_id() :
GetBackbufferServiceId();
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, service_id);
}
}
Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled.
This is when we expose DrawBuffers extension.
BUG=376951
TEST=the attached test case, webgl conformance
[email protected],[email protected]
Review URL: https://codereview.chromium.org/315283002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void GLES2DecoderImpl::ClearUnclearedAttachments(
GLenum target, Framebuffer* framebuffer) {
if (target == GL_READ_FRAMEBUFFER_EXT) {
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0);
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, framebuffer->service_id());
}
GLbitfield clear_bits = 0;
if (framebuffer->HasUnclearedColorAttachments()) {
glClearColor(
0.0f, 0.0f, 0.0f,
(GLES2Util::GetChannelsForFormat(
framebuffer->GetColorAttachmentFormat()) & 0x0008) != 0 ? 0.0f :
1.0f);
state_.SetDeviceColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
clear_bits |= GL_COLOR_BUFFER_BIT;
framebuffer->PrepareDrawBuffersForClear();
}
if (framebuffer->HasUnclearedAttachment(GL_STENCIL_ATTACHMENT) ||
framebuffer->HasUnclearedAttachment(GL_DEPTH_STENCIL_ATTACHMENT)) {
glClearStencil(0);
state_.SetDeviceStencilMaskSeparate(GL_FRONT, -1);
state_.SetDeviceStencilMaskSeparate(GL_BACK, -1);
clear_bits |= GL_STENCIL_BUFFER_BIT;
}
if (framebuffer->HasUnclearedAttachment(GL_DEPTH_ATTACHMENT) ||
framebuffer->HasUnclearedAttachment(GL_DEPTH_STENCIL_ATTACHMENT)) {
glClearDepth(1.0f);
state_.SetDeviceDepthMask(GL_TRUE);
clear_bits |= GL_DEPTH_BUFFER_BIT;
}
state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false);
glClear(clear_bits);
if ((clear_bits | GL_COLOR_BUFFER_BIT) != 0)
framebuffer->RestoreDrawBuffersAfterClear();
framebuffer_manager()->MarkAttachmentsAsCleared(
framebuffer, renderbuffer_manager(), texture_manager());
RestoreClearState();
if (target == GL_READ_FRAMEBUFFER_EXT) {
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, framebuffer->service_id());
Framebuffer* draw_framebuffer =
GetFramebufferInfoForTarget(GL_DRAW_FRAMEBUFFER_EXT);
GLuint service_id = draw_framebuffer ? draw_framebuffer->service_id() :
GetBackbufferServiceId();
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, service_id);
}
}
| 171,658 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool ExtensionTtsPlatformImplChromeOs::Speak(
const std::string& utterance,
const std::string& locale,
const std::string& gender,
double rate,
double pitch,
double volume) {
chromeos::CrosLibrary* cros_library = chromeos::CrosLibrary::Get();
if (!cros_library->EnsureLoaded()) {
set_error(kCrosLibraryNotLoadedError);
return false;
}
std::string options;
if (!locale.empty()) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyLocale,
locale,
&options);
}
if (!gender.empty()) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyGender,
gender,
&options);
}
if (rate >= 0.0) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyRate,
DoubleToString(rate * 5),
&options);
}
if (pitch >= 0.0) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyPitch,
DoubleToString(pitch * 2),
&options);
}
if (volume >= 0.0) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyVolume,
DoubleToString(volume * 5),
&options);
}
if (!options.empty()) {
cros_library->GetSpeechSynthesisLibrary()->SetSpeakProperties(
options.c_str());
}
return cros_library->GetSpeechSynthesisLibrary()->Speak(utterance.c_str());
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
bool ExtensionTtsPlatformImplChromeOs::Speak(
int utterance_id,
const std::string& utterance,
const std::string& lang,
const UtteranceContinuousParameters& params) {
chromeos::CrosLibrary* cros_library = chromeos::CrosLibrary::Get();
if (!cros_library->EnsureLoaded()) {
set_error(kCrosLibraryNotLoadedError);
return false;
}
utterance_id_ = utterance_id;
utterance_length_ = utterance.size();
std::string options;
if (!lang.empty()) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyLocale,
lang,
&options);
}
if (params.rate >= 0.0) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyRate,
DoubleToString(1.5 + params.rate * 2.5),
&options);
}
if (params.pitch >= 0.0) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyPitch,
DoubleToString(params.pitch),
&options);
}
if (params.volume >= 0.0) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyVolume,
DoubleToString(params.volume * 5),
&options);
}
if (!options.empty()) {
cros_library->GetSpeechSynthesisLibrary()->SetSpeakProperties(
options.c_str());
}
bool result =
cros_library->GetSpeechSynthesisLibrary()->Speak(utterance.c_str());
if (result) {
ExtensionTtsController* controller = ExtensionTtsController::GetInstance();
controller->OnTtsEvent(utterance_id_, TTS_EVENT_START, 0, std::string());
PollUntilSpeechFinishes(utterance_id_);
}
return result;
}
| 170,399 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
Image *image)
{
#if !defined(TIFFDefaultStripSize)
#define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff))
#endif
const char
*mode,
*option;
CompressionType
compression;
EndianType
endian_type;
MagickBooleanType
debug,
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
ssize_t
y;
TIFF
*tiff;
TIFFInfo
tiff_info;
uint16
bits_per_sample,
compress_tag,
endian,
photometric;
uint32
rows_per_strip;
unsigned char
*pixels;
/*
Open TIFF file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) SetMagickThreadValue(tiff_exception,&image->exception);
endian_type=UndefinedEndian;
option=GetImageOption(image_info,"tiff:endian");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian_type=MSBEndian;
if (LocaleNCompare(option,"lsb",3) == 0)
endian_type=LSBEndian;;
}
switch (endian_type)
{
case LSBEndian: mode="wl"; break;
case MSBEndian: mode="wb"; break;
default: mode="w"; break;
}
#if defined(TIFF_VERSION_BIG)
if (LocaleCompare(image_info->magick,"TIFF64") == 0)
switch (endian_type)
{
case LSBEndian: mode="wl8"; break;
case MSBEndian: mode="wb8"; break;
default: mode="w8"; break;
}
#endif
tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
return(MagickFalse);
scene=0;
debug=IsEventLogging();
(void) debug;
do
{
/*
Initialize TIFF fields.
*/
if ((image_info->type != UndefinedType) &&
(image_info->type != OptimizeType))
(void) SetImageType(image,image_info->type);
compression=UndefinedCompression;
if (image->compression != JPEGCompression)
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
(void) SetImageType(image,BilevelType);
(void) SetImageDepth(image,1);
break;
}
case JPEGCompression:
{
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
break;
}
default:
break;
}
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
(quantum_info->format == UndefinedQuantumFormat) &&
(IsHighDynamicRangeImage(image,&image->exception) != MagickFalse))
{
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
(GetPreviousImageInList(image) != (Image *) NULL))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
if ((image->columns != (uint32) image->columns) ||
(image->rows != (uint32) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
(void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
(void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
switch (compression)
{
case FaxCompression:
{
compress_tag=COMPRESSION_CCITTFAX3;
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
case Group4Compression:
{
compress_tag=COMPRESSION_CCITTFAX4;
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
#if defined(COMPRESSION_JBIG)
case JBIG1Compression:
{
compress_tag=COMPRESSION_JBIG;
break;
}
#endif
case JPEGCompression:
{
compress_tag=COMPRESSION_JPEG;
break;
}
#if defined(COMPRESSION_LZMA)
case LZMACompression:
{
compress_tag=COMPRESSION_LZMA;
break;
}
#endif
case LZWCompression:
{
compress_tag=COMPRESSION_LZW;
break;
}
case RLECompression:
{
compress_tag=COMPRESSION_PACKBITS;
break;
}
case ZipCompression:
{
compress_tag=COMPRESSION_ADOBE_DEFLATE;
break;
}
case NoCompression:
default:
{
compress_tag=COMPRESSION_NONE;
break;
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
}
#else
switch (compress_tag)
{
#if defined(CCITT_SUPPORT)
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
#endif
#if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
case COMPRESSION_JPEG:
#endif
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
#endif
#if defined(LZW_SUPPORT)
case COMPRESSION_LZW:
#endif
#if defined(PACKBITS_SUPPORT)
case COMPRESSION_PACKBITS:
#endif
#if defined(ZIP_SUPPORT)
case COMPRESSION_ADOBE_DEFLATE:
#endif
case COMPRESSION_NONE:
break;
default:
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
break;
}
}
#endif
if (image->colorspace == CMYKColorspace)
{
photometric=PHOTOMETRIC_SEPARATED;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
(void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
}
else
{
/*
Full color TIFF raster.
*/
if (image->colorspace == LabColorspace)
{
photometric=PHOTOMETRIC_CIELAB;
EncodeLabImage(image,&image->exception);
}
else
if (image->colorspace == YCbCrColorspace)
{
photometric=PHOTOMETRIC_YCBCR;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
}
else
photometric=PHOTOMETRIC_RGB;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
if ((image_info->type != TrueColorType) &&
(image_info->type != TrueColorMatteType))
{
if ((image_info->type != PaletteType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
photometric=(uint16) (quantum_info->min_is_white !=
MagickFalse ? PHOTOMETRIC_MINISWHITE :
PHOTOMETRIC_MINISBLACK);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
if ((image->depth == 1) && (image->matte == MagickFalse))
SetImageMonochrome(image,&image->exception);
}
else
if (image->storage_class == PseudoClass)
{
size_t
depth;
/*
Colormapped TIFF raster.
*/
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
photometric=PHOTOMETRIC_PALETTE;
depth=1;
while ((GetQuantumRange(depth)+1) < image->colors)
depth<<=1;
status=SetQuantumDepth(image,quantum_info,depth);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
if ((compress_tag == COMPRESSION_CCITTFAX3) &&
(photometric != PHOTOMETRIC_MINISWHITE))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
else
if ((compress_tag == COMPRESSION_CCITTFAX4) &&
(photometric != PHOTOMETRIC_MINISWHITE))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
option=GetImageOption(image_info,"tiff:fill-order");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian=FILLORDER_MSB2LSB;
if (LocaleNCompare(option,"lsb",3) == 0)
endian=FILLORDER_LSB2MSB;
}
(void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
(void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
(void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
if (image->matte != MagickFalse)
{
uint16
extra_samples,
sample_info[1],
samples_per_pixel;
/*
TIFF has a matte channel.
*/
extra_samples=1;
sample_info[0]=EXTRASAMPLE_UNASSALPHA;
option=GetImageOption(image_info,"tiff:alpha");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"associated") == 0)
sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
else
if (LocaleCompare(option,"unspecified") == 0)
sample_info[0]=EXTRASAMPLE_UNSPECIFIED;
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
&samples_per_pixel);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
(void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
&sample_info);
if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
}
(void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
switch (quantum_info->format)
{
case FloatingPointQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
(void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
(void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
break;
}
case SignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
break;
}
case UnsignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
break;
}
default:
break;
}
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
if (photometric == PHOTOMETRIC_RGB)
if ((image_info->interlace == PlaneInterlace) ||
(image_info->interlace == PartitionInterlace))
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
rows_per_strip=TIFFDefaultStripSize(tiff,0);
option=GetImageOption(image_info,"tiff:rows-per-strip");
if (option != (const char *) NULL)
rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
switch (compress_tag)
{
case COMPRESSION_JPEG:
{
#if defined(JPEG_SUPPORT)
const char
*sampling_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
rows_per_strip+=(16-(rows_per_strip % 16));
if (image_info->quality != UndefinedCompressionQuality)
(void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
{
const char
*value;
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
sampling_factor=(const char *) NULL;
value=GetImageProperty(image,"jpeg:sampling-factor");
if (value != (char *) NULL)
{
sampling_factor=value;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Input sampling-factors=%s",sampling_factor);
}
if (image_info->sampling_factor != (char *) NULL)
sampling_factor=image_info->sampling_factor;
if (sampling_factor != (const char *) NULL)
{
flags=ParseGeometry(sampling_factor,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
if (image->colorspace == YCbCrColorspace)
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
geometry_info.rho,(uint16) geometry_info.sigma);
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (bits_per_sample == 12)
(void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
#endif
break;
}
case COMPRESSION_ADOBE_DEFLATE:
{
rows_per_strip=(uint32) image->rows;
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
(void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
case COMPRESSION_CCITTFAX3:
{
/*
Byte-aligned EOL.
*/
rows_per_strip=(uint32) image->rows;
(void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
break;
}
case COMPRESSION_CCITTFAX4:
{
rows_per_strip=(uint32) image->rows;
break;
}
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
{
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
(void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
#endif
case COMPRESSION_LZW:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
break;
}
default:
break;
}
if (rows_per_strip < 1)
rows_per_strip=1;
if ((image->rows/rows_per_strip) >= (1UL << 15))
rows_per_strip=(uint32) (image->rows >> 15);
(void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))
{
unsigned short
units;
/*
Set image resolution.
*/
units=RESUNIT_NONE;
if (image->units == PixelsPerInchResolution)
units=RESUNIT_INCH;
if (image->units == PixelsPerCentimeterResolution)
units=RESUNIT_CENTIMETER;
(void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
(void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution);
(void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution);
if ((image->page.x < 0) || (image->page.y < 0))
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"TIFF: negative image positions unsupported","%s",
image->filename);
if ((image->page.x > 0) && (image->x_resolution > 0.0))
{
/*
Set horizontal image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
image->x_resolution);
}
if ((image->page.y > 0) && (image->y_resolution > 0.0))
{
/*
Set vertical image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
image->y_resolution);
}
}
if (image->chromaticity.white_point.x != 0.0)
{
float
chromaticity[6];
/*
Set image chromaticity.
*/
chromaticity[0]=(float) image->chromaticity.red_primary.x;
chromaticity[1]=(float) image->chromaticity.red_primary.y;
chromaticity[2]=(float) image->chromaticity.green_primary.x;
chromaticity[3]=(float) image->chromaticity.green_primary.y;
chromaticity[4]=(float) image->chromaticity.blue_primary.x;
chromaticity[5]=(float) image->chromaticity.blue_primary.y;
(void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
chromaticity[0]=(float) image->chromaticity.white_point.x;
chromaticity[1]=(float) image->chromaticity.white_point.y;
(void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
}
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1))
{
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
if (image->scene != 0)
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
GetImageListLength(image));
}
if (image->orientation != UndefinedOrientation)
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
(void) TIFFSetProfiles(tiff,image);
{
uint16
page,
pages;
page=(uint16) scene;
pages=(uint16) GetImageListLength(image);
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
(void) TIFFSetProperties(tiff,image_info,image);
DisableMSCWarning(4127)
if (0)
RestoreMSCWarning
(void) TIFFSetEXIFProperties(tiff,image);
/*
Write image scanlines.
*/
if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->endian=LSBEndian;
pixels=GetQuantumPixels(quantum_info);
tiff_info.scanline=GetQuantumPixels(quantum_info);
switch (photometric)
{
case PHOTOMETRIC_CIELAB:
case PHOTOMETRIC_YCBCR:
case PHOTOMETRIC_RGB:
{
/*
RGB TIFF image.
*/
switch (image_info->interlace)
{
case NoInterlace:
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PlaneInterlace:
case PartitionInterlace:
{
/*
Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,100,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,200,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,300,400);
if (status == MagickFalse)
break;
}
if (image->matte != MagickFalse)
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,400,400);
if (status == MagickFalse)
break;
}
break;
}
}
break;
}
case PHOTOMETRIC_SEPARATED:
{
/*
CMYK TIFF image.
*/
quantum_type=CMYKQuantum;
if (image->matte != MagickFalse)
quantum_type=CMYKAQuantum;
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PHOTOMETRIC_PALETTE:
{
uint16
*blue,
*green,
*red;
/*
Colormapped TIFF image.
*/
red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
(blue == (uint16 *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize TIFF colormap.
*/
(void) ResetMagickMemory(red,0,65536*sizeof(*red));
(void) ResetMagickMemory(green,0,65536*sizeof(*green));
(void) ResetMagickMemory(blue,0,65536*sizeof(*blue));
for (i=0; i < (ssize_t) image->colors; i++)
{
red[i]=ScaleQuantumToShort(image->colormap[i].red);
green[i]=ScaleQuantumToShort(image->colormap[i].green);
blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
}
(void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
red=(uint16 *) RelinquishMagickMemory(red);
green=(uint16 *) RelinquishMagickMemory(green);
blue=(uint16 *) RelinquishMagickMemory(blue);
}
default:
{
/*
Convert PseudoClass packets to contiguous grayscale scanlines.
*/
quantum_type=IndexQuantum;
if (image->matte != MagickFalse)
{
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayAlphaQuantum;
else
quantum_type=IndexAlphaQuantum;
}
else
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (image->colorspace == LabColorspace)
DecodeLabImage(image,&image->exception);
DestroyTIFFInfo(&tiff_info);
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
RestoreMSCWarning
TIFFPrintDirectory(tiff,stdout,MagickFalse);
(void) TIFFWriteDirectory(tiff);
image=SyncNextImageInList(image);
if (image == (Image *) NULL)
break;
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
TIFFClose(tiff);
return(MagickTrue);
}
Commit Message: Fix TIFF divide by zero (bug report from Donghai Zhu)
CWE ID: CWE-369
|
static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
Image *image)
{
#if !defined(TIFFDefaultStripSize)
#define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff))
#endif
const char
*mode,
*option;
CompressionType
compression;
EndianType
endian_type;
MagickBooleanType
debug,
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
ssize_t
y;
TIFF
*tiff;
TIFFInfo
tiff_info;
uint16
bits_per_sample,
compress_tag,
endian,
photometric;
uint32
rows_per_strip;
unsigned char
*pixels;
/*
Open TIFF file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) SetMagickThreadValue(tiff_exception,&image->exception);
endian_type=UndefinedEndian;
option=GetImageOption(image_info,"tiff:endian");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian_type=MSBEndian;
if (LocaleNCompare(option,"lsb",3) == 0)
endian_type=LSBEndian;;
}
switch (endian_type)
{
case LSBEndian: mode="wl"; break;
case MSBEndian: mode="wb"; break;
default: mode="w"; break;
}
#if defined(TIFF_VERSION_BIG)
if (LocaleCompare(image_info->magick,"TIFF64") == 0)
switch (endian_type)
{
case LSBEndian: mode="wl8"; break;
case MSBEndian: mode="wb8"; break;
default: mode="w8"; break;
}
#endif
tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
return(MagickFalse);
scene=0;
debug=IsEventLogging();
(void) debug;
do
{
/*
Initialize TIFF fields.
*/
if ((image_info->type != UndefinedType) &&
(image_info->type != OptimizeType))
(void) SetImageType(image,image_info->type);
compression=UndefinedCompression;
if (image->compression != JPEGCompression)
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
(void) SetImageType(image,BilevelType);
(void) SetImageDepth(image,1);
break;
}
case JPEGCompression:
{
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
break;
}
default:
break;
}
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
(quantum_info->format == UndefinedQuantumFormat) &&
(IsHighDynamicRangeImage(image,&image->exception) != MagickFalse))
{
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
(GetPreviousImageInList(image) != (Image *) NULL))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
if ((image->columns != (uint32) image->columns) ||
(image->rows != (uint32) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
(void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
(void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
switch (compression)
{
case FaxCompression:
{
compress_tag=COMPRESSION_CCITTFAX3;
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
case Group4Compression:
{
compress_tag=COMPRESSION_CCITTFAX4;
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
#if defined(COMPRESSION_JBIG)
case JBIG1Compression:
{
compress_tag=COMPRESSION_JBIG;
break;
}
#endif
case JPEGCompression:
{
compress_tag=COMPRESSION_JPEG;
break;
}
#if defined(COMPRESSION_LZMA)
case LZMACompression:
{
compress_tag=COMPRESSION_LZMA;
break;
}
#endif
case LZWCompression:
{
compress_tag=COMPRESSION_LZW;
break;
}
case RLECompression:
{
compress_tag=COMPRESSION_PACKBITS;
break;
}
case ZipCompression:
{
compress_tag=COMPRESSION_ADOBE_DEFLATE;
break;
}
case NoCompression:
default:
{
compress_tag=COMPRESSION_NONE;
break;
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
}
#else
switch (compress_tag)
{
#if defined(CCITT_SUPPORT)
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
#endif
#if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
case COMPRESSION_JPEG:
#endif
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
#endif
#if defined(LZW_SUPPORT)
case COMPRESSION_LZW:
#endif
#if defined(PACKBITS_SUPPORT)
case COMPRESSION_PACKBITS:
#endif
#if defined(ZIP_SUPPORT)
case COMPRESSION_ADOBE_DEFLATE:
#endif
case COMPRESSION_NONE:
break;
default:
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
break;
}
}
#endif
if (image->colorspace == CMYKColorspace)
{
photometric=PHOTOMETRIC_SEPARATED;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
(void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
}
else
{
/*
Full color TIFF raster.
*/
if (image->colorspace == LabColorspace)
{
photometric=PHOTOMETRIC_CIELAB;
EncodeLabImage(image,&image->exception);
}
else
if (image->colorspace == YCbCrColorspace)
{
photometric=PHOTOMETRIC_YCBCR;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
}
else
photometric=PHOTOMETRIC_RGB;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
if ((image_info->type != TrueColorType) &&
(image_info->type != TrueColorMatteType))
{
if ((image_info->type != PaletteType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
photometric=(uint16) (quantum_info->min_is_white !=
MagickFalse ? PHOTOMETRIC_MINISWHITE :
PHOTOMETRIC_MINISBLACK);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
if ((image->depth == 1) && (image->matte == MagickFalse))
SetImageMonochrome(image,&image->exception);
}
else
if (image->storage_class == PseudoClass)
{
size_t
depth;
/*
Colormapped TIFF raster.
*/
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
photometric=PHOTOMETRIC_PALETTE;
depth=1;
while ((GetQuantumRange(depth)+1) < image->colors)
depth<<=1;
status=SetQuantumDepth(image,quantum_info,depth);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
if ((compress_tag == COMPRESSION_CCITTFAX3) &&
(photometric != PHOTOMETRIC_MINISWHITE))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
else
if ((compress_tag == COMPRESSION_CCITTFAX4) &&
(photometric != PHOTOMETRIC_MINISWHITE))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
option=GetImageOption(image_info,"tiff:fill-order");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian=FILLORDER_MSB2LSB;
if (LocaleNCompare(option,"lsb",3) == 0)
endian=FILLORDER_LSB2MSB;
}
(void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
(void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
(void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
if (image->matte != MagickFalse)
{
uint16
extra_samples,
sample_info[1],
samples_per_pixel;
/*
TIFF has a matte channel.
*/
extra_samples=1;
sample_info[0]=EXTRASAMPLE_UNASSALPHA;
option=GetImageOption(image_info,"tiff:alpha");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"associated") == 0)
sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
else
if (LocaleCompare(option,"unspecified") == 0)
sample_info[0]=EXTRASAMPLE_UNSPECIFIED;
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
&samples_per_pixel);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
(void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
&sample_info);
if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
}
(void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
switch (quantum_info->format)
{
case FloatingPointQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
(void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
(void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
break;
}
case SignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
break;
}
case UnsignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
break;
}
default:
break;
}
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
if (photometric == PHOTOMETRIC_RGB)
if ((image_info->interlace == PlaneInterlace) ||
(image_info->interlace == PartitionInterlace))
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
rows_per_strip=1;
if (TIFFScanlineSize(tiff) != 0)
rows_per_strip=TIFFDefaultStripSize(tiff,0);
option=GetImageOption(image_info,"tiff:rows-per-strip");
if (option != (const char *) NULL)
rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
switch (compress_tag)
{
case COMPRESSION_JPEG:
{
#if defined(JPEG_SUPPORT)
const char
*sampling_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
rows_per_strip+=(16-(rows_per_strip % 16));
if (image_info->quality != UndefinedCompressionQuality)
(void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
{
const char
*value;
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
sampling_factor=(const char *) NULL;
value=GetImageProperty(image,"jpeg:sampling-factor");
if (value != (char *) NULL)
{
sampling_factor=value;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Input sampling-factors=%s",sampling_factor);
}
if (image_info->sampling_factor != (char *) NULL)
sampling_factor=image_info->sampling_factor;
if (sampling_factor != (const char *) NULL)
{
flags=ParseGeometry(sampling_factor,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
if (image->colorspace == YCbCrColorspace)
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
geometry_info.rho,(uint16) geometry_info.sigma);
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (bits_per_sample == 12)
(void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
#endif
break;
}
case COMPRESSION_ADOBE_DEFLATE:
{
rows_per_strip=(uint32) image->rows;
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
(void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
case COMPRESSION_CCITTFAX3:
{
/*
Byte-aligned EOL.
*/
rows_per_strip=(uint32) image->rows;
(void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
break;
}
case COMPRESSION_CCITTFAX4:
{
rows_per_strip=(uint32) image->rows;
break;
}
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
{
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
(void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
#endif
case COMPRESSION_LZW:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
break;
}
default:
break;
}
if (rows_per_strip < 1)
rows_per_strip=1;
if ((image->rows/rows_per_strip) >= (1UL << 15))
rows_per_strip=(uint32) (image->rows >> 15);
(void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))
{
unsigned short
units;
/*
Set image resolution.
*/
units=RESUNIT_NONE;
if (image->units == PixelsPerInchResolution)
units=RESUNIT_INCH;
if (image->units == PixelsPerCentimeterResolution)
units=RESUNIT_CENTIMETER;
(void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
(void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution);
(void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution);
if ((image->page.x < 0) || (image->page.y < 0))
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"TIFF: negative image positions unsupported","%s",
image->filename);
if ((image->page.x > 0) && (image->x_resolution > 0.0))
{
/*
Set horizontal image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
image->x_resolution);
}
if ((image->page.y > 0) && (image->y_resolution > 0.0))
{
/*
Set vertical image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
image->y_resolution);
}
}
if (image->chromaticity.white_point.x != 0.0)
{
float
chromaticity[6];
/*
Set image chromaticity.
*/
chromaticity[0]=(float) image->chromaticity.red_primary.x;
chromaticity[1]=(float) image->chromaticity.red_primary.y;
chromaticity[2]=(float) image->chromaticity.green_primary.x;
chromaticity[3]=(float) image->chromaticity.green_primary.y;
chromaticity[4]=(float) image->chromaticity.blue_primary.x;
chromaticity[5]=(float) image->chromaticity.blue_primary.y;
(void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
chromaticity[0]=(float) image->chromaticity.white_point.x;
chromaticity[1]=(float) image->chromaticity.white_point.y;
(void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
}
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1))
{
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
if (image->scene != 0)
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
GetImageListLength(image));
}
if (image->orientation != UndefinedOrientation)
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
(void) TIFFSetProfiles(tiff,image);
{
uint16
page,
pages;
page=(uint16) scene;
pages=(uint16) GetImageListLength(image);
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
(void) TIFFSetProperties(tiff,image_info,image);
DisableMSCWarning(4127)
if (0)
RestoreMSCWarning
(void) TIFFSetEXIFProperties(tiff,image);
/*
Write image scanlines.
*/
if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->endian=LSBEndian;
pixels=GetQuantumPixels(quantum_info);
tiff_info.scanline=GetQuantumPixels(quantum_info);
switch (photometric)
{
case PHOTOMETRIC_CIELAB:
case PHOTOMETRIC_YCBCR:
case PHOTOMETRIC_RGB:
{
/*
RGB TIFF image.
*/
switch (image_info->interlace)
{
case NoInterlace:
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PlaneInterlace:
case PartitionInterlace:
{
/*
Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,100,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,200,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,300,400);
if (status == MagickFalse)
break;
}
if (image->matte != MagickFalse)
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,400,400);
if (status == MagickFalse)
break;
}
break;
}
}
break;
}
case PHOTOMETRIC_SEPARATED:
{
/*
CMYK TIFF image.
*/
quantum_type=CMYKQuantum;
if (image->matte != MagickFalse)
quantum_type=CMYKAQuantum;
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PHOTOMETRIC_PALETTE:
{
uint16
*blue,
*green,
*red;
/*
Colormapped TIFF image.
*/
red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
(blue == (uint16 *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize TIFF colormap.
*/
(void) ResetMagickMemory(red,0,65536*sizeof(*red));
(void) ResetMagickMemory(green,0,65536*sizeof(*green));
(void) ResetMagickMemory(blue,0,65536*sizeof(*blue));
for (i=0; i < (ssize_t) image->colors; i++)
{
red[i]=ScaleQuantumToShort(image->colormap[i].red);
green[i]=ScaleQuantumToShort(image->colormap[i].green);
blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
}
(void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
red=(uint16 *) RelinquishMagickMemory(red);
green=(uint16 *) RelinquishMagickMemory(green);
blue=(uint16 *) RelinquishMagickMemory(blue);
}
default:
{
/*
Convert PseudoClass packets to contiguous grayscale scanlines.
*/
quantum_type=IndexQuantum;
if (image->matte != MagickFalse)
{
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayAlphaQuantum;
else
quantum_type=IndexAlphaQuantum;
}
else
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (image->colorspace == LabColorspace)
DecodeLabImage(image,&image->exception);
DestroyTIFFInfo(&tiff_info);
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
RestoreMSCWarning
TIFFPrintDirectory(tiff,stdout,MagickFalse);
(void) TIFFWriteDirectory(tiff);
image=SyncNextImageInList(image);
if (image == (Image *) NULL)
break;
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
TIFFClose(tiff);
return(MagickTrue);
}
| 168,637 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: struct crypto_template *crypto_lookup_template(const char *name)
{
return try_then_request_module(__crypto_lookup_template(name), "%s",
name);
}
Commit Message: crypto: include crypto- module prefix in template
This adds the module loading prefix "crypto-" to the template lookup
as well.
For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly
includes the "crypto-" prefix at every level, correctly rejecting "vfat":
net-pf-38
algif-hash
crypto-vfat(blowfish)
crypto-vfat(blowfish)-all
crypto-vfat
Reported-by: Mathias Krause <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Acked-by: Mathias Krause <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264
|
struct crypto_template *crypto_lookup_template(const char *name)
{
return try_then_request_module(__crypto_lookup_template(name),
"crypto-%s", name);
}
| 166,771 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static ps_sd *ps_sd_new(ps_mm *data, const char *key)
{
php_uint32 hv, slot;
ps_sd *sd;
int keylen;
keylen = strlen(key);
sd = mm_malloc(data->mm, sizeof(ps_sd) + keylen);
if (!sd) {
TSRMLS_FETCH();
php_error_docref(NULL TSRMLS_CC, E_WARNING, "mm_malloc failed, avail %d, err %s", mm_available(data->mm), mm_error());
return NULL;
}
hv = ps_sd_hash(key, keylen);
slot = hv & data->hash_max;
sd->ctime = 0;
sd->hv = hv;
sd->data = NULL;
sd->alloclen = sd->datalen = 0;
memcpy(sd->key, key, keylen + 1);
sd->next = data->hash[slot];
data->hash[slot] = sd;
data->hash_cnt++;
if (!sd->next) {
if (data->hash_cnt >= data->hash_max) {
hash_split(data);
}
}
ps_mm_debug(("inserting %s(%p) into slot %d\n", key, sd, slot));
return sd;
}
Commit Message:
CWE ID: CWE-264
|
static ps_sd *ps_sd_new(ps_mm *data, const char *key)
{
php_uint32 hv, slot;
ps_sd *sd;
int keylen;
keylen = strlen(key);
sd = mm_malloc(data->mm, sizeof(ps_sd) + keylen);
if (!sd) {
TSRMLS_FETCH();
php_error_docref(NULL TSRMLS_CC, E_WARNING, "mm_malloc failed, avail %ld, err %s", mm_available(data->mm), mm_error());
return NULL;
}
hv = ps_sd_hash(key, keylen);
slot = hv & data->hash_max;
sd->ctime = 0;
sd->hv = hv;
sd->data = NULL;
sd->alloclen = sd->datalen = 0;
memcpy(sd->key, key, keylen + 1);
sd->next = data->hash[slot];
data->hash[slot] = sd;
data->hash_cnt++;
if (!sd->next) {
if (data->hash_cnt >= data->hash_max) {
hash_split(data);
}
}
ps_mm_debug(("inserting %s(%p) into slot %d\n", key, sd, slot));
return sd;
}
| 164,872 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PaintImage AcceleratedStaticBitmapImage::PaintImageForCurrentFrame() {
CheckThread();
if (!IsValid())
return PaintImage();
sk_sp<SkImage> image;
if (original_skia_image_ &&
original_skia_image_thread_id_ ==
Platform::Current()->CurrentThread()->ThreadId()) {
image = original_skia_image_;
} else {
CreateImageFromMailboxIfNeeded();
image = texture_holder_->GetSkImage();
}
return CreatePaintImageBuilder()
.set_image(image, paint_image_content_id_)
.set_completion_state(PaintImage::CompletionState::DONE)
.TakePaintImage();
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119
|
PaintImage AcceleratedStaticBitmapImage::PaintImageForCurrentFrame() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (!IsValid())
return PaintImage();
sk_sp<SkImage> image;
if (original_skia_image_ &&
original_skia_image_task_runner_->BelongsToCurrentThread()) {
image = original_skia_image_;
} else {
CreateImageFromMailboxIfNeeded();
image = texture_holder_->GetSkImage();
}
return CreatePaintImageBuilder()
.set_image(image, paint_image_content_id_)
.set_completion_state(PaintImage::CompletionState::DONE)
.TakePaintImage();
}
| 172,596 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: Block::Block(long long start, long long size_, long long discard_padding) :
m_start(start),
m_size(size_),
m_track(0),
m_timecode(-1),
m_flags(0),
m_frames(NULL),
m_frame_count(-1),
m_discard_padding(discard_padding)
{
}
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
|
Block::Block(long long start, long long size_, long long discard_padding) :
| 174,240 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static ogg_uint32_t decpack(long entry,long used_entry,long quantvals,
codebook *b,oggpack_buffer *opb,int maptype){
ogg_uint32_t ret=0;
int j;
switch(b->dec_type){
case 0:
return (ogg_uint32_t)entry;
case 1:
if(maptype==1){
/* vals are already read into temporary column vector here */
for(j=0;j<b->dim;j++){
ogg_uint32_t off=entry%quantvals;
entry/=quantvals;
ret|=((ogg_uint16_t *)(b->q_val))[off]<<(b->q_bits*j);
}
}else{
for(j=0;j<b->dim;j++)
ret|=oggpack_read(opb,b->q_bits)<<(b->q_bits*j);
}
return ret;
case 2:
for(j=0;j<b->dim;j++){
ogg_uint32_t off=entry%quantvals;
entry/=quantvals;
ret|=off<<(b->q_pack*j);
}
return ret;
case 3:
return (ogg_uint32_t)used_entry;
}
return 0; /* silence compiler */
}
Commit Message: Fix out of bounds access in codebook processing
Bug: 62800140
Test: ran poc, CTS
Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37
(cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0)
CWE ID: CWE-200
|
static ogg_uint32_t decpack(long entry,long used_entry,long quantvals,
codebook *b,oggpack_buffer *opb,int maptype){
ogg_uint32_t ret=0;
int j;
switch(b->dec_type){
case 0:
return (ogg_uint32_t)entry;
case 1:
if(maptype==1){
/* vals are already read into temporary column vector here */
for(j=0;j<b->dim;j++){
ogg_uint32_t off=entry%quantvals;
entry/=quantvals;
ret|=((ogg_uint16_t *)(b->q_val))[off]<<(b->q_bits*j);
}
}else{
for(j=0;j<b->dim;j++)
ret|=oggpack_read(opb,b->q_bits)<<(b->q_bits*j);
}
return ret;
case 2:
for(j=0;j<b->dim;j++){
ogg_uint32_t off=entry%quantvals;
entry/=quantvals;
ret|=off<<(b->q_pack*j);
}
return ret;
case 3:
return (ogg_uint32_t)used_entry;
}
return 0; /* silence compiler */
}
| 173,985 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void sync_lockstate_on_connect(btif_hh_device_t *p_dev)
{
int keylockstates;
BTIF_TRACE_EVENT("%s: Syncing keyboard lock states after "\
"reconnect...",__FUNCTION__);
/*If the device is connected, update keyboard state */
update_keyboard_lockstates(p_dev);
/*Check if the lockstate of caps,scroll,num is set.
If so, send a report to the kernel
so the lockstate is in sync */
keylockstates = get_keylockstates();
if (keylockstates)
{
BTIF_TRACE_DEBUG("%s: Sending hid report to kernel "\
"indicating lock key state 0x%x",__FUNCTION__,
keylockstates);
usleep(200000);
toggle_os_keylockstates(p_dev->fd, keylockstates);
}
else
{
BTIF_TRACE_DEBUG("%s: NOT sending hid report to kernel "\
"indicating lock key state 0x%x",__FUNCTION__,
keylockstates);
}
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
static void sync_lockstate_on_connect(btif_hh_device_t *p_dev)
{
int keylockstates;
BTIF_TRACE_EVENT("%s: Syncing keyboard lock states after "\
"reconnect...",__FUNCTION__);
/*If the device is connected, update keyboard state */
update_keyboard_lockstates(p_dev);
/*Check if the lockstate of caps,scroll,num is set.
If so, send a report to the kernel
so the lockstate is in sync */
keylockstates = get_keylockstates();
if (keylockstates)
{
BTIF_TRACE_DEBUG("%s: Sending hid report to kernel "\
"indicating lock key state 0x%x",__FUNCTION__,
keylockstates);
TEMP_FAILURE_RETRY(usleep(200000));
toggle_os_keylockstates(p_dev->fd, keylockstates);
}
else
{
BTIF_TRACE_DEBUG("%s: NOT sending hid report to kernel "\
"indicating lock key state 0x%x",__FUNCTION__,
keylockstates);
}
}
| 173,437 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: purgekeys_2_svc(purgekeys_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg, *funcname;
gss_buffer_desc client_name, service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
funcname = "kadm5_purgekeys";
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (!cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) &&
(CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY,
arg->princ, NULL))) {
ret.code = KADM5_AUTH_MODIFY;
log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp);
} else {
ret.code = kadm5_purgekeys((void *)handle, arg->princ,
arg->keepkvno);
if (ret.code != 0)
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done(funcname, prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119
|
purgekeys_2_svc(purgekeys_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg, *funcname;
gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER;
gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
funcname = "kadm5_purgekeys";
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (!cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) &&
(CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY,
arg->princ, NULL))) {
ret.code = KADM5_AUTH_MODIFY;
log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp);
} else {
ret.code = kadm5_purgekeys((void *)handle, arg->princ,
arg->keepkvno);
if (ret.code != 0)
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done(funcname, prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
exit_func:
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 167,522 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: LoadWatcher(ScriptContext* context,
content::RenderFrame* frame,
v8::Local<v8::Function> cb)
: content::RenderFrameObserver(frame),
context_(context),
callback_(context->isolate(), cb) {
if (ExtensionFrameHelper::Get(frame)->
did_create_current_document_element()) {
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&LoadWatcher::CallbackAndDie, base::Unretained(this),
true));
}
}
Commit Message: Fix re-entrancy and lifetime issue in RenderFrameObserverNatives::OnDocumentElementCreated
BUG=585268,568130
Review URL: https://codereview.chromium.org/1684953002
Cr-Commit-Position: refs/heads/master@{#374758}
CWE ID:
|
LoadWatcher(ScriptContext* context,
LoadWatcher(content::RenderFrame* frame,
const base::Callback<void(bool)>& callback)
: content::RenderFrameObserver(frame), callback_(callback) {}
void DidCreateDocumentElement() override {
// The callback must be run as soon as the root element is available.
// Running the callback may trigger DidCreateDocumentElement or
// DidFailProvisionalLoad, so delete this before running the callback.
base::Callback<void(bool)> callback = callback_;
delete this;
callback.Run(true);
}
| 172,145 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool SessionManager::Remove(const std::string& id) {
std::map<std::string, Session*>::iterator it;
Session* session;
base::AutoLock lock(map_lock_);
it = map_.find(id);
if (it == map_.end()) {
VLOG(1) << "No such session with ID " << id;
return false;
}
session = it->second;
map_.erase(it);
return true;
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool SessionManager::Remove(const std::string& id) {
std::map<std::string, Session*>::iterator it;
Session* session;
base::AutoLock lock(map_lock_);
it = map_.find(id);
if (it == map_.end())
return false;
session = it->second;
map_.erase(it);
return true;
}
| 170,464 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: TouchpadLibrary* CrosLibrary::GetTouchpadLibrary() {
return touchpad_lib_.GetDefaultImpl(use_stub_impl_);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
|
TouchpadLibrary* CrosLibrary::GetTouchpadLibrary() {
| 170,633 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool ResourcePrefetchPredictor::GetRedirectEndpointsForPreconnect(
const url::Origin& entry_origin,
const RedirectDataMap& redirect_data,
PreconnectPrediction* prediction) const {
if (!base::FeatureList::IsEnabled(
features::kLoadingPreconnectToRedirectTarget)) {
return false;
}
DCHECK(!prediction || prediction->requests.empty());
RedirectData data;
if (!redirect_data.TryGetData(entry_origin.host(), &data))
return false;
const float kMinRedirectConfidenceToTriggerPrefetch = 0.1f;
bool at_least_one_redirect_endpoint_added = false;
for (const auto& redirect : data.redirect_endpoints()) {
if (ComputeRedirectConfidence(redirect) <
kMinRedirectConfidenceToTriggerPrefetch) {
continue;
}
std::string redirect_scheme =
redirect.url_scheme().empty() ? "https" : redirect.url_scheme();
int redirect_port = redirect.has_url_port() ? redirect.url_port() : 443;
const url::Origin redirect_origin = url::Origin::CreateFromNormalizedTuple(
redirect_scheme, redirect.url(), redirect_port);
if (redirect_origin == entry_origin) {
continue;
}
if (prediction) {
prediction->requests.emplace_back(
redirect_origin.GetURL(), 1 /* num_scokets */,
net::NetworkIsolationKey(redirect_origin, redirect_origin));
}
at_least_one_redirect_endpoint_added = true;
}
if (prediction && prediction->host.empty() &&
at_least_one_redirect_endpoint_added) {
prediction->host = entry_origin.host();
}
return at_least_one_redirect_endpoint_added;
}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <[email protected]>
Reviewed-by: Alex Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125
|
bool ResourcePrefetchPredictor::GetRedirectEndpointsForPreconnect(
const url::Origin& entry_origin,
const RedirectDataMap& redirect_data,
PreconnectPrediction* prediction) const {
if (!base::FeatureList::IsEnabled(
features::kLoadingPreconnectToRedirectTarget)) {
return false;
}
DCHECK(!prediction || prediction->requests.empty());
RedirectData data;
if (!redirect_data.TryGetData(entry_origin.host(), &data))
return false;
const float kMinRedirectConfidenceToTriggerPrefetch = 0.1f;
bool at_least_one_redirect_endpoint_added = false;
for (const auto& redirect : data.redirect_endpoints()) {
if (ComputeRedirectConfidence(redirect) <
kMinRedirectConfidenceToTriggerPrefetch) {
continue;
}
std::string redirect_scheme =
redirect.url_scheme().empty() ? "https" : redirect.url_scheme();
int redirect_port = redirect.has_url_port() ? redirect.url_port() : 443;
const url::Origin redirect_origin = url::Origin::CreateFromNormalizedTuple(
redirect_scheme, redirect.url(), redirect_port);
if (redirect_origin == entry_origin) {
continue;
}
if (prediction) {
prediction->requests.emplace_back(
redirect_origin, 1 /* num_scokets */,
net::NetworkIsolationKey(redirect_origin, redirect_origin));
}
at_least_one_redirect_endpoint_added = true;
}
if (prediction && prediction->host.empty() &&
at_least_one_redirect_endpoint_added) {
prediction->host = entry_origin.host();
}
return at_least_one_redirect_endpoint_added;
}
| 172,378 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static bool snd_ctl_remove_numid_conflict(struct snd_card *card,
unsigned int count)
{
struct snd_kcontrol *kctl;
list_for_each_entry(kctl, &card->controls, list) {
if (kctl->id.numid < card->last_numid + 1 + count &&
kctl->id.numid + kctl->count > card->last_numid + 1) {
card->last_numid = kctl->id.numid + kctl->count - 1;
return true;
}
}
return false;
}
Commit Message: ALSA: control: Handle numid overflow
Each control gets automatically assigned its numids when the control is created.
The allocation is done by incrementing the numid by the amount of allocated
numids per allocation. This means that excessive creation and destruction of
controls (e.g. via SNDRV_CTL_IOCTL_ELEM_ADD/REMOVE) can cause the id to
eventually overflow. Currently when this happens for the control that caused the
overflow kctl->id.numid + kctl->count will also over flow causing it to be
smaller than kctl->id.numid. Most of the code assumes that this is something
that can not happen, so we need to make sure that it won't happen
Signed-off-by: Lars-Peter Clausen <[email protected]>
Acked-by: Jaroslav Kysela <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-189
|
static bool snd_ctl_remove_numid_conflict(struct snd_card *card,
unsigned int count)
{
struct snd_kcontrol *kctl;
/* Make sure that the ids assigned to the control do not wrap around */
if (card->last_numid >= UINT_MAX - count)
card->last_numid = 0;
list_for_each_entry(kctl, &card->controls, list) {
if (kctl->id.numid < card->last_numid + 1 + count &&
kctl->id.numid + kctl->count > card->last_numid + 1) {
card->last_numid = kctl->id.numid + kctl->count - 1;
return true;
}
}
return false;
}
| 166,290 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_FUNCTION(imageaffinematrixget)
{
double affine[6];
long type;
zval *options;
zval **tmp;
int res = GD_FALSE, i;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &type, &options) == FAILURE) {
return;
}
switch((gdAffineStandardMatrix)type) {
case GD_AFFINE_TRANSLATE:
case GD_AFFINE_SCALE: {
double x, y;
if (Z_TYPE_P(options) != IS_ARRAY) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array expected as options");
}
if (zend_hash_find(HASH_OF(options), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
convert_to_double_ex(tmp);
x = Z_DVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(options), "y", sizeof("y"), (void **)&tmp) != FAILURE) {
convert_to_double_ex(tmp);
y = Z_DVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (type == GD_AFFINE_TRANSLATE) {
res = gdAffineTranslate(affine, x, y);
} else {
res = gdAffineScale(affine, x, y);
}
break;
}
case GD_AFFINE_ROTATE:
case GD_AFFINE_SHEAR_HORIZONTAL:
case GD_AFFINE_SHEAR_VERTICAL: {
double angle;
convert_to_double_ex(&options);
angle = Z_DVAL_P(options);
if (type == GD_AFFINE_SHEAR_HORIZONTAL) {
res = gdAffineShearHorizontal(affine, angle);
} else if (type == GD_AFFINE_SHEAR_VERTICAL) {
res = gdAffineShearVertical(affine, angle);
} else {
res = gdAffineRotate(affine, angle);
}
break;
}
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %li", type);
RETURN_FALSE;
}
if (res == GD_FALSE) {
RETURN_FALSE;
} else {
array_init(return_value);
for (i = 0; i < 6; i++) {
add_index_double(return_value, i, affine[i]);
}
}
}
Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop())
And also fixed the bug: arguments are altered after some calls
CWE ID: CWE-189
|
PHP_FUNCTION(imageaffinematrixget)
{
double affine[6];
long type;
zval *options;
zval **tmp;
int res = GD_FALSE, i;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &type, &options) == FAILURE) {
return;
}
switch((gdAffineStandardMatrix)type) {
case GD_AFFINE_TRANSLATE:
case GD_AFFINE_SCALE: {
double x, y;
if (Z_TYPE_P(options) != IS_ARRAY) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array expected as options");
}
if (zend_hash_find(HASH_OF(options), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_DOUBLE) {
zval dval;
dval = **tmp;
zval_copy_ctor(&dval);
convert_to_double(&dval);
x = Z_DVAL(dval);
} else {
x = Z_DVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(options), "y", sizeof("y"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_DOUBLE) {
zval dval;
dval = **tmp;
zval_copy_ctor(&dval);
convert_to_double(&dval);
y = Z_DVAL(dval);
} else {
y = Z_DVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (type == GD_AFFINE_TRANSLATE) {
res = gdAffineTranslate(affine, x, y);
} else {
res = gdAffineScale(affine, x, y);
}
break;
}
case GD_AFFINE_ROTATE:
case GD_AFFINE_SHEAR_HORIZONTAL:
case GD_AFFINE_SHEAR_VERTICAL: {
double angle;
convert_to_double_ex(&options);
angle = Z_DVAL_P(options);
if (type == GD_AFFINE_SHEAR_HORIZONTAL) {
res = gdAffineShearHorizontal(affine, angle);
} else if (type == GD_AFFINE_SHEAR_VERTICAL) {
res = gdAffineShearVertical(affine, angle);
} else {
res = gdAffineRotate(affine, angle);
}
break;
}
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %li", type);
RETURN_FALSE;
}
if (res == GD_FALSE) {
RETURN_FALSE;
} else {
array_init(return_value);
for (i = 0; i < 6; i++) {
add_index_double(return_value, i, affine[i]);
}
}
}
| 166,429 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: GLboolean WebGLRenderingContextBase::isBuffer(WebGLBuffer* buffer) {
if (!buffer || isContextLost())
return 0;
if (!buffer->HasEverBeenBound())
return 0;
if (buffer->IsDeleted())
return 0;
return ContextGL()->IsBuffer(buffer->Object());
}
Commit Message: Validate all incoming WebGLObjects.
A few entry points were missing the correct validation.
Tested with improved conformance tests in
https://github.com/KhronosGroup/WebGL/pull/2654 .
Bug: 848914
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008
Reviewed-on: https://chromium-review.googlesource.com/1086718
Reviewed-by: Kai Ninomiya <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Commit-Queue: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565016}
CWE ID: CWE-119
|
GLboolean WebGLRenderingContextBase::isBuffer(WebGLBuffer* buffer) {
if (!buffer || isContextLost() || !buffer->Validate(ContextGroup(), this))
return 0;
if (!buffer->HasEverBeenBound())
return 0;
if (buffer->IsDeleted())
return 0;
return ContextGL()->IsBuffer(buffer->Object());
}
| 173,128 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: Cluster::GetEntry(
const CuePoint& cp,
const CuePoint::TrackPosition& tp) const
{
assert(m_pSegment);
#if 0
LoadBlockEntries();
if (m_entries == NULL)
return NULL;
const long long count = m_entries_count;
if (count <= 0)
return NULL;
const long long tc = cp.GetTimeCode();
if ((tp.m_block > 0) && (tp.m_block <= count))
{
const size_t block = static_cast<size_t>(tp.m_block);
const size_t index = block - 1;
const BlockEntry* const pEntry = m_entries[index];
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if ((pBlock->GetTrackNumber() == tp.m_track) &&
(pBlock->GetTimeCode(this) == tc))
{
return pEntry;
}
}
const BlockEntry* const* i = m_entries;
const BlockEntry* const* const j = i + count;
while (i != j)
{
#ifdef _DEBUG
const ptrdiff_t idx = i - m_entries;
idx;
#endif
const BlockEntry* const pEntry = *i++;
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if (pBlock->GetTrackNumber() != tp.m_track)
continue;
const long long tc_ = pBlock->GetTimeCode(this);
assert(tc_ >= 0);
if (tc_ < tc)
continue;
if (tc_ > tc)
return NULL;
const Tracks* const pTracks = m_pSegment->GetTracks();
assert(pTracks);
const long tn = static_cast<long>(tp.m_track);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
if (pTrack == NULL)
return NULL;
const long long type = pTrack->GetType();
if (type == 2) //audio
return pEntry;
if (type != 1) //not video
return NULL;
if (!pBlock->IsKey())
return NULL;
return pEntry;
}
return NULL;
#else
const long long tc = cp.GetTimeCode();
if (tp.m_block > 0)
{
const long block = static_cast<long>(tp.m_block);
const long index = block - 1;
while (index >= m_entries_count)
{
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) //TODO: can this happen?
return NULL;
if (status > 0) //nothing remains to be parsed
return NULL;
}
const BlockEntry* const pEntry = m_entries[index];
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if ((pBlock->GetTrackNumber() == tp.m_track) &&
(pBlock->GetTimeCode(this) == tc))
{
return pEntry;
}
}
long index = 0;
for (;;)
{
if (index >= m_entries_count)
{
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) //TODO: can this happen?
return NULL;
if (status > 0) //nothing remains to be parsed
return NULL;
assert(m_entries);
assert(index < m_entries_count);
}
const BlockEntry* const pEntry = m_entries[index];
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if (pBlock->GetTrackNumber() != tp.m_track)
{
++index;
continue;
}
const long long tc_ = pBlock->GetTimeCode(this);
if (tc_ < tc)
{
++index;
continue;
}
if (tc_ > tc)
return NULL;
const Tracks* const pTracks = m_pSegment->GetTracks();
assert(pTracks);
const long tn = static_cast<long>(tp.m_track);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
if (pTrack == NULL)
return NULL;
const long long type = pTrack->GetType();
if (type == 2) //audio
return pEntry;
if (type != 1) //not video
return NULL;
if (!pBlock->IsKey())
return NULL;
return pEntry;
}
#endif
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
|
Cluster::GetEntry(
const BlockEntry* Cluster::GetEntry(const CuePoint& cp,
const CuePoint::TrackPosition& tp) const {
assert(m_pSegment);
#if 0
LoadBlockEntries();
if (m_entries == NULL)
return NULL;
const long long count = m_entries_count;
if (count <= 0)
return NULL;
const long long tc = cp.GetTimeCode();
if ((tp.m_block > 0) && (tp.m_block <= count))
{
const size_t block = static_cast<size_t>(tp.m_block);
const size_t index = block - 1;
const BlockEntry* const pEntry = m_entries[index];
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if ((pBlock->GetTrackNumber() == tp.m_track) &&
(pBlock->GetTimeCode(this) == tc))
{
return pEntry;
}
}
const BlockEntry* const* i = m_entries;
const BlockEntry* const* const j = i + count;
while (i != j)
{
#ifdef _DEBUG
const ptrdiff_t idx = i - m_entries;
idx;
#endif
const BlockEntry* const pEntry = *i++;
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if (pBlock->GetTrackNumber() != tp.m_track)
continue;
const long long tc_ = pBlock->GetTimeCode(this);
assert(tc_ >= 0);
if (tc_ < tc)
continue;
if (tc_ > tc)
return NULL;
const Tracks* const pTracks = m_pSegment->GetTracks();
assert(pTracks);
const long tn = static_cast<long>(tp.m_track);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
if (pTrack == NULL)
return NULL;
const long long type = pTrack->GetType();
if (type == 2) //audio
return pEntry;
if (type != 1) //not video
return NULL;
if (!pBlock->IsKey())
return NULL;
return pEntry;
}
return NULL;
#else
const long long tc = cp.GetTimeCode();
if (tp.m_block > 0) {
const long block = static_cast<long>(tp.m_block);
const long index = block - 1;
while (index >= m_entries_count) {
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) // TODO: can this happen?
return NULL;
if (status > 0) // nothing remains to be parsed
return NULL;
}
const BlockEntry* const pEntry = m_entries[index];
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if ((pBlock->GetTrackNumber() == tp.m_track) &&
(pBlock->GetTimeCode(this) == tc)) {
return pEntry;
}
}
long index = 0;
for (;;) {
if (index >= m_entries_count) {
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) // TODO: can this happen?
return NULL;
if (status > 0) // nothing remains to be parsed
return NULL;
assert(m_entries);
assert(index < m_entries_count);
}
const BlockEntry* const pEntry = m_entries[index];
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if (pBlock->GetTrackNumber() != tp.m_track) {
++index;
continue;
}
const long long tc_ = pBlock->GetTimeCode(this);
if (tc_ < tc) {
++index;
continue;
}
if (tc_ > tc)
return NULL;
const Tracks* const pTracks = m_pSegment->GetTracks();
assert(pTracks);
const long tn = static_cast<long>(tp.m_track);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
if (pTrack == NULL)
return NULL;
const long long type = pTrack->GetType();
if (type == 2) // audio
return pEntry;
if (type != 1) // not video
return NULL;
if (!pBlock->IsKey())
return NULL;
return pEntry;
}
#endif
}
| 174,316 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int __kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem,
int user_alloc)
{
int r;
gfn_t base_gfn;
unsigned long npages;
unsigned long i;
struct kvm_memory_slot *memslot;
struct kvm_memory_slot old, new;
struct kvm_memslots *slots, *old_memslots;
r = -EINVAL;
/* General sanity checks */
if (mem->memory_size & (PAGE_SIZE - 1))
goto out;
if (mem->guest_phys_addr & (PAGE_SIZE - 1))
goto out;
/* We can read the guest memory with __xxx_user() later on. */
if (user_alloc &&
((mem->userspace_addr & (PAGE_SIZE - 1)) ||
!access_ok(VERIFY_WRITE,
(void __user *)(unsigned long)mem->userspace_addr,
mem->memory_size)))
goto out;
if (mem->slot >= KVM_MEM_SLOTS_NUM)
goto out;
if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
goto out;
memslot = id_to_memslot(kvm->memslots, mem->slot);
base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
npages = mem->memory_size >> PAGE_SHIFT;
r = -EINVAL;
if (npages > KVM_MEM_MAX_NR_PAGES)
goto out;
if (!npages)
mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
new = old = *memslot;
new.id = mem->slot;
new.base_gfn = base_gfn;
new.npages = npages;
new.flags = mem->flags;
/* Disallow changing a memory slot's size. */
r = -EINVAL;
if (npages && old.npages && npages != old.npages)
goto out_free;
/* Check for overlaps */
r = -EEXIST;
for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
struct kvm_memory_slot *s = &kvm->memslots->memslots[i];
if (s == memslot || !s->npages)
continue;
if (!((base_gfn + npages <= s->base_gfn) ||
(base_gfn >= s->base_gfn + s->npages)))
goto out_free;
}
/* Free page dirty bitmap if unneeded */
if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
new.dirty_bitmap = NULL;
r = -ENOMEM;
/* Allocate if a slot is being created */
#ifndef CONFIG_S390
if (npages && !new.rmap) {
new.rmap = vzalloc(npages * sizeof(*new.rmap));
if (!new.rmap)
goto out_free;
new.user_alloc = user_alloc;
new.userspace_addr = mem->userspace_addr;
}
if (!npages)
goto skip_lpage;
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) {
unsigned long ugfn;
unsigned long j;
int lpages;
int level = i + 2;
/* Avoid unused variable warning if no large pages */
(void)level;
if (new.lpage_info[i])
continue;
lpages = 1 + ((base_gfn + npages - 1)
>> KVM_HPAGE_GFN_SHIFT(level));
lpages -= base_gfn >> KVM_HPAGE_GFN_SHIFT(level);
new.lpage_info[i] = vzalloc(lpages * sizeof(*new.lpage_info[i]));
if (!new.lpage_info[i])
goto out_free;
if (base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
new.lpage_info[i][0].write_count = 1;
if ((base_gfn+npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
new.lpage_info[i][lpages - 1].write_count = 1;
ugfn = new.userspace_addr >> PAGE_SHIFT;
/*
* If the gfn and userspace address are not aligned wrt each
* other, or if explicitly asked to, disable large page
* support for this slot
*/
if ((base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
!largepages_enabled)
for (j = 0; j < lpages; ++j)
new.lpage_info[i][j].write_count = 1;
}
skip_lpage:
/* Allocate page dirty bitmap if needed */
if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
if (kvm_create_dirty_bitmap(&new) < 0)
goto out_free;
/* destroy any largepage mappings for dirty tracking */
}
#else /* not defined CONFIG_S390 */
new.user_alloc = user_alloc;
if (user_alloc)
new.userspace_addr = mem->userspace_addr;
#endif /* not defined CONFIG_S390 */
if (!npages) {
struct kvm_memory_slot *slot;
r = -ENOMEM;
slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
GFP_KERNEL);
if (!slots)
goto out_free;
slot = id_to_memslot(slots, mem->slot);
slot->flags |= KVM_MEMSLOT_INVALID;
update_memslots(slots, NULL);
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
/* From this point no new shadow pages pointing to a deleted
* memslot will be created.
*
* validation of sp->gfn happens in:
* - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
* - kvm_is_visible_gfn (mmu_check_roots)
*/
kvm_arch_flush_shadow(kvm);
kfree(old_memslots);
}
r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc);
if (r)
goto out_free;
/* map the pages in iommu page table */
if (npages) {
r = kvm_iommu_map_pages(kvm, &new);
if (r)
goto out_free;
}
r = -ENOMEM;
slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
GFP_KERNEL);
if (!slots)
goto out_free;
/* actual memory is freed via old in kvm_free_physmem_slot below */
if (!npages) {
new.rmap = NULL;
new.dirty_bitmap = NULL;
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i)
new.lpage_info[i] = NULL;
}
update_memslots(slots, &new);
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
kvm_arch_commit_memory_region(kvm, mem, old, user_alloc);
/*
* If the new memory slot is created, we need to clear all
* mmio sptes.
*/
if (npages && old.base_gfn != mem->guest_phys_addr >> PAGE_SHIFT)
kvm_arch_flush_shadow(kvm);
kvm_free_physmem_slot(&old, &new);
kfree(old_memslots);
return 0;
out_free:
kvm_free_physmem_slot(&new, &old);
out:
return r;
}
Commit Message: KVM: unmap pages from the iommu when slots are removed
commit 32f6daad4651a748a58a3ab6da0611862175722f upstream.
We've been adding new mappings, but not destroying old mappings.
This can lead to a page leak as pages are pinned using
get_user_pages, but only unpinned with put_page if they still
exist in the memslots list on vm shutdown. A memslot that is
destroyed while an iommu domain is enabled for the guest will
therefore result in an elevated page reference count that is
never cleared.
Additionally, without this fix, the iommu is only programmed
with the first translation for a gpa. This can result in
peer-to-peer errors if a mapping is destroyed and replaced by a
new mapping at the same gpa as the iommu will still be pointing
to the original, pinned memory address.
Signed-off-by: Alex Williamson <[email protected]>
Signed-off-by: Marcelo Tosatti <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-264
|
int __kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem,
int user_alloc)
{
int r;
gfn_t base_gfn;
unsigned long npages;
unsigned long i;
struct kvm_memory_slot *memslot;
struct kvm_memory_slot old, new;
struct kvm_memslots *slots, *old_memslots;
r = -EINVAL;
/* General sanity checks */
if (mem->memory_size & (PAGE_SIZE - 1))
goto out;
if (mem->guest_phys_addr & (PAGE_SIZE - 1))
goto out;
/* We can read the guest memory with __xxx_user() later on. */
if (user_alloc &&
((mem->userspace_addr & (PAGE_SIZE - 1)) ||
!access_ok(VERIFY_WRITE,
(void __user *)(unsigned long)mem->userspace_addr,
mem->memory_size)))
goto out;
if (mem->slot >= KVM_MEM_SLOTS_NUM)
goto out;
if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
goto out;
memslot = id_to_memslot(kvm->memslots, mem->slot);
base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
npages = mem->memory_size >> PAGE_SHIFT;
r = -EINVAL;
if (npages > KVM_MEM_MAX_NR_PAGES)
goto out;
if (!npages)
mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
new = old = *memslot;
new.id = mem->slot;
new.base_gfn = base_gfn;
new.npages = npages;
new.flags = mem->flags;
/* Disallow changing a memory slot's size. */
r = -EINVAL;
if (npages && old.npages && npages != old.npages)
goto out_free;
/* Check for overlaps */
r = -EEXIST;
for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
struct kvm_memory_slot *s = &kvm->memslots->memslots[i];
if (s == memslot || !s->npages)
continue;
if (!((base_gfn + npages <= s->base_gfn) ||
(base_gfn >= s->base_gfn + s->npages)))
goto out_free;
}
/* Free page dirty bitmap if unneeded */
if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
new.dirty_bitmap = NULL;
r = -ENOMEM;
/* Allocate if a slot is being created */
#ifndef CONFIG_S390
if (npages && !new.rmap) {
new.rmap = vzalloc(npages * sizeof(*new.rmap));
if (!new.rmap)
goto out_free;
new.user_alloc = user_alloc;
new.userspace_addr = mem->userspace_addr;
}
if (!npages)
goto skip_lpage;
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) {
unsigned long ugfn;
unsigned long j;
int lpages;
int level = i + 2;
/* Avoid unused variable warning if no large pages */
(void)level;
if (new.lpage_info[i])
continue;
lpages = 1 + ((base_gfn + npages - 1)
>> KVM_HPAGE_GFN_SHIFT(level));
lpages -= base_gfn >> KVM_HPAGE_GFN_SHIFT(level);
new.lpage_info[i] = vzalloc(lpages * sizeof(*new.lpage_info[i]));
if (!new.lpage_info[i])
goto out_free;
if (base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
new.lpage_info[i][0].write_count = 1;
if ((base_gfn+npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
new.lpage_info[i][lpages - 1].write_count = 1;
ugfn = new.userspace_addr >> PAGE_SHIFT;
/*
* If the gfn and userspace address are not aligned wrt each
* other, or if explicitly asked to, disable large page
* support for this slot
*/
if ((base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
!largepages_enabled)
for (j = 0; j < lpages; ++j)
new.lpage_info[i][j].write_count = 1;
}
skip_lpage:
/* Allocate page dirty bitmap if needed */
if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
if (kvm_create_dirty_bitmap(&new) < 0)
goto out_free;
/* destroy any largepage mappings for dirty tracking */
}
#else /* not defined CONFIG_S390 */
new.user_alloc = user_alloc;
if (user_alloc)
new.userspace_addr = mem->userspace_addr;
#endif /* not defined CONFIG_S390 */
if (!npages) {
struct kvm_memory_slot *slot;
r = -ENOMEM;
slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
GFP_KERNEL);
if (!slots)
goto out_free;
slot = id_to_memslot(slots, mem->slot);
slot->flags |= KVM_MEMSLOT_INVALID;
update_memslots(slots, NULL);
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
/* From this point no new shadow pages pointing to a deleted
* memslot will be created.
*
* validation of sp->gfn happens in:
* - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
* - kvm_is_visible_gfn (mmu_check_roots)
*/
kvm_arch_flush_shadow(kvm);
kfree(old_memslots);
}
r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc);
if (r)
goto out_free;
/* map/unmap the pages in iommu page table */
if (npages) {
r = kvm_iommu_map_pages(kvm, &new);
if (r)
goto out_free;
} else
kvm_iommu_unmap_pages(kvm, &old);
r = -ENOMEM;
slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
GFP_KERNEL);
if (!slots)
goto out_free;
/* actual memory is freed via old in kvm_free_physmem_slot below */
if (!npages) {
new.rmap = NULL;
new.dirty_bitmap = NULL;
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i)
new.lpage_info[i] = NULL;
}
update_memslots(slots, &new);
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
kvm_arch_commit_memory_region(kvm, mem, old, user_alloc);
/*
* If the new memory slot is created, we need to clear all
* mmio sptes.
*/
if (npages && old.base_gfn != mem->guest_phys_addr >> PAGE_SHIFT)
kvm_arch_flush_shadow(kvm);
kvm_free_physmem_slot(&old, &new);
kfree(old_memslots);
return 0;
out_free:
kvm_free_physmem_slot(&new, &old);
out:
return r;
}
| 165,618 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
size_t mincodes, size_t numcodes, unsigned maxbitlen)
{
unsigned error = 0;
while(!frequencies[numcodes - 1] && numcodes > mincodes) numcodes--; /*trim zeroes*/
tree->maxbitlen = maxbitlen;
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
tree->lengths = (unsigned*)realloc(tree->lengths, numcodes * sizeof(unsigned));
if(!tree->lengths) return 83; /*alloc fail*/
/*initialize all lengths to 0*/
memset(tree->lengths, 0, numcodes * sizeof(unsigned));
error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
if(!error) error = HuffmanTree_makeFromLengths2(tree);
return error;
}
Commit Message: Fixed #5645: realloc return handling
CWE ID: CWE-772
|
static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
size_t mincodes, size_t numcodes, unsigned maxbitlen)
{
unsigned* lengths;
unsigned error = 0;
while(!frequencies[numcodes - 1] && numcodes > mincodes) numcodes--; /*trim zeroes*/
tree->maxbitlen = maxbitlen;
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
lengths = (unsigned*)realloc(tree->lengths, numcodes * sizeof(unsigned));
if (!lengths)
free(tree->lengths);
tree->lengths = lengths;
if(!tree->lengths) return 83; /*alloc fail*/
/*initialize all lengths to 0*/
memset(tree->lengths, 0, numcodes * sizeof(unsigned));
error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
if(!error) error = HuffmanTree_makeFromLengths2(tree);
return error;
}
| 169,499 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_p_b_slice(dec_state_t *ps_dec)
{
WORD16 *pi2_vld_out;
UWORD32 i;
yuv_buf_t *ps_cur_frm_buf = &ps_dec->s_cur_frm_buf;
UWORD32 u4_frm_offset = 0;
const dec_mb_params_t *ps_dec_mb_params;
IMPEG2D_ERROR_CODES_T e_error = (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
pi2_vld_out = ps_dec->ai2_vld_buf;
memset(ps_dec->ai2_pred_mv,0,sizeof(ps_dec->ai2_pred_mv));
ps_dec->u2_prev_intra_mb = 0;
ps_dec->u2_first_mb = 1;
ps_dec->u2_picture_width = ps_dec->u2_frame_width;
if(ps_dec->u2_picture_structure != FRAME_PICTURE)
{
ps_dec->u2_picture_width <<= 1;
if(ps_dec->u2_picture_structure == BOTTOM_FIELD)
{
u4_frm_offset = ps_dec->u2_frame_width;
}
}
do
{
UWORD32 u4_x_offset, u4_y_offset;
UWORD32 u4_x_dst_offset = 0;
UWORD32 u4_y_dst_offset = 0;
UWORD8 *pu1_out_p;
UWORD8 *pu1_pred;
WORD32 u4_pred_strd;
IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y);
if(ps_dec->e_pic_type == B_PIC)
impeg2d_dec_pnb_mb_params(ps_dec);
else
impeg2d_dec_p_mb_params(ps_dec);
IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y);
u4_x_dst_offset = u4_frm_offset + (ps_dec->u2_mb_x << 4);
u4_y_dst_offset = (ps_dec->u2_mb_y << 4) * ps_dec->u2_picture_width;
pu1_out_p = ps_cur_frm_buf->pu1_y + u4_x_dst_offset + u4_y_dst_offset;
if(ps_dec->u2_prev_intra_mb == 0)
{
UWORD32 offset_x, offset_y, stride;
UWORD16 index = (ps_dec->u2_motion_type);
/*only for non intra mb's*/
if(ps_dec->e_mb_pred == BIDIRECT)
{
ps_dec_mb_params = &ps_dec->ps_func_bi_direct[index];
}
else
{
ps_dec_mb_params = &ps_dec->ps_func_forw_or_back[index];
}
stride = ps_dec->u2_picture_width;
offset_x = u4_frm_offset + (ps_dec->u2_mb_x << 4);
offset_y = (ps_dec->u2_mb_y << 4);
ps_dec->s_dest_buf.pu1_y = ps_cur_frm_buf->pu1_y + offset_y * stride + offset_x;
stride = stride >> 1;
ps_dec->s_dest_buf.pu1_u = ps_cur_frm_buf->pu1_u + (offset_y >> 1) * stride
+ (offset_x >> 1);
ps_dec->s_dest_buf.pu1_v = ps_cur_frm_buf->pu1_v + (offset_y >> 1) * stride
+ (offset_x >> 1);
PROFILE_DISABLE_MC_IF0
ps_dec_mb_params->pf_mc(ps_dec);
}
for(i = 0; i < NUM_LUMA_BLKS; ++i)
{
if((ps_dec->u2_cbp & (1 << (BLOCKS_IN_MB - 1 - i))) != 0)
{
e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix,
ps_dec->u2_prev_intra_mb, Y_LUMA, 0);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
return e_error;
}
u4_x_offset = gai2_impeg2_blk_x_off[i];
if(ps_dec->u2_field_dct == 0)
u4_y_offset = gai2_impeg2_blk_y_off_frm[i] ;
else
u4_y_offset = gai2_impeg2_blk_y_off_fld[i] ;
IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows);
PROFILE_DISABLE_IDCT_IF0
{
WORD32 idx;
if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows))
idx = 0;
else
idx = 1;
if(0 == ps_dec->u2_prev_intra_mb)
{
pu1_pred = pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset;
u4_pred_strd = ps_dec->u2_picture_width << ps_dec->u2_field_dct;
}
else
{
pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf;
u4_pred_strd = 8;
}
ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out,
ps_dec->ai2_idct_stg1,
pu1_pred,
pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset,
8,
u4_pred_strd,
ps_dec->u2_picture_width << ps_dec->u2_field_dct,
~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows);
}
}
}
/* For U and V blocks, divide the x and y offsets by 2. */
u4_x_dst_offset >>= 1;
u4_y_dst_offset >>= 2;
/* In case of chrominance blocks the DCT will be frame DCT */
/* i = 0, U component and i = 1 is V componet */
if((ps_dec->u2_cbp & 0x02) != 0)
{
pu1_out_p = ps_cur_frm_buf->pu1_u + u4_x_dst_offset + u4_y_dst_offset;
e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix,
ps_dec->u2_prev_intra_mb, U_CHROMA, 0);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
return e_error;
}
IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows);
PROFILE_DISABLE_IDCT_IF0
{
WORD32 idx;
if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows))
idx = 0;
else
idx = 1;
if(0 == ps_dec->u2_prev_intra_mb)
{
pu1_pred = pu1_out_p;
u4_pred_strd = ps_dec->u2_picture_width >> 1;
}
else
{
pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf;
u4_pred_strd = 8;
}
ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out,
ps_dec->ai2_idct_stg1,
pu1_pred,
pu1_out_p,
8,
u4_pred_strd,
ps_dec->u2_picture_width >> 1,
~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows);
}
}
if((ps_dec->u2_cbp & 0x01) != 0)
{
pu1_out_p = ps_cur_frm_buf->pu1_v + u4_x_dst_offset + u4_y_dst_offset;
e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix,
ps_dec->u2_prev_intra_mb, V_CHROMA, 0);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
return e_error;
}
IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows);
PROFILE_DISABLE_IDCT_IF0
{
WORD32 idx;
if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows))
idx = 0;
else
idx = 1;
if(0 == ps_dec->u2_prev_intra_mb)
{
pu1_pred = pu1_out_p;
u4_pred_strd = ps_dec->u2_picture_width >> 1;
}
else
{
pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf;
u4_pred_strd = 8;
}
ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out,
ps_dec->ai2_idct_stg1,
pu1_pred,
pu1_out_p,
8,
u4_pred_strd,
ps_dec->u2_picture_width >> 1,
~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows);
}
}
ps_dec->u2_num_mbs_left--;
ps_dec->u2_first_mb = 0;
ps_dec->u2_mb_x++;
if(ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset)
{
return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR;
}
else if (ps_dec->u2_mb_x == ps_dec->u2_num_horiz_mb)
{
ps_dec->u2_mb_x = 0;
ps_dec->u2_mb_y++;
}
}
while(ps_dec->u2_num_mbs_left != 0 && impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,23) != 0x0);
return e_error;
}
Commit Message: Return error for wrong mb_type
If mb_type decoded returns an invalid type of MB, then return error
Bug: 26070014
Change-Id: I66abcad5de1352dd42d05b1a13bb4176153b133c
CWE ID: CWE-119
|
IMPEG2D_ERROR_CODES_T impeg2d_dec_p_b_slice(dec_state_t *ps_dec)
{
WORD16 *pi2_vld_out;
UWORD32 i;
yuv_buf_t *ps_cur_frm_buf = &ps_dec->s_cur_frm_buf;
UWORD32 u4_frm_offset = 0;
const dec_mb_params_t *ps_dec_mb_params;
IMPEG2D_ERROR_CODES_T e_error = (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
pi2_vld_out = ps_dec->ai2_vld_buf;
memset(ps_dec->ai2_pred_mv,0,sizeof(ps_dec->ai2_pred_mv));
ps_dec->u2_prev_intra_mb = 0;
ps_dec->u2_first_mb = 1;
ps_dec->u2_picture_width = ps_dec->u2_frame_width;
if(ps_dec->u2_picture_structure != FRAME_PICTURE)
{
ps_dec->u2_picture_width <<= 1;
if(ps_dec->u2_picture_structure == BOTTOM_FIELD)
{
u4_frm_offset = ps_dec->u2_frame_width;
}
}
do
{
UWORD32 u4_x_offset, u4_y_offset;
WORD32 ret;
UWORD32 u4_x_dst_offset = 0;
UWORD32 u4_y_dst_offset = 0;
UWORD8 *pu1_out_p;
UWORD8 *pu1_pred;
WORD32 u4_pred_strd;
IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y);
if(ps_dec->e_pic_type == B_PIC)
ret = impeg2d_dec_pnb_mb_params(ps_dec);
else
ret = impeg2d_dec_p_mb_params(ps_dec);
if(ret)
return IMPEG2D_MB_TEX_DECODE_ERR;
IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y);
u4_x_dst_offset = u4_frm_offset + (ps_dec->u2_mb_x << 4);
u4_y_dst_offset = (ps_dec->u2_mb_y << 4) * ps_dec->u2_picture_width;
pu1_out_p = ps_cur_frm_buf->pu1_y + u4_x_dst_offset + u4_y_dst_offset;
if(ps_dec->u2_prev_intra_mb == 0)
{
UWORD32 offset_x, offset_y, stride;
UWORD16 index = (ps_dec->u2_motion_type);
/*only for non intra mb's*/
if(ps_dec->e_mb_pred == BIDIRECT)
{
ps_dec_mb_params = &ps_dec->ps_func_bi_direct[index];
}
else
{
ps_dec_mb_params = &ps_dec->ps_func_forw_or_back[index];
}
stride = ps_dec->u2_picture_width;
offset_x = u4_frm_offset + (ps_dec->u2_mb_x << 4);
offset_y = (ps_dec->u2_mb_y << 4);
ps_dec->s_dest_buf.pu1_y = ps_cur_frm_buf->pu1_y + offset_y * stride + offset_x;
stride = stride >> 1;
ps_dec->s_dest_buf.pu1_u = ps_cur_frm_buf->pu1_u + (offset_y >> 1) * stride
+ (offset_x >> 1);
ps_dec->s_dest_buf.pu1_v = ps_cur_frm_buf->pu1_v + (offset_y >> 1) * stride
+ (offset_x >> 1);
PROFILE_DISABLE_MC_IF0
ps_dec_mb_params->pf_mc(ps_dec);
}
for(i = 0; i < NUM_LUMA_BLKS; ++i)
{
if((ps_dec->u2_cbp & (1 << (BLOCKS_IN_MB - 1 - i))) != 0)
{
e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix,
ps_dec->u2_prev_intra_mb, Y_LUMA, 0);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
return e_error;
}
u4_x_offset = gai2_impeg2_blk_x_off[i];
if(ps_dec->u2_field_dct == 0)
u4_y_offset = gai2_impeg2_blk_y_off_frm[i] ;
else
u4_y_offset = gai2_impeg2_blk_y_off_fld[i] ;
IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows);
PROFILE_DISABLE_IDCT_IF0
{
WORD32 idx;
if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows))
idx = 0;
else
idx = 1;
if(0 == ps_dec->u2_prev_intra_mb)
{
pu1_pred = pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset;
u4_pred_strd = ps_dec->u2_picture_width << ps_dec->u2_field_dct;
}
else
{
pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf;
u4_pred_strd = 8;
}
ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out,
ps_dec->ai2_idct_stg1,
pu1_pred,
pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset,
8,
u4_pred_strd,
ps_dec->u2_picture_width << ps_dec->u2_field_dct,
~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows);
}
}
}
/* For U and V blocks, divide the x and y offsets by 2. */
u4_x_dst_offset >>= 1;
u4_y_dst_offset >>= 2;
/* In case of chrominance blocks the DCT will be frame DCT */
/* i = 0, U component and i = 1 is V componet */
if((ps_dec->u2_cbp & 0x02) != 0)
{
pu1_out_p = ps_cur_frm_buf->pu1_u + u4_x_dst_offset + u4_y_dst_offset;
e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix,
ps_dec->u2_prev_intra_mb, U_CHROMA, 0);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
return e_error;
}
IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows);
PROFILE_DISABLE_IDCT_IF0
{
WORD32 idx;
if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows))
idx = 0;
else
idx = 1;
if(0 == ps_dec->u2_prev_intra_mb)
{
pu1_pred = pu1_out_p;
u4_pred_strd = ps_dec->u2_picture_width >> 1;
}
else
{
pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf;
u4_pred_strd = 8;
}
ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out,
ps_dec->ai2_idct_stg1,
pu1_pred,
pu1_out_p,
8,
u4_pred_strd,
ps_dec->u2_picture_width >> 1,
~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows);
}
}
if((ps_dec->u2_cbp & 0x01) != 0)
{
pu1_out_p = ps_cur_frm_buf->pu1_v + u4_x_dst_offset + u4_y_dst_offset;
e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix,
ps_dec->u2_prev_intra_mb, V_CHROMA, 0);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
return e_error;
}
IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows);
PROFILE_DISABLE_IDCT_IF0
{
WORD32 idx;
if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows))
idx = 0;
else
idx = 1;
if(0 == ps_dec->u2_prev_intra_mb)
{
pu1_pred = pu1_out_p;
u4_pred_strd = ps_dec->u2_picture_width >> 1;
}
else
{
pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf;
u4_pred_strd = 8;
}
ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out,
ps_dec->ai2_idct_stg1,
pu1_pred,
pu1_out_p,
8,
u4_pred_strd,
ps_dec->u2_picture_width >> 1,
~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows);
}
}
ps_dec->u2_num_mbs_left--;
ps_dec->u2_first_mb = 0;
ps_dec->u2_mb_x++;
if(ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset)
{
return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR;
}
else if (ps_dec->u2_mb_x == ps_dec->u2_num_horiz_mb)
{
ps_dec->u2_mb_x = 0;
ps_dec->u2_mb_y++;
}
}
while(ps_dec->u2_num_mbs_left != 0 && impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,23) != 0x0);
return e_error;
}
| 174,608 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: int do_adjtimex(struct timex *txc)
{
long mtemp, save_adjust, rem;
s64 freq_adj;
int result;
/* In order to modify anything, you gotta be super-user! */
if (txc->modes && !capable(CAP_SYS_TIME))
return -EPERM;
/* Now we validate the data before disabling interrupts */
if ((txc->modes & ADJ_OFFSET_SINGLESHOT) == ADJ_OFFSET_SINGLESHOT) {
/* singleshot must not be used with any other mode bits */
if (txc->modes != ADJ_OFFSET_SINGLESHOT &&
txc->modes != ADJ_OFFSET_SS_READ)
return -EINVAL;
}
if (txc->modes != ADJ_OFFSET_SINGLESHOT && (txc->modes & ADJ_OFFSET))
/* adjustment Offset limited to +- .512 seconds */
if (txc->offset <= - MAXPHASE || txc->offset >= MAXPHASE )
return -EINVAL;
/* if the quartz is off by more than 10% something is VERY wrong ! */
if (txc->modes & ADJ_TICK)
if (txc->tick < 900000/USER_HZ ||
txc->tick > 1100000/USER_HZ)
return -EINVAL;
write_seqlock_irq(&xtime_lock);
result = time_state; /* mostly `TIME_OK' */
/* Save for later - semantics of adjtime is to return old value */
save_adjust = time_adjust;
#if 0 /* STA_CLOCKERR is never set yet */
time_status &= ~STA_CLOCKERR; /* reset STA_CLOCKERR */
#endif
/* If there are input parameters, then process them */
if (txc->modes)
{
if (txc->modes & ADJ_STATUS) /* only set allowed bits */
time_status = (txc->status & ~STA_RONLY) |
(time_status & STA_RONLY);
if (txc->modes & ADJ_FREQUENCY) { /* p. 22 */
if (txc->freq > MAXFREQ || txc->freq < -MAXFREQ) {
result = -EINVAL;
goto leave;
}
time_freq = ((s64)txc->freq * NSEC_PER_USEC)
>> (SHIFT_USEC - SHIFT_NSEC);
}
if (txc->modes & ADJ_MAXERROR) {
if (txc->maxerror < 0 || txc->maxerror >= NTP_PHASE_LIMIT) {
result = -EINVAL;
goto leave;
}
time_maxerror = txc->maxerror;
}
if (txc->modes & ADJ_ESTERROR) {
if (txc->esterror < 0 || txc->esterror >= NTP_PHASE_LIMIT) {
result = -EINVAL;
goto leave;
}
time_esterror = txc->esterror;
}
if (txc->modes & ADJ_TIMECONST) { /* p. 24 */
if (txc->constant < 0) { /* NTP v4 uses values > 6 */
result = -EINVAL;
goto leave;
}
time_constant = min(txc->constant + 4, (long)MAXTC);
}
if (txc->modes & ADJ_OFFSET) { /* values checked earlier */
if (txc->modes == ADJ_OFFSET_SINGLESHOT) {
/* adjtime() is independent from ntp_adjtime() */
time_adjust = txc->offset;
}
else if (time_status & STA_PLL) {
time_offset = txc->offset * NSEC_PER_USEC;
/*
* Scale the phase adjustment and
* clamp to the operating range.
*/
time_offset = min(time_offset, (s64)MAXPHASE * NSEC_PER_USEC);
time_offset = max(time_offset, (s64)-MAXPHASE * NSEC_PER_USEC);
/*
* Select whether the frequency is to be controlled
* and in which mode (PLL or FLL). Clamp to the operating
* range. Ugly multiply/divide should be replaced someday.
*/
if (time_status & STA_FREQHOLD || time_reftime == 0)
time_reftime = xtime.tv_sec;
mtemp = xtime.tv_sec - time_reftime;
time_reftime = xtime.tv_sec;
freq_adj = time_offset * mtemp;
freq_adj = shift_right(freq_adj, time_constant * 2 +
(SHIFT_PLL + 2) * 2 - SHIFT_NSEC);
if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp > MAXSEC))
freq_adj += div_s64(time_offset << (SHIFT_NSEC - SHIFT_FLL), mtemp);
freq_adj += time_freq;
freq_adj = min(freq_adj, (s64)MAXFREQ_NSEC);
time_freq = max(freq_adj, (s64)-MAXFREQ_NSEC);
time_offset = div_long_long_rem_signed(time_offset,
NTP_INTERVAL_FREQ,
&rem);
time_offset <<= SHIFT_UPDATE;
} /* STA_PLL */
} /* txc->modes & ADJ_OFFSET */
if (txc->modes & ADJ_TICK)
tick_usec = txc->tick;
if (txc->modes & (ADJ_TICK|ADJ_FREQUENCY|ADJ_OFFSET))
ntp_update_frequency();
} /* txc->modes */
leave: if ((time_status & (STA_UNSYNC|STA_CLOCKERR)) != 0)
result = TIME_ERROR;
if ((txc->modes == ADJ_OFFSET_SINGLESHOT) ||
(txc->modes == ADJ_OFFSET_SS_READ))
txc->offset = save_adjust;
else
txc->offset = ((long)shift_right(time_offset, SHIFT_UPDATE)) *
NTP_INTERVAL_FREQ / 1000;
txc->freq = (time_freq / NSEC_PER_USEC) <<
(SHIFT_USEC - SHIFT_NSEC);
txc->maxerror = time_maxerror;
txc->esterror = time_esterror;
txc->status = time_status;
txc->constant = time_constant;
txc->precision = 1;
txc->tolerance = MAXFREQ;
txc->tick = tick_usec;
/* PPS is not implemented, so these are zero */
txc->ppsfreq = 0;
txc->jitter = 0;
txc->shift = 0;
txc->stabil = 0;
txc->jitcnt = 0;
txc->calcnt = 0;
txc->errcnt = 0;
txc->stbcnt = 0;
write_sequnlock_irq(&xtime_lock);
do_gettimeofday(&txc->time);
notify_cmos_timer();
return(result);
}
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
|
int do_adjtimex(struct timex *txc)
{
long mtemp, save_adjust;
s64 freq_adj;
int result;
/* In order to modify anything, you gotta be super-user! */
if (txc->modes && !capable(CAP_SYS_TIME))
return -EPERM;
/* Now we validate the data before disabling interrupts */
if ((txc->modes & ADJ_OFFSET_SINGLESHOT) == ADJ_OFFSET_SINGLESHOT) {
/* singleshot must not be used with any other mode bits */
if (txc->modes != ADJ_OFFSET_SINGLESHOT &&
txc->modes != ADJ_OFFSET_SS_READ)
return -EINVAL;
}
if (txc->modes != ADJ_OFFSET_SINGLESHOT && (txc->modes & ADJ_OFFSET))
/* adjustment Offset limited to +- .512 seconds */
if (txc->offset <= - MAXPHASE || txc->offset >= MAXPHASE )
return -EINVAL;
/* if the quartz is off by more than 10% something is VERY wrong ! */
if (txc->modes & ADJ_TICK)
if (txc->tick < 900000/USER_HZ ||
txc->tick > 1100000/USER_HZ)
return -EINVAL;
write_seqlock_irq(&xtime_lock);
result = time_state; /* mostly `TIME_OK' */
/* Save for later - semantics of adjtime is to return old value */
save_adjust = time_adjust;
#if 0 /* STA_CLOCKERR is never set yet */
time_status &= ~STA_CLOCKERR; /* reset STA_CLOCKERR */
#endif
/* If there are input parameters, then process them */
if (txc->modes)
{
if (txc->modes & ADJ_STATUS) /* only set allowed bits */
time_status = (txc->status & ~STA_RONLY) |
(time_status & STA_RONLY);
if (txc->modes & ADJ_FREQUENCY) { /* p. 22 */
if (txc->freq > MAXFREQ || txc->freq < -MAXFREQ) {
result = -EINVAL;
goto leave;
}
time_freq = ((s64)txc->freq * NSEC_PER_USEC)
>> (SHIFT_USEC - SHIFT_NSEC);
}
if (txc->modes & ADJ_MAXERROR) {
if (txc->maxerror < 0 || txc->maxerror >= NTP_PHASE_LIMIT) {
result = -EINVAL;
goto leave;
}
time_maxerror = txc->maxerror;
}
if (txc->modes & ADJ_ESTERROR) {
if (txc->esterror < 0 || txc->esterror >= NTP_PHASE_LIMIT) {
result = -EINVAL;
goto leave;
}
time_esterror = txc->esterror;
}
if (txc->modes & ADJ_TIMECONST) { /* p. 24 */
if (txc->constant < 0) { /* NTP v4 uses values > 6 */
result = -EINVAL;
goto leave;
}
time_constant = min(txc->constant + 4, (long)MAXTC);
}
if (txc->modes & ADJ_OFFSET) { /* values checked earlier */
if (txc->modes == ADJ_OFFSET_SINGLESHOT) {
/* adjtime() is independent from ntp_adjtime() */
time_adjust = txc->offset;
}
else if (time_status & STA_PLL) {
time_offset = txc->offset * NSEC_PER_USEC;
/*
* Scale the phase adjustment and
* clamp to the operating range.
*/
time_offset = min(time_offset, (s64)MAXPHASE * NSEC_PER_USEC);
time_offset = max(time_offset, (s64)-MAXPHASE * NSEC_PER_USEC);
/*
* Select whether the frequency is to be controlled
* and in which mode (PLL or FLL). Clamp to the operating
* range. Ugly multiply/divide should be replaced someday.
*/
if (time_status & STA_FREQHOLD || time_reftime == 0)
time_reftime = xtime.tv_sec;
mtemp = xtime.tv_sec - time_reftime;
time_reftime = xtime.tv_sec;
freq_adj = time_offset * mtemp;
freq_adj = shift_right(freq_adj, time_constant * 2 +
(SHIFT_PLL + 2) * 2 - SHIFT_NSEC);
if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp > MAXSEC))
freq_adj += div_s64(time_offset << (SHIFT_NSEC - SHIFT_FLL), mtemp);
freq_adj += time_freq;
freq_adj = min(freq_adj, (s64)MAXFREQ_NSEC);
time_freq = max(freq_adj, (s64)-MAXFREQ_NSEC);
time_offset = div_s64(time_offset, NTP_INTERVAL_FREQ);
time_offset <<= SHIFT_UPDATE;
} /* STA_PLL */
} /* txc->modes & ADJ_OFFSET */
if (txc->modes & ADJ_TICK)
tick_usec = txc->tick;
if (txc->modes & (ADJ_TICK|ADJ_FREQUENCY|ADJ_OFFSET))
ntp_update_frequency();
} /* txc->modes */
leave: if ((time_status & (STA_UNSYNC|STA_CLOCKERR)) != 0)
result = TIME_ERROR;
if ((txc->modes == ADJ_OFFSET_SINGLESHOT) ||
(txc->modes == ADJ_OFFSET_SS_READ))
txc->offset = save_adjust;
else
txc->offset = ((long)shift_right(time_offset, SHIFT_UPDATE)) *
NTP_INTERVAL_FREQ / 1000;
txc->freq = (time_freq / NSEC_PER_USEC) <<
(SHIFT_USEC - SHIFT_NSEC);
txc->maxerror = time_maxerror;
txc->esterror = time_esterror;
txc->status = time_status;
txc->constant = time_constant;
txc->precision = 1;
txc->tolerance = MAXFREQ;
txc->tick = tick_usec;
/* PPS is not implemented, so these are zero */
txc->ppsfreq = 0;
txc->jitter = 0;
txc->shift = 0;
txc->stabil = 0;
txc->jitcnt = 0;
txc->calcnt = 0;
txc->errcnt = 0;
txc->stbcnt = 0;
write_sequnlock_irq(&xtime_lock);
do_gettimeofday(&txc->time);
notify_cmos_timer();
return(result);
}
| 165,757 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: WorkerProcessLauncherTest::WorkerProcessLauncherTest()
: message_loop_(MessageLoop::TYPE_IO) {
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
WorkerProcessLauncherTest::WorkerProcessLauncherTest()
: message_loop_(MessageLoop::TYPE_IO),
client_pid_(GetCurrentProcessId()),
permanent_error_(false) {
}
| 171,553 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static Image *ReadWPGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
typedef struct
{
size_t FileId;
MagickOffsetType DataOffset;
unsigned int ProductType;
unsigned int FileType;
unsigned char MajorVersion;
unsigned char MinorVersion;
unsigned int EncryptKey;
unsigned int Reserved;
} WPGHeader;
typedef struct
{
unsigned char RecType;
size_t RecordLength;
} WPGRecord;
typedef struct
{
unsigned char Class;
unsigned char RecType;
size_t Extension;
size_t RecordLength;
} WPG2Record;
typedef struct
{
unsigned HorizontalUnits;
unsigned VerticalUnits;
unsigned char PosSizePrecision;
} WPG2Start;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType1;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned char Depth;
unsigned char Compression;
} WPG2BitmapType1;
typedef struct
{
unsigned int RotAngle;
unsigned int LowLeftX;
unsigned int LowLeftY;
unsigned int UpRightX;
unsigned int UpRightY;
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType2;
typedef struct
{
unsigned int StartIndex;
unsigned int NumOfEntries;
} WPGColorMapRec;
/*
typedef struct {
size_t PS_unknown1;
unsigned int PS_unknown2;
unsigned int PS_unknown3;
} WPGPSl1Record;
*/
Image
*image;
unsigned int
status;
WPGHeader
Header;
WPGRecord
Rec;
WPG2Record
Rec2;
WPG2Start StartWPG;
WPGBitmapType1
BitmapHeader1;
WPG2BitmapType1
Bitmap2Header1;
WPGBitmapType2
BitmapHeader2;
WPGColorMapRec
WPG_Palette;
int
i,
bpp,
WPG2Flags;
ssize_t
ldblk;
size_t
one;
unsigned char
*BImgBuff;
tCTM CTM; /*current transform matrix*/
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
one=1;
image=AcquireImage(image_info,exception);
image->depth=8;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read WPG image.
*/
Header.FileId=ReadBlobLSBLong(image);
Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image);
Header.ProductType=ReadBlobLSBShort(image);
Header.FileType=ReadBlobLSBShort(image);
Header.MajorVersion=ReadBlobByte(image);
Header.MinorVersion=ReadBlobByte(image);
Header.EncryptKey=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (Header.EncryptKey!=0)
ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported");
image->columns = 1;
image->rows = 1;
image->colors = 0;
bpp=0;
BitmapHeader2.RotAngle=0;
switch(Header.FileType)
{
case 1: /* WPG level 1 */
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec.RecordLength;
switch(Rec.RecType)
{
case 0x0B: /* bitmap type 1 */
BitmapHeader1.Width=ReadBlobLSBShort(image);
BitmapHeader1.Height=ReadBlobLSBShort(image);
if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader1.Depth=ReadBlobLSBShort(image);
BitmapHeader1.HorzRes=ReadBlobLSBShort(image);
BitmapHeader1.VertRes=ReadBlobLSBShort(image);
if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes)
{
image->units=PixelsPerCentimeterResolution;
image->resolution.x=BitmapHeader1.HorzRes/470.0;
image->resolution.y=BitmapHeader1.VertRes/470.0;
}
image->columns=BitmapHeader1.Width;
image->rows=BitmapHeader1.Height;
bpp=BitmapHeader1.Depth;
goto UnpackRaster;
case 0x0E: /*Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
}
break;
case 0x11: /* Start PS l1 */
if(Rec.RecordLength > 8)
image=ExtractPostscript(image,image_info,
TellBlob(image)+8, /* skip PS header in the wpg */
(ssize_t) Rec.RecordLength-8,exception);
break;
case 0x14: /* bitmap type 2 */
BitmapHeader2.RotAngle=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftX=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftY=ReadBlobLSBShort(image);
BitmapHeader2.UpRightX=ReadBlobLSBShort(image);
BitmapHeader2.UpRightY=ReadBlobLSBShort(image);
BitmapHeader2.Width=ReadBlobLSBShort(image);
BitmapHeader2.Height=ReadBlobLSBShort(image);
if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader2.Depth=ReadBlobLSBShort(image);
BitmapHeader2.HorzRes=ReadBlobLSBShort(image);
BitmapHeader2.VertRes=ReadBlobLSBShort(image);
image->units=PixelsPerCentimeterResolution;
image->page.width=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0);
image->page.height=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0);
image->page.x=(int) (BitmapHeader2.LowLeftX/470.0);
image->page.y=(int) (BitmapHeader2.LowLeftX/470.0);
if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes)
{
image->resolution.x=BitmapHeader2.HorzRes/470.0;
image->resolution.y=BitmapHeader2.VertRes/470.0;
}
image->columns=BitmapHeader2.Width;
image->rows=BitmapHeader2.Height;
bpp=BitmapHeader2.Depth;
UnpackRaster:
if ((image->colors == 0) && (bpp != 24))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
{
NoMemory:
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
/* printf("Load default colormap \n"); */
for (i=0; (i < (int) image->colors) && (i < 256); i++)
{
image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red);
image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green);
image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue);
}
}
else
{
if (bpp < 24)
if ( (image->colors < (one << bpp)) && (bpp != 24) )
image->colormap=(PixelInfo *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
if (bpp == 1)
{
if(image->colormap[0].red==0 &&
image->colormap[0].green==0 &&
image->colormap[0].blue==0 &&
image->colormap[1].red==0 &&
image->colormap[1].green==0 &&
image->colormap[1].blue==0)
{ /* fix crippled monochrome palette */
image->colormap[1].red =
image->colormap[1].green =
image->colormap[1].blue = QuantumRange;
}
}
if(UnpackWPGRaster(image,bpp,exception) < 0)
/* The raster cannot be unpacked */
{
DecompressionFailed:
ThrowReaderException(CoderError,"UnableToDecompressImage");
}
if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping)
{
/* flop command */
if(BitmapHeader2.RotAngle & 0x8000)
{
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
}
/* flip command */
if(BitmapHeader2.RotAngle & 0x2000)
{
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
}
/* rotate command */
if(BitmapHeader2.RotAngle & 0x0FFF)
{
Image
*rotate_image;
rotate_image=RotateImage(image,(BitmapHeader2.RotAngle &
0x0FFF), exception);
if (rotate_image != (Image *) NULL) {
DuplicateBlob(rotate_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,rotate_image);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
break;
case 0x1B: /* Postscript l2 */
if(Rec.RecordLength>0x3C)
image=ExtractPostscript(image,image_info,
TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */
(ssize_t) Rec.RecordLength-0x3C,exception);
break;
}
}
break;
case 2: /* WPG level 2 */
(void) memset(CTM,0,sizeof(CTM));
StartWPG.PosSizePrecision = 0;
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec2.Class=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rec2.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec2.Extension);
Rd_WP_DWORD(image,&Rec2.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec2.RecordLength;
switch(Rec2.RecType)
{
case 1:
StartWPG.HorizontalUnits=ReadBlobLSBShort(image);
StartWPG.VerticalUnits=ReadBlobLSBShort(image);
StartWPG.PosSizePrecision=ReadBlobByte(image);
break;
case 0x0C: /* Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((char)
ReadBlobByte(image));
(void) ReadBlobByte(image); /*Opacity??*/
}
break;
case 0x0E:
Bitmap2Header1.Width=ReadBlobLSBShort(image);
Bitmap2Header1.Height=ReadBlobLSBShort(image);
if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
Bitmap2Header1.Depth=ReadBlobByte(image);
Bitmap2Header1.Compression=ReadBlobByte(image);
if(Bitmap2Header1.Compression > 1)
continue; /*Unknown compression method */
switch(Bitmap2Header1.Depth)
{
case 1:
bpp=1;
break;
case 2:
bpp=2;
break;
case 3:
bpp=4;
break;
case 4:
bpp=8;
break;
case 8:
bpp=24;
break;
default:
continue; /*Ignore raster with unknown depth*/
}
image->columns=Bitmap2Header1.Width;
image->rows=Bitmap2Header1.Height;
if ((image->colors == 0) && (bpp != 24))
{
size_t
one;
one=1;
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
}
else
{
if(bpp < 24)
if( image->colors<(one << bpp) && bpp!=24 )
image->colormap=(PixelInfo *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
switch(Bitmap2Header1.Compression)
{
case 0: /*Uncompressed raster*/
{
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t)
ldblk,sizeof(*BImgBuff));
if (BImgBuff == (unsigned char *) NULL)
goto NoMemory;
for(i=0; i< (ssize_t) image->rows; i++)
{
(void) ReadBlob(image,ldblk,BImgBuff);
InsertRow(image,BImgBuff,i,bpp,exception);
}
if(BImgBuff)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);;
break;
}
case 1: /*RLE for WPG2 */
{
if( UnpackWPG2Raster(image,bpp,exception) < 0)
goto DecompressionFailed;
break;
}
}
if(CTM[0][0]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0;
Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll);
Tx(1,2)=0; Tx(2,2)=1; */
}
if(CTM[1][1]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
float_matrix Tx(3,3);
Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0;
Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll);
Tx(2,2)=1; */
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x12: /* Postscript WPG2*/
i=ReadBlobLSBShort(image);
if(Rec2.RecordLength > (unsigned int) i)
image=ExtractPostscript(image,image_info,
TellBlob(image)+i, /*skip PS header in the wpg2*/
(ssize_t) (Rec2.RecordLength-i-2),exception);
break;
case 0x1B: /*bitmap rectangle*/
WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM);
(void) WPG2Flags;
break;
}
}
break;
default:
{
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
}
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
Finish:
(void) CloseBlob(image);
{
Image
*p;
ssize_t
scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers.
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=(size_t) scene++;
}
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,
"ImageFileDoesNotContainAnyImageData");
return(image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/120
CWE ID: CWE-125
|
static Image *ReadWPGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
typedef struct
{
size_t FileId;
MagickOffsetType DataOffset;
unsigned int ProductType;
unsigned int FileType;
unsigned char MajorVersion;
unsigned char MinorVersion;
unsigned int EncryptKey;
unsigned int Reserved;
} WPGHeader;
typedef struct
{
unsigned char RecType;
size_t RecordLength;
} WPGRecord;
typedef struct
{
unsigned char Class;
unsigned char RecType;
size_t Extension;
size_t RecordLength;
} WPG2Record;
typedef struct
{
unsigned HorizontalUnits;
unsigned VerticalUnits;
unsigned char PosSizePrecision;
} WPG2Start;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType1;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned char Depth;
unsigned char Compression;
} WPG2BitmapType1;
typedef struct
{
unsigned int RotAngle;
unsigned int LowLeftX;
unsigned int LowLeftY;
unsigned int UpRightX;
unsigned int UpRightY;
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType2;
typedef struct
{
unsigned int StartIndex;
unsigned int NumOfEntries;
} WPGColorMapRec;
/*
typedef struct {
size_t PS_unknown1;
unsigned int PS_unknown2;
unsigned int PS_unknown3;
} WPGPSl1Record;
*/
Image
*image;
unsigned int
status;
WPGHeader
Header;
WPGRecord
Rec;
WPG2Record
Rec2;
WPG2Start StartWPG;
WPGBitmapType1
BitmapHeader1;
WPG2BitmapType1
Bitmap2Header1;
WPGBitmapType2
BitmapHeader2;
WPGColorMapRec
WPG_Palette;
int
i,
bpp,
WPG2Flags;
ssize_t
ldblk;
size_t
one;
unsigned char
*BImgBuff;
tCTM CTM; /*current transform matrix*/
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
one=1;
image=AcquireImage(image_info,exception);
image->depth=8;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read WPG image.
*/
Header.FileId=ReadBlobLSBLong(image);
Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image);
Header.ProductType=ReadBlobLSBShort(image);
Header.FileType=ReadBlobLSBShort(image);
Header.MajorVersion=ReadBlobByte(image);
Header.MinorVersion=ReadBlobByte(image);
Header.EncryptKey=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (Header.EncryptKey!=0)
ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported");
image->columns = 1;
image->rows = 1;
image->colors = 0;
bpp=0;
BitmapHeader2.RotAngle=0;
switch(Header.FileType)
{
case 1: /* WPG level 1 */
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec.RecordLength;
switch(Rec.RecType)
{
case 0x0B: /* bitmap type 1 */
BitmapHeader1.Width=ReadBlobLSBShort(image);
BitmapHeader1.Height=ReadBlobLSBShort(image);
if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader1.Depth=ReadBlobLSBShort(image);
BitmapHeader1.HorzRes=ReadBlobLSBShort(image);
BitmapHeader1.VertRes=ReadBlobLSBShort(image);
if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes)
{
image->units=PixelsPerCentimeterResolution;
image->resolution.x=BitmapHeader1.HorzRes/470.0;
image->resolution.y=BitmapHeader1.VertRes/470.0;
}
image->columns=BitmapHeader1.Width;
image->rows=BitmapHeader1.Height;
bpp=BitmapHeader1.Depth;
goto UnpackRaster;
case 0x0E: /*Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
}
break;
case 0x11: /* Start PS l1 */
if(Rec.RecordLength > 8)
image=ExtractPostscript(image,image_info,
TellBlob(image)+8, /* skip PS header in the wpg */
(ssize_t) Rec.RecordLength-8,exception);
break;
case 0x14: /* bitmap type 2 */
BitmapHeader2.RotAngle=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftX=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftY=ReadBlobLSBShort(image);
BitmapHeader2.UpRightX=ReadBlobLSBShort(image);
BitmapHeader2.UpRightY=ReadBlobLSBShort(image);
BitmapHeader2.Width=ReadBlobLSBShort(image);
BitmapHeader2.Height=ReadBlobLSBShort(image);
if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader2.Depth=ReadBlobLSBShort(image);
BitmapHeader2.HorzRes=ReadBlobLSBShort(image);
BitmapHeader2.VertRes=ReadBlobLSBShort(image);
image->units=PixelsPerCentimeterResolution;
image->page.width=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0);
image->page.height=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0);
image->page.x=(int) (BitmapHeader2.LowLeftX/470.0);
image->page.y=(int) (BitmapHeader2.LowLeftX/470.0);
if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes)
{
image->resolution.x=BitmapHeader2.HorzRes/470.0;
image->resolution.y=BitmapHeader2.VertRes/470.0;
}
image->columns=BitmapHeader2.Width;
image->rows=BitmapHeader2.Height;
bpp=BitmapHeader2.Depth;
UnpackRaster:
if ((image->colors == 0) && (bpp != 24))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
{
NoMemory:
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
/* printf("Load default colormap \n"); */
for (i=0; (i < (int) image->colors) && (i < 256); i++)
{
image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red);
image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green);
image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue);
}
}
else
{
if (bpp < 24)
if ( (image->colors < (one << bpp)) && (bpp != 24) )
image->colormap=(PixelInfo *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
if (bpp == 1)
{
if(image->colormap[0].red==0 &&
image->colormap[0].green==0 &&
image->colormap[0].blue==0 &&
image->colormap[1].red==0 &&
image->colormap[1].green==0 &&
image->colormap[1].blue==0)
{ /* fix crippled monochrome palette */
image->colormap[1].red =
image->colormap[1].green =
image->colormap[1].blue = QuantumRange;
}
}
if(UnpackWPGRaster(image,bpp,exception) < 0)
/* The raster cannot be unpacked */
{
DecompressionFailed:
ThrowReaderException(CoderError,"UnableToDecompressImage");
}
if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping)
{
/* flop command */
if(BitmapHeader2.RotAngle & 0x8000)
{
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
}
/* flip command */
if(BitmapHeader2.RotAngle & 0x2000)
{
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
}
/* rotate command */
if(BitmapHeader2.RotAngle & 0x0FFF)
{
Image
*rotate_image;
rotate_image=RotateImage(image,(BitmapHeader2.RotAngle &
0x0FFF), exception);
if (rotate_image != (Image *) NULL) {
DuplicateBlob(rotate_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,rotate_image);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
break;
case 0x1B: /* Postscript l2 */
if(Rec.RecordLength>0x3C)
image=ExtractPostscript(image,image_info,
TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */
(ssize_t) Rec.RecordLength-0x3C,exception);
break;
}
}
break;
case 2: /* WPG level 2 */
(void) memset(CTM,0,sizeof(CTM));
StartWPG.PosSizePrecision = 0;
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec2.Class=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rec2.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec2.Extension);
Rd_WP_DWORD(image,&Rec2.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec2.RecordLength;
switch(Rec2.RecType)
{
case 1:
StartWPG.HorizontalUnits=ReadBlobLSBShort(image);
StartWPG.VerticalUnits=ReadBlobLSBShort(image);
StartWPG.PosSizePrecision=ReadBlobByte(image);
break;
case 0x0C: /* Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((char)
ReadBlobByte(image));
(void) ReadBlobByte(image); /*Opacity??*/
}
break;
case 0x0E:
Bitmap2Header1.Width=ReadBlobLSBShort(image);
Bitmap2Header1.Height=ReadBlobLSBShort(image);
if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
Bitmap2Header1.Depth=ReadBlobByte(image);
Bitmap2Header1.Compression=ReadBlobByte(image);
if(Bitmap2Header1.Compression > 1)
continue; /*Unknown compression method */
switch(Bitmap2Header1.Depth)
{
case 1:
bpp=1;
break;
case 2:
bpp=2;
break;
case 3:
bpp=4;
break;
case 4:
bpp=8;
break;
case 8:
bpp=24;
break;
default:
continue; /*Ignore raster with unknown depth*/
}
image->columns=Bitmap2Header1.Width;
image->rows=Bitmap2Header1.Height;
if ((image->colors == 0) && (bpp != 24))
{
size_t
one;
one=1;
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
}
else
{
if(bpp < 24)
if( image->colors<(one << bpp) && bpp!=24 )
image->colormap=(PixelInfo *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
switch(Bitmap2Header1.Compression)
{
case 0: /*Uncompressed raster*/
{
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t)
ldblk+1,sizeof(*BImgBuff));
if (BImgBuff == (unsigned char *) NULL)
goto NoMemory;
for(i=0; i< (ssize_t) image->rows; i++)
{
(void) ReadBlob(image,ldblk,BImgBuff);
InsertRow(image,BImgBuff,i,bpp,exception);
}
if(BImgBuff)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);;
break;
}
case 1: /*RLE for WPG2 */
{
if( UnpackWPG2Raster(image,bpp,exception) < 0)
goto DecompressionFailed;
break;
}
}
if(CTM[0][0]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0;
Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll);
Tx(1,2)=0; Tx(2,2)=1; */
}
if(CTM[1][1]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
float_matrix Tx(3,3);
Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0;
Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll);
Tx(2,2)=1; */
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x12: /* Postscript WPG2*/
i=ReadBlobLSBShort(image);
if(Rec2.RecordLength > (unsigned int) i)
image=ExtractPostscript(image,image_info,
TellBlob(image)+i, /*skip PS header in the wpg2*/
(ssize_t) (Rec2.RecordLength-i-2),exception);
break;
case 0x1B: /*bitmap rectangle*/
WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM);
(void) WPG2Flags;
break;
}
}
break;
default:
{
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
}
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
Finish:
(void) CloseBlob(image);
{
Image
*p;
ssize_t
scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers.
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=(size_t) scene++;
}
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,
"ImageFileDoesNotContainAnyImageData");
return(image);
}
| 168,795 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: png_text_compress(png_structp png_ptr,
png_charp text, png_size_t text_len, int compression,
compression_state *comp)
{
int ret;
comp->num_output_ptr = 0;
comp->max_output_ptr = 0;
comp->output_ptr = NULL;
comp->input = NULL;
comp->input_len = 0;
/* We may just want to pass the text right through */
if (compression == PNG_TEXT_COMPRESSION_NONE)
{
comp->input = text;
comp->input_len = text_len;
return((int)text_len);
}
if (compression >= PNG_TEXT_COMPRESSION_LAST)
{
#if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE)
char msg[50];
png_snprintf(msg, 50, "Unknown compression type %d", compression);
png_warning(png_ptr, msg);
#else
png_warning(png_ptr, "Unknown compression type");
#endif
}
/* We can't write the chunk until we find out how much data we have,
* which means we need to run the compressor first and save the
* output. This shouldn't be a problem, as the vast majority of
* comments should be reasonable, but we will set up an array of
* malloc'd pointers to be sure.
*
* If we knew the application was well behaved, we could simplify this
* greatly by assuming we can always malloc an output buffer large
* enough to hold the compressed text ((1001 * text_len / 1000) + 12)
* and malloc this directly. The only time this would be a bad idea is
* if we can't malloc more than 64K and we have 64K of random input
* data, or if the input string is incredibly large (although this
* wouldn't cause a failure, just a slowdown due to swapping).
*/
/* Set up the compression buffers */
png_ptr->zstream.avail_in = (uInt)text_len;
png_ptr->zstream.next_in = (Bytef *)text;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
/* This is the same compression loop as in png_write_row() */
do
{
/* Compress the data */
ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
if (ret != Z_OK)
{
/* Error */
if (png_ptr->zstream.msg != NULL)
png_error(png_ptr, png_ptr->zstream.msg);
else
png_error(png_ptr, "zlib error");
}
/* Check to see if we need more room */
if (!(png_ptr->zstream.avail_out))
{
/* Make sure the output array has room */
if (comp->num_output_ptr >= comp->max_output_ptr)
{
int old_max;
old_max = comp->max_output_ptr;
comp->max_output_ptr = comp->num_output_ptr + 4;
if (comp->output_ptr != NULL)
{
png_charpp old_ptr;
old_ptr = comp->output_ptr;
comp->output_ptr = (png_charpp)png_malloc(png_ptr,
(png_uint_32)
(comp->max_output_ptr * png_sizeof(png_charpp)));
png_memcpy(comp->output_ptr, old_ptr, old_max
* png_sizeof(png_charp));
png_free(png_ptr, old_ptr);
}
else
comp->output_ptr = (png_charpp)png_malloc(png_ptr,
(png_uint_32)
(comp->max_output_ptr * png_sizeof(png_charp)));
}
/* Save the data */
comp->output_ptr[comp->num_output_ptr] =
(png_charp)png_malloc(png_ptr,
(png_uint_32)png_ptr->zbuf_size);
png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
png_ptr->zbuf_size);
comp->num_output_ptr++;
/* and reset the buffer */
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_out = png_ptr->zbuf;
}
/* Continue until we don't have any more to compress */
} while (png_ptr->zstream.avail_in);
/* Finish the compression */
do
{
/* Tell zlib we are finished */
ret = deflate(&png_ptr->zstream, Z_FINISH);
if (ret == Z_OK)
{
/* Check to see if we need more room */
if (!(png_ptr->zstream.avail_out))
{
/* Check to make sure our output array has room */
if (comp->num_output_ptr >= comp->max_output_ptr)
{
int old_max;
old_max = comp->max_output_ptr;
comp->max_output_ptr = comp->num_output_ptr + 4;
if (comp->output_ptr != NULL)
{
png_charpp old_ptr;
old_ptr = comp->output_ptr;
/* This could be optimized to realloc() */
comp->output_ptr = (png_charpp)png_malloc(png_ptr,
(png_uint_32)(comp->max_output_ptr *
png_sizeof(png_charp)));
png_memcpy(comp->output_ptr, old_ptr,
old_max * png_sizeof(png_charp));
png_free(png_ptr, old_ptr);
}
else
comp->output_ptr = (png_charpp)png_malloc(png_ptr,
(png_uint_32)(comp->max_output_ptr *
png_sizeof(png_charp)));
}
/* Save the data */
comp->output_ptr[comp->num_output_ptr] =
(png_charp)png_malloc(png_ptr,
(png_uint_32)png_ptr->zbuf_size);
png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
png_ptr->zbuf_size);
comp->num_output_ptr++;
/* and reset the buffer pointers */
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_out = png_ptr->zbuf;
}
}
else if (ret != Z_STREAM_END)
{
/* We got an error */
if (png_ptr->zstream.msg != NULL)
png_error(png_ptr, png_ptr->zstream.msg);
else
png_error(png_ptr, "zlib error");
}
} while (ret != Z_STREAM_END);
/* Text length is number of buffers plus last buffer */
text_len = png_ptr->zbuf_size * comp->num_output_ptr;
if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
return((int)text_len);
}
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_text_compress(png_structp png_ptr,
png_charp text, png_size_t text_len, int compression,
compression_state *comp)
{
int ret;
comp->num_output_ptr = 0;
comp->max_output_ptr = 0;
comp->output_ptr = NULL;
comp->input = NULL;
comp->input_len = 0;
/* We may just want to pass the text right through */
if (compression == PNG_TEXT_COMPRESSION_NONE)
{
comp->input = text;
comp->input_len = text_len;
return((int)text_len);
}
if (compression >= PNG_TEXT_COMPRESSION_LAST)
{
#if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE)
char msg[50];
png_snprintf(msg, 50, "Unknown compression type %d", compression);
png_warning(png_ptr, msg);
#else
png_warning(png_ptr, "Unknown compression type");
#endif
}
/* We can't write the chunk until we find out how much data we have,
* which means we need to run the compressor first and save the
* output. This shouldn't be a problem, as the vast majority of
* comments should be reasonable, but we will set up an array of
* malloc'd pointers to be sure.
*
* If we knew the application was well behaved, we could simplify this
* greatly by assuming we can always malloc an output buffer large
* enough to hold the compressed text ((1001 * text_len / 1000) + 12)
* and malloc this directly. The only time this would be a bad idea is
* if we can't malloc more than 64K and we have 64K of random input
* data, or if the input string is incredibly large (although this
* wouldn't cause a failure, just a slowdown due to swapping).
*/
/* Set up the compression buffers */
png_ptr->zstream.avail_in = (uInt)text_len;
png_ptr->zstream.next_in = (Bytef *)text;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
/* This is the same compression loop as in png_write_row() */
do
{
/* Compress the data */
ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
if (ret != Z_OK)
{
/* Error */
if (png_ptr->zstream.msg != NULL)
png_error(png_ptr, png_ptr->zstream.msg);
else
png_error(png_ptr, "zlib error");
}
/* Check to see if we need more room */
if (!(png_ptr->zstream.avail_out))
{
/* Make sure the output array has room */
if (comp->num_output_ptr >= comp->max_output_ptr)
{
int old_max;
old_max = comp->max_output_ptr;
comp->max_output_ptr = comp->num_output_ptr + 4;
if (comp->output_ptr != NULL)
{
png_charpp old_ptr;
old_ptr = comp->output_ptr;
comp->output_ptr = (png_charpp)png_malloc(png_ptr,
(png_uint_32)
(comp->max_output_ptr * png_sizeof(png_charp)));
png_memcpy(comp->output_ptr, old_ptr, old_max
* png_sizeof(png_charp));
png_free(png_ptr, old_ptr);
}
else
comp->output_ptr = (png_charpp)png_malloc(png_ptr,
(png_uint_32)
(comp->max_output_ptr * png_sizeof(png_charp)));
}
/* Save the data */
comp->output_ptr[comp->num_output_ptr] =
(png_charp)png_malloc(png_ptr,
(png_uint_32)png_ptr->zbuf_size);
png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
png_ptr->zbuf_size);
comp->num_output_ptr++;
/* and reset the buffer */
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_out = png_ptr->zbuf;
}
/* Continue until we don't have any more to compress */
} while (png_ptr->zstream.avail_in);
/* Finish the compression */
do
{
/* Tell zlib we are finished */
ret = deflate(&png_ptr->zstream, Z_FINISH);
if (ret == Z_OK)
{
/* Check to see if we need more room */
if (!(png_ptr->zstream.avail_out))
{
/* Check to make sure our output array has room */
if (comp->num_output_ptr >= comp->max_output_ptr)
{
int old_max;
old_max = comp->max_output_ptr;
comp->max_output_ptr = comp->num_output_ptr + 4;
if (comp->output_ptr != NULL)
{
png_charpp old_ptr;
old_ptr = comp->output_ptr;
/* This could be optimized to realloc() */
comp->output_ptr = (png_charpp)png_malloc(png_ptr,
(png_uint_32)(comp->max_output_ptr *
png_sizeof(png_charp)));
png_memcpy(comp->output_ptr, old_ptr,
old_max * png_sizeof(png_charp));
png_free(png_ptr, old_ptr);
}
else
comp->output_ptr = (png_charpp)png_malloc(png_ptr,
(png_uint_32)(comp->max_output_ptr *
png_sizeof(png_charp)));
}
/* Save the data */
comp->output_ptr[comp->num_output_ptr] =
(png_charp)png_malloc(png_ptr,
(png_uint_32)png_ptr->zbuf_size);
png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
png_ptr->zbuf_size);
comp->num_output_ptr++;
/* and reset the buffer pointers */
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_out = png_ptr->zbuf;
}
}
else if (ret != Z_STREAM_END)
{
/* We got an error */
if (png_ptr->zstream.msg != NULL)
png_error(png_ptr, png_ptr->zstream.msg);
else
png_error(png_ptr, "zlib error");
}
} while (ret != Z_STREAM_END);
/* Text length is number of buffers plus last buffer */
text_len = png_ptr->zbuf_size * comp->num_output_ptr;
if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
return((int)text_len);
}
| 172,192 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void set_own_dir(const char *argv0) {
size_t l = strlen(argv0);
while(l && argv0[l - 1] != '/')
l--;
if(l == 0)
memcpy(own_dir, ".", 2);
else {
memcpy(own_dir, argv0, l - 1);
own_dir[l] = 0;
}
}
Commit Message: fix for CVE-2015-3887
closes #60
CWE ID: CWE-426
|
static void set_own_dir(const char *argv0) {
size_t l = strlen(argv0);
while(l && argv0[l - 1] != '/')
l--;
if(l == 0)
#ifdef SUPER_SECURE
memcpy(own_dir, "/dev/null/", 2);
#else
memcpy(own_dir, ".", 2);
#endif
else {
memcpy(own_dir, argv0, l - 1);
own_dir[l] = 0;
}
}
| 168,884 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: OMX_ERRORTYPE omx_video::use_output_buffer(
OMX_IN OMX_HANDLETYPE hComp,
OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr,
OMX_IN OMX_U32 port,
OMX_IN OMX_PTR appData,
OMX_IN OMX_U32 bytes,
OMX_IN OMX_U8* buffer)
{
(void)hComp, (void)port;
OMX_ERRORTYPE eRet = OMX_ErrorNone;
OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header
unsigned i= 0; // Temporary counter
unsigned char *buf_addr = NULL;
#ifdef _MSM8974_
int align_size;
#endif
DEBUG_PRINT_HIGH("Inside use_output_buffer()");
if (bytes != m_sOutPortDef.nBufferSize) {
DEBUG_PRINT_ERROR("ERROR: use_output_buffer: Size Mismatch!! "
"bytes[%u] != Port.nBufferSize[%u]", (unsigned int)bytes, (unsigned int)m_sOutPortDef.nBufferSize);
return OMX_ErrorBadParameter;
}
if (!m_out_mem_ptr) {
output_use_buffer = true;
int nBufHdrSize = 0;
DEBUG_PRINT_LOW("Allocating First Output Buffer(%u)",(unsigned int)m_sOutPortDef.nBufferCountActual);
nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE);
/*
* Memory for output side involves the following:
* 1. Array of Buffer Headers
* 2. Bitmask array to hold the buffer allocation details
* In order to minimize the memory management entire allocation
* is done in one step.
*/
m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1);
if (m_out_mem_ptr == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_out_mem_ptr");
return OMX_ErrorInsufficientResources;
}
m_pOutput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sOutPortDef.nBufferCountActual);
if (m_pOutput_pmem == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem");
return OMX_ErrorInsufficientResources;
}
#ifdef USE_ION
m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual);
if (m_pOutput_ion == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion");
return OMX_ErrorInsufficientResources;
}
#endif
if (m_out_mem_ptr) {
bufHdr = m_out_mem_ptr;
DEBUG_PRINT_LOW("Memory Allocation Succeeded for OUT port%p",m_out_mem_ptr);
for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) {
bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE);
bufHdr->nVersion.nVersion = OMX_SPEC_VERSION;
bufHdr->nAllocLen = bytes;
bufHdr->nFilledLen = 0;
bufHdr->pAppPrivate = appData;
bufHdr->nOutputPortIndex = PORT_INDEX_OUT;
bufHdr->pBuffer = NULL;
bufHdr++;
m_pOutput_pmem[i].fd = -1;
#ifdef USE_ION
m_pOutput_ion[i].ion_device_fd =-1;
m_pOutput_ion[i].fd_ion_data.fd=-1;
m_pOutput_ion[i].ion_alloc_data.handle = 0;
#endif
}
} else {
DEBUG_PRINT_ERROR("ERROR: Output buf mem alloc failed[0x%p]",m_out_mem_ptr);
eRet = OMX_ErrorInsufficientResources;
}
}
for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) {
if (BITMASK_ABSENT(&m_out_bm_count,i)) {
break;
}
}
if (eRet == OMX_ErrorNone) {
if (i < m_sOutPortDef.nBufferCountActual) {
*bufferHdr = (m_out_mem_ptr + i );
(*bufferHdr)->pBuffer = (OMX_U8 *)buffer;
(*bufferHdr)->pAppPrivate = appData;
BITMASK_SET(&m_out_bm_count,i);
if (!m_use_output_pmem) {
#ifdef USE_ION
#ifdef _MSM8974_
align_size = (m_sOutPortDef.nBufferSize + (SZ_4K - 1)) & ~(SZ_4K - 1);
m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size,
&m_pOutput_ion[i].ion_alloc_data,
&m_pOutput_ion[i].fd_ion_data,0);
#else
m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(
m_sOutPortDef.nBufferSize,
&m_pOutput_ion[i].ion_alloc_data,
&m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED);
#endif
if (m_pOutput_ion[i].ion_device_fd < 0) {
DEBUG_PRINT_ERROR("ERROR:ION device open() Failed");
return OMX_ErrorInsufficientResources;
}
m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd;
#else
m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
if (m_pOutput_pmem[i].fd == 0) {
m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
}
if (m_pOutput_pmem[i].fd < 0) {
DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed");
return OMX_ErrorInsufficientResources;
}
#endif
m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize;
m_pOutput_pmem[i].offset = 0;
m_pOutput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR;
if(!secure_session) {
#ifdef _MSM8974_
m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL,
align_size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pOutput_pmem[i].fd,0);
#else
m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL,
m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pOutput_pmem[i].fd,0);
#endif
if (m_pOutput_pmem[i].buffer == MAP_FAILED) {
DEBUG_PRINT_ERROR("ERROR: mmap() Failed");
close(m_pOutput_pmem[i].fd);
#ifdef USE_ION
free_ion_memory(&m_pOutput_ion[i]);
#endif
return OMX_ErrorInsufficientResources;
}
}
} else {
OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *pParam = reinterpret_cast<OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO*>((*bufferHdr)->pAppPrivate);
DEBUG_PRINT_LOW("Inside qcom_ext pParam: %p", pParam);
if (pParam) {
DEBUG_PRINT_LOW("Inside qcom_ext with luma:(fd:%lu,offset:0x%x)", pParam->pmem_fd, (int)pParam->offset);
m_pOutput_pmem[i].fd = pParam->pmem_fd;
m_pOutput_pmem[i].offset = pParam->offset;
m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize;
m_pOutput_pmem[i].buffer = (unsigned char *)buffer;
} else {
DEBUG_PRINT_ERROR("ERROR: Invalid AppData given for PMEM o/p UseBuffer case");
return OMX_ErrorBadParameter;
}
buf_addr = (unsigned char *)buffer;
}
DEBUG_PRINT_LOW("use_out:: bufhdr = %p, pBuffer = %p, m_pOutput_pmem[i].buffer = %p",
(*bufferHdr), (*bufferHdr)->pBuffer, m_pOutput_pmem[i].buffer);
if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) {
DEBUG_PRINT_ERROR("ERROR: dev_use_buf Failed for o/p buf");
return OMX_ErrorInsufficientResources;
}
} else {
DEBUG_PRINT_ERROR("ERROR: All o/p Buffers have been Used, invalid use_buf call for "
"index = %u", i);
eRet = OMX_ErrorInsufficientResources;
}
}
return eRet;
}
Commit Message: DO NOT MERGE mm-video-v4l2: venc: add safety checks for freeing buffers
Allow only up to 64 buffers on input/output port (since the
allocation bitmap is only 64-wide).
Add safety checks to free only as many buffers were allocated.
Fixes: Heap Overflow and Possible Local Privilege Escalation in
MediaServer (libOmxVenc problem)
Bug: 27532497
Change-Id: I31e576ef9dc542df73aa6b0ea113d72724b50fc6
CWE ID: CWE-119
|
OMX_ERRORTYPE omx_video::use_output_buffer(
OMX_IN OMX_HANDLETYPE hComp,
OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr,
OMX_IN OMX_U32 port,
OMX_IN OMX_PTR appData,
OMX_IN OMX_U32 bytes,
OMX_IN OMX_U8* buffer)
{
(void)hComp, (void)port;
OMX_ERRORTYPE eRet = OMX_ErrorNone;
OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header
unsigned i= 0; // Temporary counter
unsigned char *buf_addr = NULL;
#ifdef _MSM8974_
int align_size;
#endif
DEBUG_PRINT_HIGH("Inside use_output_buffer()");
if (bytes != m_sOutPortDef.nBufferSize) {
DEBUG_PRINT_ERROR("ERROR: use_output_buffer: Size Mismatch!! "
"bytes[%u] != Port.nBufferSize[%u]", (unsigned int)bytes, (unsigned int)m_sOutPortDef.nBufferSize);
return OMX_ErrorBadParameter;
}
if (!m_out_mem_ptr) {
output_use_buffer = true;
int nBufHdrSize = 0;
DEBUG_PRINT_LOW("Allocating First Output Buffer(%u)",(unsigned int)m_sOutPortDef.nBufferCountActual);
nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE);
/*
* Memory for output side involves the following:
* 1. Array of Buffer Headers
* 2. Bitmask array to hold the buffer allocation details
* In order to minimize the memory management entire allocation
* is done in one step.
*/
m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1);
if (m_out_mem_ptr == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_out_mem_ptr");
return OMX_ErrorInsufficientResources;
}
m_pOutput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sOutPortDef.nBufferCountActual);
if (m_pOutput_pmem == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem");
return OMX_ErrorInsufficientResources;
}
#ifdef USE_ION
m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual);
if (m_pOutput_ion == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion");
return OMX_ErrorInsufficientResources;
}
#endif
if (m_out_mem_ptr) {
bufHdr = m_out_mem_ptr;
DEBUG_PRINT_LOW("Memory Allocation Succeeded for OUT port%p",m_out_mem_ptr);
for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) {
bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE);
bufHdr->nVersion.nVersion = OMX_SPEC_VERSION;
bufHdr->nAllocLen = bytes;
bufHdr->nFilledLen = 0;
bufHdr->pAppPrivate = appData;
bufHdr->nOutputPortIndex = PORT_INDEX_OUT;
bufHdr->pBuffer = NULL;
bufHdr++;
m_pOutput_pmem[i].fd = -1;
#ifdef USE_ION
m_pOutput_ion[i].ion_device_fd =-1;
m_pOutput_ion[i].fd_ion_data.fd=-1;
m_pOutput_ion[i].ion_alloc_data.handle = 0;
#endif
}
} else {
DEBUG_PRINT_ERROR("ERROR: Output buf mem alloc failed[0x%p]",m_out_mem_ptr);
eRet = OMX_ErrorInsufficientResources;
}
}
for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) {
if (BITMASK_ABSENT(&m_out_bm_count,i)) {
break;
}
}
if (eRet == OMX_ErrorNone) {
if (i < m_sOutPortDef.nBufferCountActual) {
*bufferHdr = (m_out_mem_ptr + i );
(*bufferHdr)->pBuffer = (OMX_U8 *)buffer;
(*bufferHdr)->pAppPrivate = appData;
if (!m_use_output_pmem) {
#ifdef USE_ION
#ifdef _MSM8974_
align_size = (m_sOutPortDef.nBufferSize + (SZ_4K - 1)) & ~(SZ_4K - 1);
m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size,
&m_pOutput_ion[i].ion_alloc_data,
&m_pOutput_ion[i].fd_ion_data,0);
#else
m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(
m_sOutPortDef.nBufferSize,
&m_pOutput_ion[i].ion_alloc_data,
&m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED);
#endif
if (m_pOutput_ion[i].ion_device_fd < 0) {
DEBUG_PRINT_ERROR("ERROR:ION device open() Failed");
return OMX_ErrorInsufficientResources;
}
m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd;
#else
m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
if (m_pOutput_pmem[i].fd == 0) {
m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
}
if (m_pOutput_pmem[i].fd < 0) {
DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed");
return OMX_ErrorInsufficientResources;
}
#endif
m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize;
m_pOutput_pmem[i].offset = 0;
m_pOutput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR;
if(!secure_session) {
#ifdef _MSM8974_
m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL,
align_size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pOutput_pmem[i].fd,0);
#else
m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL,
m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pOutput_pmem[i].fd,0);
#endif
if (m_pOutput_pmem[i].buffer == MAP_FAILED) {
DEBUG_PRINT_ERROR("ERROR: mmap() Failed");
close(m_pOutput_pmem[i].fd);
#ifdef USE_ION
free_ion_memory(&m_pOutput_ion[i]);
#endif
return OMX_ErrorInsufficientResources;
}
}
} else {
OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *pParam = reinterpret_cast<OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO*>((*bufferHdr)->pAppPrivate);
DEBUG_PRINT_LOW("Inside qcom_ext pParam: %p", pParam);
if (pParam) {
DEBUG_PRINT_LOW("Inside qcom_ext with luma:(fd:%lu,offset:0x%x)", pParam->pmem_fd, (int)pParam->offset);
m_pOutput_pmem[i].fd = pParam->pmem_fd;
m_pOutput_pmem[i].offset = pParam->offset;
m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize;
m_pOutput_pmem[i].buffer = (unsigned char *)buffer;
} else {
DEBUG_PRINT_ERROR("ERROR: Invalid AppData given for PMEM o/p UseBuffer case");
return OMX_ErrorBadParameter;
}
buf_addr = (unsigned char *)buffer;
}
DEBUG_PRINT_LOW("use_out:: bufhdr = %p, pBuffer = %p, m_pOutput_pmem[i].buffer = %p",
(*bufferHdr), (*bufferHdr)->pBuffer, m_pOutput_pmem[i].buffer);
if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) {
DEBUG_PRINT_ERROR("ERROR: dev_use_buf Failed for o/p buf");
return OMX_ErrorInsufficientResources;
}
BITMASK_SET(&m_out_bm_count,i);
} else {
DEBUG_PRINT_ERROR("ERROR: All o/p Buffers have been Used, invalid use_buf call for "
"index = %u", i);
eRet = OMX_ErrorInsufficientResources;
}
}
return eRet;
}
| 173,781 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num)
{
const uni_to_enc *l = table,
*h = &table[num-1],
*m;
unsigned short code_key;
/* we have no mappings outside the BMP */
if (code_key_a > 0xFFFFU)
return 0;
code_key = (unsigned short) code_key_a;
while (l <= h) {
m = l + (h - l) / 2;
if (code_key < m->un_code_point)
h = m - 1;
else if (code_key > m->un_code_point)
l = m + 1;
else
return m->cs_code;
}
return 0;
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190
|
static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num)
{
const uni_to_enc *l = table,
*h = &table[num-1],
*m;
unsigned short code_key;
/* we have no mappings outside the BMP */
if (code_key_a > 0xFFFFU)
return 0;
code_key = (unsigned short) code_key_a;
while (l <= h) {
m = l + (h - l) / 2;
if (code_key < m->un_code_point)
h = m - 1;
else if (code_key > m->un_code_point)
l = m + 1;
else
return m->cs_code;
}
return 0;
}
| 167,180 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: virDomainGetTime(virDomainPtr dom,
long long *seconds,
unsigned int *nseconds,
unsigned int flags)
{
VIR_DOMAIN_DEBUG(dom, "seconds=%p, nseconds=%p, flags=%x",
seconds, nseconds, flags);
virResetLastError();
virCheckDomainReturn(dom, -1);
if (dom->conn->driver->domainGetTime) {
int ret = dom->conn->driver->domainGetTime(dom, seconds,
nseconds, flags);
if (ret < 0)
goto error;
return ret;
}
virReportUnsupportedError();
error:
virDispatchError(dom->conn);
return -1;
}
Commit Message: virDomainGetTime: Deny on RO connections
We have a policy that if API may end up talking to a guest agent
it should require RW connection. We don't obey the rule in
virDomainGetTime().
Signed-off-by: Michal Privoznik <[email protected]>
CWE ID: CWE-254
|
virDomainGetTime(virDomainPtr dom,
long long *seconds,
unsigned int *nseconds,
unsigned int flags)
{
VIR_DOMAIN_DEBUG(dom, "seconds=%p, nseconds=%p, flags=%x",
seconds, nseconds, flags);
virResetLastError();
virCheckDomainReturn(dom, -1);
virCheckReadOnlyGoto(dom->conn->flags, error);
if (dom->conn->driver->domainGetTime) {
int ret = dom->conn->driver->domainGetTime(dom, seconds,
nseconds, flags);
if (ret < 0)
goto error;
return ret;
}
virReportUnsupportedError();
error:
virDispatchError(dom->conn);
return -1;
}
| 169,863 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: dissect_usb_ms_bulk(tvbuff_t *tvb, packet_info *pinfo, proto_tree *parent_tree, void* data)
{
usb_conv_info_t *usb_conv_info;
usb_ms_conv_info_t *usb_ms_conv_info;
proto_tree *tree;
proto_item *ti;
guint32 signature=0;
int offset=0;
gboolean is_request;
itl_nexus_t *itl;
itlq_nexus_t *itlq;
/* Reject the packet if data is NULL */
if (data == NULL)
return 0;
usb_conv_info = (usb_conv_info_t *)data;
/* verify that we do have a usb_ms_conv_info */
usb_ms_conv_info=(usb_ms_conv_info_t *)usb_conv_info->class_data;
if(!usb_ms_conv_info){
usb_ms_conv_info=wmem_new(wmem_file_scope(), usb_ms_conv_info_t);
usb_ms_conv_info->itl=wmem_tree_new(wmem_file_scope());
usb_ms_conv_info->itlq=wmem_tree_new(wmem_file_scope());
usb_conv_info->class_data=usb_ms_conv_info;
}
is_request=(pinfo->srcport==NO_ENDPOINT);
col_set_str(pinfo->cinfo, COL_PROTOCOL, "USBMS");
col_clear(pinfo->cinfo, COL_INFO);
ti = proto_tree_add_protocol_format(parent_tree, proto_usb_ms, tvb, 0, -1, "USB Mass Storage");
tree = proto_item_add_subtree(ti, ett_usb_ms);
signature=tvb_get_letohl(tvb, offset);
/*
* SCSI CDB inside CBW
*/
if(is_request&&(signature==0x43425355)&&(tvb_reported_length(tvb)==31)){
tvbuff_t *cdb_tvb;
int cdbrlen, cdblen;
guint8 lun, flags;
guint32 datalen;
/* dCBWSignature */
proto_tree_add_item(tree, hf_usb_ms_dCBWSignature, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCBWTag */
proto_tree_add_item(tree, hf_usb_ms_dCBWTag, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCBWDataTransferLength */
proto_tree_add_item(tree, hf_usb_ms_dCBWDataTransferLength, tvb, offset, 4, ENC_LITTLE_ENDIAN);
datalen=tvb_get_letohl(tvb, offset);
offset+=4;
/* dCBWFlags */
proto_tree_add_item(tree, hf_usb_ms_dCBWFlags, tvb, offset, 1, ENC_LITTLE_ENDIAN);
flags=tvb_get_guint8(tvb, offset);
offset+=1;
/* dCBWLUN */
proto_tree_add_item(tree, hf_usb_ms_dCBWTarget, tvb, offset, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_usb_ms_dCBWLUN, tvb, offset, 1, ENC_LITTLE_ENDIAN);
lun=tvb_get_guint8(tvb, offset)&0x0f;
offset+=1;
/* make sure we have a ITL structure for this LUN */
itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, lun);
if(!itl){
itl=wmem_new(wmem_file_scope(), itl_nexus_t);
itl->cmdset=0xff;
itl->conversation=NULL;
wmem_tree_insert32(usb_ms_conv_info->itl, lun, itl);
}
/* make sure we have an ITLQ structure for this LUN/transaction */
itlq=(itlq_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itlq, pinfo->num);
if(!itlq){
itlq=wmem_new(wmem_file_scope(), itlq_nexus_t);
itlq->lun=lun;
itlq->scsi_opcode=0xffff;
itlq->task_flags=0;
if(datalen){
if(flags&0x80){
itlq->task_flags|=SCSI_DATA_READ;
} else {
itlq->task_flags|=SCSI_DATA_WRITE;
}
}
itlq->data_length=datalen;
itlq->bidir_data_length=0;
itlq->fc_time=pinfo->abs_ts;
itlq->first_exchange_frame=pinfo->num;
itlq->last_exchange_frame=0;
itlq->flags=0;
itlq->alloc_len=0;
itlq->extra_data=NULL;
wmem_tree_insert32(usb_ms_conv_info->itlq, pinfo->num, itlq);
}
/* dCBWCBLength */
proto_tree_add_item(tree, hf_usb_ms_dCBWCBLength, tvb, offset, 1, ENC_LITTLE_ENDIAN);
cdbrlen=tvb_get_guint8(tvb, offset)&0x1f;
offset+=1;
cdblen=cdbrlen;
if(cdblen>tvb_captured_length_remaining(tvb, offset)){
cdblen=tvb_captured_length_remaining(tvb, offset);
}
if(cdblen){
cdb_tvb=tvb_new_subset(tvb, offset, cdblen, cdbrlen);
dissect_scsi_cdb(cdb_tvb, pinfo, parent_tree, SCSI_DEV_UNKNOWN, itlq, itl);
}
return tvb_captured_length(tvb);
}
/*
* SCSI RESPONSE inside CSW
*/
if((!is_request)&&(signature==0x53425355)&&(tvb_reported_length(tvb)==13)){
guint8 status;
/* dCSWSignature */
proto_tree_add_item(tree, hf_usb_ms_dCSWSignature, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCSWTag */
proto_tree_add_item(tree, hf_usb_ms_dCBWTag, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCSWDataResidue */
proto_tree_add_item(tree, hf_usb_ms_dCSWDataResidue, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCSWStatus */
proto_tree_add_item(tree, hf_usb_ms_dCSWStatus, tvb, offset, 1, ENC_LITTLE_ENDIAN);
status=tvb_get_guint8(tvb, offset);
/*offset+=1;*/
itlq=(itlq_nexus_t *)wmem_tree_lookup32_le(usb_ms_conv_info->itlq, pinfo->num);
if(!itlq){
return tvb_captured_length(tvb);
}
itlq->last_exchange_frame=pinfo->num;
itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, itlq->lun);
if(!itl){
return tvb_captured_length(tvb);
}
if(!status){
dissect_scsi_rsp(tvb, pinfo, parent_tree, itlq, itl, 0);
} else {
/* just send "check condition" */
dissect_scsi_rsp(tvb, pinfo, parent_tree, itlq, itl, 0x02);
}
return tvb_captured_length(tvb);
}
/*
* Ok it was neither CDB not STATUS so just assume it is either data in/out
*/
itlq=(itlq_nexus_t *)wmem_tree_lookup32_le(usb_ms_conv_info->itlq, pinfo->num);
if(!itlq){
return tvb_captured_length(tvb);
}
itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, itlq->lun);
if(!itl){
return tvb_captured_length(tvb);
}
dissect_scsi_payload(tvb, pinfo, parent_tree, is_request, itlq, itl, 0);
return tvb_captured_length(tvb);
}
Commit Message: Make class "type" for USB conversations.
USB dissectors can't assume that only their class type has been passed around in the conversation. Make explicit check that class type expected matches the dissector and stop/prevent dissection if there isn't a match.
Bug: 12356
Change-Id: Ib23973a4ebd0fbb51952ffc118daf95e3389a209
Reviewed-on: https://code.wireshark.org/review/15212
Petri-Dish: Michael Mann <[email protected]>
Reviewed-by: Martin Kaiser <[email protected]>
Petri-Dish: Martin Kaiser <[email protected]>
Tested-by: Petri Dish Buildbot <[email protected]>
Reviewed-by: Michael Mann <[email protected]>
CWE ID: CWE-476
|
dissect_usb_ms_bulk(tvbuff_t *tvb, packet_info *pinfo, proto_tree *parent_tree, void* data)
{
usb_conv_info_t *usb_conv_info;
usb_ms_conv_info_t *usb_ms_conv_info;
proto_tree *tree;
proto_item *ti;
guint32 signature=0;
int offset=0;
gboolean is_request;
itl_nexus_t *itl;
itlq_nexus_t *itlq;
/* Reject the packet if data is NULL */
if (data == NULL)
return 0;
usb_conv_info = (usb_conv_info_t *)data;
/* verify that we do have a usb_ms_conv_info */
usb_ms_conv_info=(usb_ms_conv_info_t *)usb_conv_info->class_data;
if(!usb_ms_conv_info){
usb_ms_conv_info=wmem_new(wmem_file_scope(), usb_ms_conv_info_t);
usb_ms_conv_info->itl=wmem_tree_new(wmem_file_scope());
usb_ms_conv_info->itlq=wmem_tree_new(wmem_file_scope());
usb_conv_info->class_data=usb_ms_conv_info;
usb_conv_info->class_data_type = USB_CONV_MASS_STORAGE;
} else if (usb_conv_info->class_data_type != USB_CONV_MASS_STORAGE) {
/* Don't dissect if another USB type is in the conversation */
return 0;
}
is_request=(pinfo->srcport==NO_ENDPOINT);
col_set_str(pinfo->cinfo, COL_PROTOCOL, "USBMS");
col_clear(pinfo->cinfo, COL_INFO);
ti = proto_tree_add_protocol_format(parent_tree, proto_usb_ms, tvb, 0, -1, "USB Mass Storage");
tree = proto_item_add_subtree(ti, ett_usb_ms);
signature=tvb_get_letohl(tvb, offset);
/*
* SCSI CDB inside CBW
*/
if(is_request&&(signature==0x43425355)&&(tvb_reported_length(tvb)==31)){
tvbuff_t *cdb_tvb;
int cdbrlen, cdblen;
guint8 lun, flags;
guint32 datalen;
/* dCBWSignature */
proto_tree_add_item(tree, hf_usb_ms_dCBWSignature, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCBWTag */
proto_tree_add_item(tree, hf_usb_ms_dCBWTag, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCBWDataTransferLength */
proto_tree_add_item(tree, hf_usb_ms_dCBWDataTransferLength, tvb, offset, 4, ENC_LITTLE_ENDIAN);
datalen=tvb_get_letohl(tvb, offset);
offset+=4;
/* dCBWFlags */
proto_tree_add_item(tree, hf_usb_ms_dCBWFlags, tvb, offset, 1, ENC_LITTLE_ENDIAN);
flags=tvb_get_guint8(tvb, offset);
offset+=1;
/* dCBWLUN */
proto_tree_add_item(tree, hf_usb_ms_dCBWTarget, tvb, offset, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_usb_ms_dCBWLUN, tvb, offset, 1, ENC_LITTLE_ENDIAN);
lun=tvb_get_guint8(tvb, offset)&0x0f;
offset+=1;
/* make sure we have a ITL structure for this LUN */
itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, lun);
if(!itl){
itl=wmem_new(wmem_file_scope(), itl_nexus_t);
itl->cmdset=0xff;
itl->conversation=NULL;
wmem_tree_insert32(usb_ms_conv_info->itl, lun, itl);
}
/* make sure we have an ITLQ structure for this LUN/transaction */
itlq=(itlq_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itlq, pinfo->num);
if(!itlq){
itlq=wmem_new(wmem_file_scope(), itlq_nexus_t);
itlq->lun=lun;
itlq->scsi_opcode=0xffff;
itlq->task_flags=0;
if(datalen){
if(flags&0x80){
itlq->task_flags|=SCSI_DATA_READ;
} else {
itlq->task_flags|=SCSI_DATA_WRITE;
}
}
itlq->data_length=datalen;
itlq->bidir_data_length=0;
itlq->fc_time=pinfo->abs_ts;
itlq->first_exchange_frame=pinfo->num;
itlq->last_exchange_frame=0;
itlq->flags=0;
itlq->alloc_len=0;
itlq->extra_data=NULL;
wmem_tree_insert32(usb_ms_conv_info->itlq, pinfo->num, itlq);
}
/* dCBWCBLength */
proto_tree_add_item(tree, hf_usb_ms_dCBWCBLength, tvb, offset, 1, ENC_LITTLE_ENDIAN);
cdbrlen=tvb_get_guint8(tvb, offset)&0x1f;
offset+=1;
cdblen=cdbrlen;
if(cdblen>tvb_captured_length_remaining(tvb, offset)){
cdblen=tvb_captured_length_remaining(tvb, offset);
}
if(cdblen){
cdb_tvb=tvb_new_subset(tvb, offset, cdblen, cdbrlen);
dissect_scsi_cdb(cdb_tvb, pinfo, parent_tree, SCSI_DEV_UNKNOWN, itlq, itl);
}
return tvb_captured_length(tvb);
}
/*
* SCSI RESPONSE inside CSW
*/
if((!is_request)&&(signature==0x53425355)&&(tvb_reported_length(tvb)==13)){
guint8 status;
/* dCSWSignature */
proto_tree_add_item(tree, hf_usb_ms_dCSWSignature, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCSWTag */
proto_tree_add_item(tree, hf_usb_ms_dCBWTag, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCSWDataResidue */
proto_tree_add_item(tree, hf_usb_ms_dCSWDataResidue, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCSWStatus */
proto_tree_add_item(tree, hf_usb_ms_dCSWStatus, tvb, offset, 1, ENC_LITTLE_ENDIAN);
status=tvb_get_guint8(tvb, offset);
/*offset+=1;*/
itlq=(itlq_nexus_t *)wmem_tree_lookup32_le(usb_ms_conv_info->itlq, pinfo->num);
if(!itlq){
return tvb_captured_length(tvb);
}
itlq->last_exchange_frame=pinfo->num;
itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, itlq->lun);
if(!itl){
return tvb_captured_length(tvb);
}
if(!status){
dissect_scsi_rsp(tvb, pinfo, parent_tree, itlq, itl, 0);
} else {
/* just send "check condition" */
dissect_scsi_rsp(tvb, pinfo, parent_tree, itlq, itl, 0x02);
}
return tvb_captured_length(tvb);
}
/*
* Ok it was neither CDB not STATUS so just assume it is either data in/out
*/
itlq=(itlq_nexus_t *)wmem_tree_lookup32_le(usb_ms_conv_info->itlq, pinfo->num);
if(!itlq){
return tvb_captured_length(tvb);
}
itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, itlq->lun);
if(!itl){
return tvb_captured_length(tvb);
}
dissect_scsi_payload(tvb, pinfo, parent_tree, is_request, itlq, itl, 0);
return tvb_captured_length(tvb);
}
| 167,154 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void JBIG2Stream::readSegments() {
Guint segNum, segFlags, segType, page, segLength;
Guint refFlags, nRefSegs;
Guint *refSegs;
Goffset segDataPos;
int c1, c2, c3;
Guint i;
while (readULong(&segNum)) {
if (!readUByte(&segFlags)) {
goto eofError1;
}
segType = segFlags & 0x3f;
if (!readUByte(&refFlags)) {
goto eofError1;
}
nRefSegs = refFlags >> 5;
if (nRefSegs == 7) {
if ((c1 = curStr->getChar()) == EOF ||
(c2 = curStr->getChar()) == EOF ||
(c3 = curStr->getChar()) == EOF) {
goto eofError1;
}
refFlags = (refFlags << 24) | (c1 << 16) | (c2 << 8) | c3;
nRefSegs = refFlags & 0x1fffffff;
for (i = 0; i < (nRefSegs + 9) >> 3; ++i) {
if ((c1 = curStr->getChar()) == EOF) {
goto eofError1;
}
}
}
refSegs = (Guint *)gmallocn(nRefSegs, sizeof(Guint));
if (segNum <= 256) {
for (i = 0; i < nRefSegs; ++i) {
if (!readUByte(&refSegs[i])) {
goto eofError2;
}
}
} else if (segNum <= 65536) {
for (i = 0; i < nRefSegs; ++i) {
if (!readUWord(&refSegs[i])) {
goto eofError2;
}
}
} else {
for (i = 0; i < nRefSegs; ++i) {
if (!readULong(&refSegs[i])) {
goto eofError2;
}
}
}
if (segFlags & 0x40) {
if (!readULong(&page)) {
goto eofError2;
}
} else {
if (!readUByte(&page)) {
goto eofError2;
}
}
if (!readULong(&segLength)) {
goto eofError2;
}
segDataPos = curStr->getPos();
if (!pageBitmap && ((segType >= 4 && segType <= 7) ||
(segType >= 20 && segType <= 43))) {
error(errSyntaxError, curStr->getPos(), "First JBIG2 segment associated with a page must be a page information segment");
goto syntaxError;
}
switch (segType) {
case 0:
if (!readSymbolDictSeg(segNum, segLength, refSegs, nRefSegs)) {
goto syntaxError;
}
break;
case 4:
readTextRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs);
break;
case 6:
readTextRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs);
break;
case 7:
readTextRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs);
break;
case 16:
readPatternDictSeg(segNum, segLength);
break;
case 20:
readHalftoneRegionSeg(segNum, gFalse, gFalse, segLength,
refSegs, nRefSegs);
break;
case 22:
readHalftoneRegionSeg(segNum, gTrue, gFalse, segLength,
refSegs, nRefSegs);
break;
case 23:
readHalftoneRegionSeg(segNum, gTrue, gTrue, segLength,
refSegs, nRefSegs);
break;
case 36:
readGenericRegionSeg(segNum, gFalse, gFalse, segLength);
break;
case 38:
readGenericRegionSeg(segNum, gTrue, gFalse, segLength);
break;
case 39:
readGenericRegionSeg(segNum, gTrue, gTrue, segLength);
break;
case 40:
readGenericRefinementRegionSeg(segNum, gFalse, gFalse, segLength,
refSegs, nRefSegs);
break;
case 42:
readGenericRefinementRegionSeg(segNum, gTrue, gFalse, segLength,
refSegs, nRefSegs);
break;
case 43:
readGenericRefinementRegionSeg(segNum, gTrue, gTrue, segLength,
refSegs, nRefSegs);
break;
case 48:
readPageInfoSeg(segLength);
break;
case 50:
readEndOfStripeSeg(segLength);
break;
case 52:
readProfilesSeg(segLength);
break;
case 53:
readCodeTableSeg(segNum, segLength);
break;
case 62:
readExtensionSeg(segLength);
break;
default:
error(errSyntaxError, curStr->getPos(), "Unknown segment type in JBIG2 stream");
for (i = 0; i < segLength; ++i) {
if ((c1 = curStr->getChar()) == EOF) {
goto eofError2;
}
}
break;
}
if (segLength != 0xffffffff) {
Goffset segExtraBytes = segDataPos + segLength - curStr->getPos();
if (segExtraBytes > 0) {
error(errSyntaxError, curStr->getPos(), "{0:d} extraneous byte{1:s} after segment",
segExtraBytes, (segExtraBytes > 1) ? "s" : "");
int trash;
for (Goffset i = segExtraBytes; i > 0; i--) {
readByte(&trash);
}
} else if (segExtraBytes < 0) {
error(errSyntaxError, curStr->getPos(), "Previous segment handler read too many bytes");
}
}
gfree(refSegs);
}
return;
syntaxError:
gfree(refSegs);
return;
eofError2:
gfree(refSegs);
eofError1:
error(errSyntaxError, curStr->getPos(), "Unexpected EOF in JBIG2 stream");
}
Commit Message:
CWE ID: CWE-119
|
void JBIG2Stream::readSegments() {
Guint segNum, segFlags, segType, page, segLength;
Guint refFlags, nRefSegs;
Guint *refSegs;
Goffset segDataPos;
int c1, c2, c3;
Guint i;
while (readULong(&segNum)) {
if (!readUByte(&segFlags)) {
goto eofError1;
}
segType = segFlags & 0x3f;
if (!readUByte(&refFlags)) {
goto eofError1;
}
nRefSegs = refFlags >> 5;
if (nRefSegs == 7) {
if ((c1 = curStr->getChar()) == EOF ||
(c2 = curStr->getChar()) == EOF ||
(c3 = curStr->getChar()) == EOF) {
goto eofError1;
}
refFlags = (refFlags << 24) | (c1 << 16) | (c2 << 8) | c3;
nRefSegs = refFlags & 0x1fffffff;
for (i = 0; i < (nRefSegs + 9) >> 3; ++i) {
if ((c1 = curStr->getChar()) == EOF) {
goto eofError1;
}
}
}
refSegs = (Guint *)gmallocn(nRefSegs, sizeof(Guint));
if (segNum <= 256) {
for (i = 0; i < nRefSegs; ++i) {
if (!readUByte(&refSegs[i])) {
goto eofError2;
}
}
} else if (segNum <= 65536) {
for (i = 0; i < nRefSegs; ++i) {
if (!readUWord(&refSegs[i])) {
goto eofError2;
}
}
} else {
for (i = 0; i < nRefSegs; ++i) {
if (!readULong(&refSegs[i])) {
goto eofError2;
}
}
}
if (segFlags & 0x40) {
if (!readULong(&page)) {
goto eofError2;
}
} else {
if (!readUByte(&page)) {
goto eofError2;
}
}
if (!readULong(&segLength)) {
goto eofError2;
}
segDataPos = curStr->getPos();
if (!pageBitmap && ((segType >= 4 && segType <= 7) ||
(segType >= 20 && segType <= 43))) {
error(errSyntaxError, curStr->getPos(), "First JBIG2 segment associated with a page must be a page information segment");
goto syntaxError;
}
switch (segType) {
case 0:
if (!readSymbolDictSeg(segNum, segLength, refSegs, nRefSegs)) {
goto syntaxError;
}
break;
case 4:
readTextRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs);
break;
case 6:
readTextRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs);
break;
case 7:
readTextRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs);
break;
case 16:
readPatternDictSeg(segNum, segLength);
break;
case 20:
readHalftoneRegionSeg(segNum, gFalse, gFalse, segLength,
refSegs, nRefSegs);
break;
case 22:
readHalftoneRegionSeg(segNum, gTrue, gFalse, segLength,
refSegs, nRefSegs);
break;
case 23:
readHalftoneRegionSeg(segNum, gTrue, gTrue, segLength,
refSegs, nRefSegs);
break;
case 36:
readGenericRegionSeg(segNum, gFalse, gFalse, segLength);
break;
case 38:
readGenericRegionSeg(segNum, gTrue, gFalse, segLength);
break;
case 39:
readGenericRegionSeg(segNum, gTrue, gTrue, segLength);
break;
case 40:
readGenericRefinementRegionSeg(segNum, gFalse, gFalse, segLength,
refSegs, nRefSegs);
break;
case 42:
readGenericRefinementRegionSeg(segNum, gTrue, gFalse, segLength,
refSegs, nRefSegs);
break;
case 43:
readGenericRefinementRegionSeg(segNum, gTrue, gTrue, segLength,
refSegs, nRefSegs);
break;
case 48:
readPageInfoSeg(segLength);
break;
case 50:
readEndOfStripeSeg(segLength);
break;
case 52:
readProfilesSeg(segLength);
break;
case 53:
readCodeTableSeg(segNum, segLength);
break;
case 62:
readExtensionSeg(segLength);
break;
default:
error(errSyntaxError, curStr->getPos(), "Unknown segment type in JBIG2 stream");
for (i = 0; i < segLength; ++i) {
if ((c1 = curStr->getChar()) == EOF) {
goto eofError2;
}
}
break;
}
if (segLength != 0xffffffff) {
Goffset segExtraBytes = segDataPos + segLength - curStr->getPos();
if (segExtraBytes > 0) {
error(errSyntaxError, curStr->getPos(), "{0:lld} extraneous byte{1:s} after segment",
segExtraBytes, (segExtraBytes > 1) ? "s" : "");
int trash;
for (Goffset i = segExtraBytes; i > 0; i--) {
readByte(&trash);
}
} else if (segExtraBytes < 0) {
error(errSyntaxError, curStr->getPos(), "Previous segment handler read too many bytes");
}
}
gfree(refSegs);
}
return;
syntaxError:
gfree(refSegs);
return;
eofError2:
gfree(refSegs);
eofError1:
error(errSyntaxError, curStr->getPos(), "Unexpected EOF in JBIG2 stream");
}
| 165,299 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed 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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: ikev1_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth)
{
const struct ikev1_pl_n *p;
struct ikev1_pl_n n;
const u_char *cp;
const u_char *ep2;
uint32_t doi;
uint32_t proto;
static const char *notify_error_str[] = {
NULL, "INVALID-PAYLOAD-TYPE",
"DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED",
"INVALID-COOKIE", "INVALID-MAJOR-VERSION",
"INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE",
"INVALID-FLAGS", "INVALID-MESSAGE-ID",
"INVALID-PROTOCOL-ID", "INVALID-SPI",
"INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED",
"NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX",
"PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION",
"INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING",
"INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED",
"INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION",
"AUTHENTICATION-FAILED", "INVALID-SIGNATURE",
"ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME",
"CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE",
"UNEQUAL-PAYLOAD-LENGTHS",
};
static const char *ipsec_notify_error_str[] = {
"RESERVED",
};
static const char *notify_status_str[] = {
"CONNECTED",
};
static const char *ipsec_notify_status_str[] = {
"RESPONDER-LIFETIME", "REPLAY-STATUS",
"INITIAL-CONTACT",
};
/* NOTE: these macro must be called with x in proper range */
/* 0 - 8191 */
#define NOTIFY_ERROR_STR(x) \
STR_OR_ID((x), notify_error_str)
/* 8192 - 16383 */
#define IPSEC_NOTIFY_ERROR_STR(x) \
STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str)
/* 16384 - 24575 */
#define NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 16384), notify_status_str)
/* 24576 - 32767 */
#define IPSEC_NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str)
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N)));
p = (const struct ikev1_pl_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
doi = ntohl(n.doi);
proto = n.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," proto=%d", proto));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
return (const u_char *)(p + 1) + n.spi_size;
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else if (ntohs(n.type) < 32768)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
ep2 = (const u_char *)p + item_len;
if (cp < ep) {
ND_PRINT((ndo," orig=("));
switch (ntohs(n.type)) {
case IPSECDOI_NTYPE_RESPONDER_LIFETIME:
{
const struct attrmap *map = oakley_t_map;
size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
while (cp < ep && cp < ep2) {
cp = ikev1_attrmap_print(ndo, cp,
(ep < ep2) ? ep : ep2, map, nmap);
}
break;
}
case IPSECDOI_NTYPE_REPLAY_STATUS:
ND_PRINT((ndo,"replay detection %sabled",
EXTRACT_32BITS(cp) ? "en" : "dis"));
break;
case ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN:
if (ikev1_sub_print(ndo, ISAKMP_NPTYPE_SA,
(const struct isakmp_gen *)cp, ep, phase, doi, proto,
depth) == NULL)
return NULL;
break;
default:
/* NULL is dummy */
isakmp_print(ndo, cp,
item_len - sizeof(*p) - n.spi_size,
NULL);
}
ND_PRINT((ndo,")"));
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
Commit Message: CVE-2017-12990/Fix printing of ISAKMPv1 Notification payload data.
The closest thing to a specification for the contents of the payload
data is draft-ietf-ipsec-notifymsg-04, and nothing in there says that it
is ever a complete ISAKMP message, so don't dissect types we don't have
specific code for as a complete ISAKMP message.
While we're at it, fix a comment, and clean up printing of V1 Nonce,
V2 Authentication payloads, and v2 Notice payloads.
This fixes an infinite loop discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-835
|
ikev1_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_n *p;
struct ikev1_pl_n n;
const u_char *cp;
const u_char *ep2;
uint32_t doi;
uint32_t proto;
static const char *notify_error_str[] = {
NULL, "INVALID-PAYLOAD-TYPE",
"DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED",
"INVALID-COOKIE", "INVALID-MAJOR-VERSION",
"INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE",
"INVALID-FLAGS", "INVALID-MESSAGE-ID",
"INVALID-PROTOCOL-ID", "INVALID-SPI",
"INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED",
"NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX",
"PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION",
"INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING",
"INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED",
"INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION",
"AUTHENTICATION-FAILED", "INVALID-SIGNATURE",
"ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME",
"CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE",
"UNEQUAL-PAYLOAD-LENGTHS",
};
static const char *ipsec_notify_error_str[] = {
"RESERVED",
};
static const char *notify_status_str[] = {
"CONNECTED",
};
static const char *ipsec_notify_status_str[] = {
"RESPONDER-LIFETIME", "REPLAY-STATUS",
"INITIAL-CONTACT",
};
/* NOTE: these macro must be called with x in proper range */
/* 0 - 8191 */
#define NOTIFY_ERROR_STR(x) \
STR_OR_ID((x), notify_error_str)
/* 8192 - 16383 */
#define IPSEC_NOTIFY_ERROR_STR(x) \
STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str)
/* 16384 - 24575 */
#define NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 16384), notify_status_str)
/* 24576 - 32767 */
#define IPSEC_NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str)
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N)));
p = (const struct ikev1_pl_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
doi = ntohl(n.doi);
proto = n.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," proto=%d", proto));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
return (const u_char *)(p + 1) + n.spi_size;
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else if (ntohs(n.type) < 32768)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
ep2 = (const u_char *)p + item_len;
if (cp < ep) {
switch (ntohs(n.type)) {
case IPSECDOI_NTYPE_RESPONDER_LIFETIME:
{
const struct attrmap *map = oakley_t_map;
size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
ND_PRINT((ndo," attrs=("));
while (cp < ep && cp < ep2) {
cp = ikev1_attrmap_print(ndo, cp,
(ep < ep2) ? ep : ep2, map, nmap);
}
ND_PRINT((ndo,")"));
break;
}
case IPSECDOI_NTYPE_REPLAY_STATUS:
ND_PRINT((ndo," status=("));
ND_PRINT((ndo,"replay detection %sabled",
EXTRACT_32BITS(cp) ? "en" : "dis"));
ND_PRINT((ndo,")"));
break;
default:
/*
* XXX - fill in more types here; see, for example,
* draft-ietf-ipsec-notifymsg-04.
*/
if (ndo->ndo_vflag > 3) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else {
if (!ike_show_somedata(ndo, cp, ep))
goto trunc;
}
break;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
| 167,924 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static struct sk_buff *udp6_ufo_fragment(struct sk_buff *skb,
netdev_features_t features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
unsigned int mss;
unsigned int unfrag_ip6hlen, unfrag_len;
struct frag_hdr *fptr;
u8 *packet_start, *prevhdr;
u8 nexthdr;
u8 frag_hdr_sz = sizeof(struct frag_hdr);
__wsum csum;
int tnl_hlen;
mss = skb_shinfo(skb)->gso_size;
if (unlikely(skb->len <= mss))
goto out;
if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) {
/* Packet is from an untrusted source, reset gso_segs. */
skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss);
/* Set the IPv6 fragment id if not set yet */
if (!skb_shinfo(skb)->ip6_frag_id)
ipv6_proxy_select_ident(dev_net(skb->dev), skb);
segs = NULL;
goto out;
}
if (skb->encapsulation && skb_shinfo(skb)->gso_type &
(SKB_GSO_UDP_TUNNEL|SKB_GSO_UDP_TUNNEL_CSUM))
segs = skb_udp_tunnel_segment(skb, features, true);
else {
const struct ipv6hdr *ipv6h;
struct udphdr *uh;
if (!pskb_may_pull(skb, sizeof(struct udphdr)))
goto out;
/* Do software UFO. Complete and fill in the UDP checksum as HW cannot
* do checksum of UDP packets sent as multiple IP fragments.
*/
uh = udp_hdr(skb);
ipv6h = ipv6_hdr(skb);
uh->check = 0;
csum = skb_checksum(skb, 0, skb->len, 0);
uh->check = udp_v6_check(skb->len, &ipv6h->saddr,
&ipv6h->daddr, csum);
if (uh->check == 0)
uh->check = CSUM_MANGLED_0;
skb->ip_summed = CHECKSUM_NONE;
/* If there is no outer header we can fake a checksum offload
* due to the fact that we have already done the checksum in
* software prior to segmenting the frame.
*/
if (!skb->encap_hdr_csum)
features |= NETIF_F_HW_CSUM;
/* Check if there is enough headroom to insert fragment header. */
tnl_hlen = skb_tnl_header_len(skb);
if (skb->mac_header < (tnl_hlen + frag_hdr_sz)) {
if (gso_pskb_expand_head(skb, tnl_hlen + frag_hdr_sz))
goto out;
}
/* Find the unfragmentable header and shift it left by frag_hdr_sz
* bytes to insert fragment header.
*/
unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr);
nexthdr = *prevhdr;
*prevhdr = NEXTHDR_FRAGMENT;
unfrag_len = (skb_network_header(skb) - skb_mac_header(skb)) +
unfrag_ip6hlen + tnl_hlen;
packet_start = (u8 *) skb->head + SKB_GSO_CB(skb)->mac_offset;
memmove(packet_start-frag_hdr_sz, packet_start, unfrag_len);
SKB_GSO_CB(skb)->mac_offset -= frag_hdr_sz;
skb->mac_header -= frag_hdr_sz;
skb->network_header -= frag_hdr_sz;
fptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen);
fptr->nexthdr = nexthdr;
fptr->reserved = 0;
if (!skb_shinfo(skb)->ip6_frag_id)
ipv6_proxy_select_ident(dev_net(skb->dev), skb);
fptr->identification = skb_shinfo(skb)->ip6_frag_id;
/* Fragment the skb. ipv6 header and the remaining fields of the
* fragment header are updated in ipv6_gso_segment()
*/
segs = skb_segment(skb, features);
}
out:
return segs;
}
Commit Message: ipv6: Prevent overrun when parsing v6 header options
The KASAN warning repoted below was discovered with a syzkaller
program. The reproducer is basically:
int s = socket(AF_INET6, SOCK_RAW, NEXTHDR_HOP);
send(s, &one_byte_of_data, 1, MSG_MORE);
send(s, &more_than_mtu_bytes_data, 2000, 0);
The socket() call sets the nexthdr field of the v6 header to
NEXTHDR_HOP, the first send call primes the payload with a non zero
byte of data, and the second send call triggers the fragmentation path.
The fragmentation code tries to parse the header options in order
to figure out where to insert the fragment option. Since nexthdr points
to an invalid option, the calculation of the size of the network header
can made to be much larger than the linear section of the skb and data
is read outside of it.
This fix makes ip6_find_1stfrag return an error if it detects
running out-of-bounds.
[ 42.361487] ==================================================================
[ 42.364412] BUG: KASAN: slab-out-of-bounds in ip6_fragment+0x11c8/0x3730
[ 42.365471] Read of size 840 at addr ffff88000969e798 by task ip6_fragment-oo/3789
[ 42.366469]
[ 42.366696] CPU: 1 PID: 3789 Comm: ip6_fragment-oo Not tainted 4.11.0+ #41
[ 42.367628] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.1-1ubuntu1 04/01/2014
[ 42.368824] Call Trace:
[ 42.369183] dump_stack+0xb3/0x10b
[ 42.369664] print_address_description+0x73/0x290
[ 42.370325] kasan_report+0x252/0x370
[ 42.370839] ? ip6_fragment+0x11c8/0x3730
[ 42.371396] check_memory_region+0x13c/0x1a0
[ 42.371978] memcpy+0x23/0x50
[ 42.372395] ip6_fragment+0x11c8/0x3730
[ 42.372920] ? nf_ct_expect_unregister_notifier+0x110/0x110
[ 42.373681] ? ip6_copy_metadata+0x7f0/0x7f0
[ 42.374263] ? ip6_forward+0x2e30/0x2e30
[ 42.374803] ip6_finish_output+0x584/0x990
[ 42.375350] ip6_output+0x1b7/0x690
[ 42.375836] ? ip6_finish_output+0x990/0x990
[ 42.376411] ? ip6_fragment+0x3730/0x3730
[ 42.376968] ip6_local_out+0x95/0x160
[ 42.377471] ip6_send_skb+0xa1/0x330
[ 42.377969] ip6_push_pending_frames+0xb3/0xe0
[ 42.378589] rawv6_sendmsg+0x2051/0x2db0
[ 42.379129] ? rawv6_bind+0x8b0/0x8b0
[ 42.379633] ? _copy_from_user+0x84/0xe0
[ 42.380193] ? debug_check_no_locks_freed+0x290/0x290
[ 42.380878] ? ___sys_sendmsg+0x162/0x930
[ 42.381427] ? rcu_read_lock_sched_held+0xa3/0x120
[ 42.382074] ? sock_has_perm+0x1f6/0x290
[ 42.382614] ? ___sys_sendmsg+0x167/0x930
[ 42.383173] ? lock_downgrade+0x660/0x660
[ 42.383727] inet_sendmsg+0x123/0x500
[ 42.384226] ? inet_sendmsg+0x123/0x500
[ 42.384748] ? inet_recvmsg+0x540/0x540
[ 42.385263] sock_sendmsg+0xca/0x110
[ 42.385758] SYSC_sendto+0x217/0x380
[ 42.386249] ? SYSC_connect+0x310/0x310
[ 42.386783] ? __might_fault+0x110/0x1d0
[ 42.387324] ? lock_downgrade+0x660/0x660
[ 42.387880] ? __fget_light+0xa1/0x1f0
[ 42.388403] ? __fdget+0x18/0x20
[ 42.388851] ? sock_common_setsockopt+0x95/0xd0
[ 42.389472] ? SyS_setsockopt+0x17f/0x260
[ 42.390021] ? entry_SYSCALL_64_fastpath+0x5/0xbe
[ 42.390650] SyS_sendto+0x40/0x50
[ 42.391103] entry_SYSCALL_64_fastpath+0x1f/0xbe
[ 42.391731] RIP: 0033:0x7fbbb711e383
[ 42.392217] RSP: 002b:00007ffff4d34f28 EFLAGS: 00000246 ORIG_RAX: 000000000000002c
[ 42.393235] RAX: ffffffffffffffda RBX: 0000000000000000 RCX: 00007fbbb711e383
[ 42.394195] RDX: 0000000000001000 RSI: 00007ffff4d34f60 RDI: 0000000000000003
[ 42.395145] RBP: 0000000000000046 R08: 00007ffff4d34f40 R09: 0000000000000018
[ 42.396056] R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000400aad
[ 42.396598] R13: 0000000000000066 R14: 00007ffff4d34ee0 R15: 00007fbbb717af00
[ 42.397257]
[ 42.397411] Allocated by task 3789:
[ 42.397702] save_stack_trace+0x16/0x20
[ 42.398005] save_stack+0x46/0xd0
[ 42.398267] kasan_kmalloc+0xad/0xe0
[ 42.398548] kasan_slab_alloc+0x12/0x20
[ 42.398848] __kmalloc_node_track_caller+0xcb/0x380
[ 42.399224] __kmalloc_reserve.isra.32+0x41/0xe0
[ 42.399654] __alloc_skb+0xf8/0x580
[ 42.400003] sock_wmalloc+0xab/0xf0
[ 42.400346] __ip6_append_data.isra.41+0x2472/0x33d0
[ 42.400813] ip6_append_data+0x1a8/0x2f0
[ 42.401122] rawv6_sendmsg+0x11ee/0x2db0
[ 42.401505] inet_sendmsg+0x123/0x500
[ 42.401860] sock_sendmsg+0xca/0x110
[ 42.402209] ___sys_sendmsg+0x7cb/0x930
[ 42.402582] __sys_sendmsg+0xd9/0x190
[ 42.402941] SyS_sendmsg+0x2d/0x50
[ 42.403273] entry_SYSCALL_64_fastpath+0x1f/0xbe
[ 42.403718]
[ 42.403871] Freed by task 1794:
[ 42.404146] save_stack_trace+0x16/0x20
[ 42.404515] save_stack+0x46/0xd0
[ 42.404827] kasan_slab_free+0x72/0xc0
[ 42.405167] kfree+0xe8/0x2b0
[ 42.405462] skb_free_head+0x74/0xb0
[ 42.405806] skb_release_data+0x30e/0x3a0
[ 42.406198] skb_release_all+0x4a/0x60
[ 42.406563] consume_skb+0x113/0x2e0
[ 42.406910] skb_free_datagram+0x1a/0xe0
[ 42.407288] netlink_recvmsg+0x60d/0xe40
[ 42.407667] sock_recvmsg+0xd7/0x110
[ 42.408022] ___sys_recvmsg+0x25c/0x580
[ 42.408395] __sys_recvmsg+0xd6/0x190
[ 42.408753] SyS_recvmsg+0x2d/0x50
[ 42.409086] entry_SYSCALL_64_fastpath+0x1f/0xbe
[ 42.409513]
[ 42.409665] The buggy address belongs to the object at ffff88000969e780
[ 42.409665] which belongs to the cache kmalloc-512 of size 512
[ 42.410846] The buggy address is located 24 bytes inside of
[ 42.410846] 512-byte region [ffff88000969e780, ffff88000969e980)
[ 42.411941] The buggy address belongs to the page:
[ 42.412405] page:ffffea000025a780 count:1 mapcount:0 mapping: (null) index:0x0 compound_mapcount: 0
[ 42.413298] flags: 0x100000000008100(slab|head)
[ 42.413729] raw: 0100000000008100 0000000000000000 0000000000000000 00000001800c000c
[ 42.414387] raw: ffffea00002a9500 0000000900000007 ffff88000c401280 0000000000000000
[ 42.415074] page dumped because: kasan: bad access detected
[ 42.415604]
[ 42.415757] Memory state around the buggy address:
[ 42.416222] ffff88000969e880: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 42.416904] ffff88000969e900: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 42.417591] >ffff88000969e980: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[ 42.418273] ^
[ 42.418588] ffff88000969ea00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
[ 42.419273] ffff88000969ea80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
[ 42.419882] ==================================================================
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: Craig Gallek <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-125
|
static struct sk_buff *udp6_ufo_fragment(struct sk_buff *skb,
netdev_features_t features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
unsigned int mss;
unsigned int unfrag_ip6hlen, unfrag_len;
struct frag_hdr *fptr;
u8 *packet_start, *prevhdr;
u8 nexthdr;
u8 frag_hdr_sz = sizeof(struct frag_hdr);
__wsum csum;
int tnl_hlen;
mss = skb_shinfo(skb)->gso_size;
if (unlikely(skb->len <= mss))
goto out;
if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) {
/* Packet is from an untrusted source, reset gso_segs. */
skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss);
/* Set the IPv6 fragment id if not set yet */
if (!skb_shinfo(skb)->ip6_frag_id)
ipv6_proxy_select_ident(dev_net(skb->dev), skb);
segs = NULL;
goto out;
}
if (skb->encapsulation && skb_shinfo(skb)->gso_type &
(SKB_GSO_UDP_TUNNEL|SKB_GSO_UDP_TUNNEL_CSUM))
segs = skb_udp_tunnel_segment(skb, features, true);
else {
const struct ipv6hdr *ipv6h;
struct udphdr *uh;
if (!pskb_may_pull(skb, sizeof(struct udphdr)))
goto out;
/* Do software UFO. Complete and fill in the UDP checksum as HW cannot
* do checksum of UDP packets sent as multiple IP fragments.
*/
uh = udp_hdr(skb);
ipv6h = ipv6_hdr(skb);
uh->check = 0;
csum = skb_checksum(skb, 0, skb->len, 0);
uh->check = udp_v6_check(skb->len, &ipv6h->saddr,
&ipv6h->daddr, csum);
if (uh->check == 0)
uh->check = CSUM_MANGLED_0;
skb->ip_summed = CHECKSUM_NONE;
/* If there is no outer header we can fake a checksum offload
* due to the fact that we have already done the checksum in
* software prior to segmenting the frame.
*/
if (!skb->encap_hdr_csum)
features |= NETIF_F_HW_CSUM;
/* Check if there is enough headroom to insert fragment header. */
tnl_hlen = skb_tnl_header_len(skb);
if (skb->mac_header < (tnl_hlen + frag_hdr_sz)) {
if (gso_pskb_expand_head(skb, tnl_hlen + frag_hdr_sz))
goto out;
}
/* Find the unfragmentable header and shift it left by frag_hdr_sz
* bytes to insert fragment header.
*/
unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr);
if (unfrag_ip6hlen < 0)
return ERR_PTR(unfrag_ip6hlen);
nexthdr = *prevhdr;
*prevhdr = NEXTHDR_FRAGMENT;
unfrag_len = (skb_network_header(skb) - skb_mac_header(skb)) +
unfrag_ip6hlen + tnl_hlen;
packet_start = (u8 *) skb->head + SKB_GSO_CB(skb)->mac_offset;
memmove(packet_start-frag_hdr_sz, packet_start, unfrag_len);
SKB_GSO_CB(skb)->mac_offset -= frag_hdr_sz;
skb->mac_header -= frag_hdr_sz;
skb->network_header -= frag_hdr_sz;
fptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen);
fptr->nexthdr = nexthdr;
fptr->reserved = 0;
if (!skb_shinfo(skb)->ip6_frag_id)
ipv6_proxy_select_ident(dev_net(skb->dev), skb);
fptr->identification = skb_shinfo(skb)->ip6_frag_id;
/* Fragment the skb. ipv6 header and the remaining fields of the
* fragment header are updated in ipv6_gso_segment()
*/
segs = skb_segment(skb, features);
}
out:
return segs;
}
| 168,133 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
unsigned long arg, int ifreq_len)
{
struct tun_file *tfile = file->private_data;
struct tun_struct *tun;
void __user* argp = (void __user*)arg;
struct sock_fprog fprog;
struct ifreq ifr;
int sndbuf;
int vnet_hdr_sz;
int ret;
if (cmd == TUNSETIFF || _IOC_TYPE(cmd) == 0x89)
if (copy_from_user(&ifr, argp, ifreq_len))
return -EFAULT;
if (cmd == TUNGETFEATURES) {
/* Currently this just means: "what IFF flags are valid?".
* This is needed because we never checked for invalid flags on
* TUNSETIFF. */
return put_user(IFF_TUN | IFF_TAP | IFF_NO_PI | IFF_ONE_QUEUE |
IFF_VNET_HDR,
(unsigned int __user*)argp);
}
rtnl_lock();
tun = __tun_get(tfile);
if (cmd == TUNSETIFF && !tun) {
ifr.ifr_name[IFNAMSIZ-1] = '\0';
ret = tun_set_iff(tfile->net, file, &ifr);
if (ret)
goto unlock;
if (copy_to_user(argp, &ifr, ifreq_len))
ret = -EFAULT;
goto unlock;
}
ret = -EBADFD;
if (!tun)
goto unlock;
tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %d\n", cmd);
ret = 0;
switch (cmd) {
case TUNGETIFF:
ret = tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
if (ret)
break;
if (copy_to_user(argp, &ifr, ifreq_len))
ret = -EFAULT;
break;
case TUNSETNOCSUM:
/* Disable/Enable checksum */
/* [unimplemented] */
tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
arg ? "disabled" : "enabled");
break;
case TUNSETPERSIST:
/* Disable/Enable persist mode */
if (arg)
tun->flags |= TUN_PERSIST;
else
tun->flags &= ~TUN_PERSIST;
tun_debug(KERN_INFO, tun, "persist %s\n",
arg ? "enabled" : "disabled");
break;
case TUNSETOWNER:
/* Set owner of the device */
tun->owner = (uid_t) arg;
tun_debug(KERN_INFO, tun, "owner set to %d\n", tun->owner);
break;
case TUNSETGROUP:
/* Set group of the device */
tun->group= (gid_t) arg;
tun_debug(KERN_INFO, tun, "group set to %d\n", tun->group);
break;
case TUNSETLINK:
/* Only allow setting the type when the interface is down */
if (tun->dev->flags & IFF_UP) {
tun_debug(KERN_INFO, tun,
"Linktype set failed because interface is up\n");
ret = -EBUSY;
} else {
tun->dev->type = (int) arg;
tun_debug(KERN_INFO, tun, "linktype set to %d\n",
tun->dev->type);
ret = 0;
}
break;
#ifdef TUN_DEBUG
case TUNSETDEBUG:
tun->debug = arg;
break;
#endif
case TUNSETOFFLOAD:
ret = set_offload(tun, arg);
break;
case TUNSETTXFILTER:
/* Can be set only for TAPs */
ret = -EINVAL;
if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
break;
ret = update_filter(&tun->txflt, (void __user *)arg);
break;
case SIOCGIFHWADDR:
/* Get hw address */
memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
ifr.ifr_hwaddr.sa_family = tun->dev->type;
if (copy_to_user(argp, &ifr, ifreq_len))
ret = -EFAULT;
break;
case SIOCSIFHWADDR:
/* Set hw address */
tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
ifr.ifr_hwaddr.sa_data);
ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
break;
case TUNGETSNDBUF:
sndbuf = tun->socket.sk->sk_sndbuf;
if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
ret = -EFAULT;
break;
case TUNSETSNDBUF:
if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
ret = -EFAULT;
break;
}
tun->socket.sk->sk_sndbuf = sndbuf;
break;
case TUNGETVNETHDRSZ:
vnet_hdr_sz = tun->vnet_hdr_sz;
if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
ret = -EFAULT;
break;
case TUNSETVNETHDRSZ:
if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
ret = -EFAULT;
break;
}
if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
ret = -EINVAL;
break;
}
tun->vnet_hdr_sz = vnet_hdr_sz;
break;
case TUNATTACHFILTER:
/* Can be set only for TAPs */
ret = -EINVAL;
if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
break;
ret = -EFAULT;
if (copy_from_user(&fprog, argp, sizeof(fprog)))
break;
ret = sk_attach_filter(&fprog, tun->socket.sk);
break;
case TUNDETACHFILTER:
/* Can be set only for TAPs */
ret = -EINVAL;
if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
break;
ret = sk_detach_filter(tun->socket.sk);
break;
default:
ret = -EINVAL;
break;
}
unlock:
rtnl_unlock();
if (tun)
tun_put(tun);
return ret;
}
Commit Message: net/tun: fix ioctl() based info leaks
The tun module leaks up to 36 bytes of memory by not fully initializing
a structure located on the stack that gets copied to user memory by the
TUNGETIFF and SIOCGIFHWADDR ioctl()s.
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
|
static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
unsigned long arg, int ifreq_len)
{
struct tun_file *tfile = file->private_data;
struct tun_struct *tun;
void __user* argp = (void __user*)arg;
struct sock_fprog fprog;
struct ifreq ifr;
int sndbuf;
int vnet_hdr_sz;
int ret;
if (cmd == TUNSETIFF || _IOC_TYPE(cmd) == 0x89) {
if (copy_from_user(&ifr, argp, ifreq_len))
return -EFAULT;
} else
memset(&ifr, 0, sizeof(ifr));
if (cmd == TUNGETFEATURES) {
/* Currently this just means: "what IFF flags are valid?".
* This is needed because we never checked for invalid flags on
* TUNSETIFF. */
return put_user(IFF_TUN | IFF_TAP | IFF_NO_PI | IFF_ONE_QUEUE |
IFF_VNET_HDR,
(unsigned int __user*)argp);
}
rtnl_lock();
tun = __tun_get(tfile);
if (cmd == TUNSETIFF && !tun) {
ifr.ifr_name[IFNAMSIZ-1] = '\0';
ret = tun_set_iff(tfile->net, file, &ifr);
if (ret)
goto unlock;
if (copy_to_user(argp, &ifr, ifreq_len))
ret = -EFAULT;
goto unlock;
}
ret = -EBADFD;
if (!tun)
goto unlock;
tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %d\n", cmd);
ret = 0;
switch (cmd) {
case TUNGETIFF:
ret = tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
if (ret)
break;
if (copy_to_user(argp, &ifr, ifreq_len))
ret = -EFAULT;
break;
case TUNSETNOCSUM:
/* Disable/Enable checksum */
/* [unimplemented] */
tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
arg ? "disabled" : "enabled");
break;
case TUNSETPERSIST:
/* Disable/Enable persist mode */
if (arg)
tun->flags |= TUN_PERSIST;
else
tun->flags &= ~TUN_PERSIST;
tun_debug(KERN_INFO, tun, "persist %s\n",
arg ? "enabled" : "disabled");
break;
case TUNSETOWNER:
/* Set owner of the device */
tun->owner = (uid_t) arg;
tun_debug(KERN_INFO, tun, "owner set to %d\n", tun->owner);
break;
case TUNSETGROUP:
/* Set group of the device */
tun->group= (gid_t) arg;
tun_debug(KERN_INFO, tun, "group set to %d\n", tun->group);
break;
case TUNSETLINK:
/* Only allow setting the type when the interface is down */
if (tun->dev->flags & IFF_UP) {
tun_debug(KERN_INFO, tun,
"Linktype set failed because interface is up\n");
ret = -EBUSY;
} else {
tun->dev->type = (int) arg;
tun_debug(KERN_INFO, tun, "linktype set to %d\n",
tun->dev->type);
ret = 0;
}
break;
#ifdef TUN_DEBUG
case TUNSETDEBUG:
tun->debug = arg;
break;
#endif
case TUNSETOFFLOAD:
ret = set_offload(tun, arg);
break;
case TUNSETTXFILTER:
/* Can be set only for TAPs */
ret = -EINVAL;
if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
break;
ret = update_filter(&tun->txflt, (void __user *)arg);
break;
case SIOCGIFHWADDR:
/* Get hw address */
memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
ifr.ifr_hwaddr.sa_family = tun->dev->type;
if (copy_to_user(argp, &ifr, ifreq_len))
ret = -EFAULT;
break;
case SIOCSIFHWADDR:
/* Set hw address */
tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
ifr.ifr_hwaddr.sa_data);
ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
break;
case TUNGETSNDBUF:
sndbuf = tun->socket.sk->sk_sndbuf;
if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
ret = -EFAULT;
break;
case TUNSETSNDBUF:
if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
ret = -EFAULT;
break;
}
tun->socket.sk->sk_sndbuf = sndbuf;
break;
case TUNGETVNETHDRSZ:
vnet_hdr_sz = tun->vnet_hdr_sz;
if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
ret = -EFAULT;
break;
case TUNSETVNETHDRSZ:
if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
ret = -EFAULT;
break;
}
if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
ret = -EINVAL;
break;
}
tun->vnet_hdr_sz = vnet_hdr_sz;
break;
case TUNATTACHFILTER:
/* Can be set only for TAPs */
ret = -EINVAL;
if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
break;
ret = -EFAULT;
if (copy_from_user(&fprog, argp, sizeof(fprog)))
break;
ret = sk_attach_filter(&fprog, tun->socket.sk);
break;
case TUNDETACHFILTER:
/* Can be set only for TAPs */
ret = -EINVAL;
if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV)
break;
ret = sk_detach_filter(tun->socket.sk);
break;
default:
ret = -EINVAL;
break;
}
unlock:
rtnl_unlock();
if (tun)
tun_put(tun);
return ret;
}
| 166,179 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: svc_set_num_threads(struct svc_serv *serv, struct svc_pool *pool, int nrservs)
{
struct svc_rqst *rqstp;
struct task_struct *task;
struct svc_pool *chosen_pool;
int error = 0;
unsigned int state = serv->sv_nrthreads-1;
int node;
if (pool == NULL) {
/* The -1 assumes caller has done a svc_get() */
nrservs -= (serv->sv_nrthreads-1);
} else {
spin_lock_bh(&pool->sp_lock);
nrservs -= pool->sp_nrthreads;
spin_unlock_bh(&pool->sp_lock);
}
/* create new threads */
while (nrservs > 0) {
nrservs--;
chosen_pool = choose_pool(serv, pool, &state);
node = svc_pool_map_get_node(chosen_pool->sp_id);
rqstp = svc_prepare_thread(serv, chosen_pool, node);
if (IS_ERR(rqstp)) {
error = PTR_ERR(rqstp);
break;
}
__module_get(serv->sv_ops->svo_module);
task = kthread_create_on_node(serv->sv_ops->svo_function, rqstp,
node, "%s", serv->sv_name);
if (IS_ERR(task)) {
error = PTR_ERR(task);
module_put(serv->sv_ops->svo_module);
svc_exit_thread(rqstp);
break;
}
rqstp->rq_task = task;
if (serv->sv_nrpools > 1)
svc_pool_map_set_cpumask(task, chosen_pool->sp_id);
svc_sock_update_bufs(serv);
wake_up_process(task);
}
/* destroy old threads */
while (nrservs < 0 &&
(task = choose_victim(serv, pool, &state)) != NULL) {
send_sig(SIGINT, task, 1);
nrservs++;
}
return error;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
|
svc_set_num_threads(struct svc_serv *serv, struct svc_pool *pool, int nrservs)
/* create new threads */
static int
svc_start_kthreads(struct svc_serv *serv, struct svc_pool *pool, int nrservs)
{
struct svc_rqst *rqstp;
struct task_struct *task;
struct svc_pool *chosen_pool;
unsigned int state = serv->sv_nrthreads-1;
int node;
do {
nrservs--;
chosen_pool = choose_pool(serv, pool, &state);
node = svc_pool_map_get_node(chosen_pool->sp_id);
rqstp = svc_prepare_thread(serv, chosen_pool, node);
if (IS_ERR(rqstp))
return PTR_ERR(rqstp);
__module_get(serv->sv_ops->svo_module);
task = kthread_create_on_node(serv->sv_ops->svo_function, rqstp,
node, "%s", serv->sv_name);
if (IS_ERR(task)) {
module_put(serv->sv_ops->svo_module);
svc_exit_thread(rqstp);
return PTR_ERR(task);
}
rqstp->rq_task = task;
if (serv->sv_nrpools > 1)
svc_pool_map_set_cpumask(task, chosen_pool->sp_id);
svc_sock_update_bufs(serv);
wake_up_process(task);
} while (nrservs > 0);
return 0;
}
/* destroy old threads */
static int
svc_signal_kthreads(struct svc_serv *serv, struct svc_pool *pool, int nrservs)
{
struct task_struct *task;
unsigned int state = serv->sv_nrthreads-1;
/* destroy old threads */
do {
task = choose_victim(serv, pool, &state);
if (task == NULL)
break;
send_sig(SIGINT, task, 1);
nrservs++;
} while (nrservs < 0);
return 0;
}
/*
* Create or destroy enough new threads to make the number
* of threads the given number. If `pool' is non-NULL, applies
* only to threads in that pool, otherwise round-robins between
* all pools. Caller must ensure that mutual exclusion between this and
* server startup or shutdown.
*
* Destroying threads relies on the service threads filling in
* rqstp->rq_task, which only the nfs ones do. Assumes the serv
* has been created using svc_create_pooled().
*
* Based on code that used to be in nfsd_svc() but tweaked
* to be pool-aware.
*/
int
svc_set_num_threads(struct svc_serv *serv, struct svc_pool *pool, int nrservs)
{
if (pool == NULL) {
/* The -1 assumes caller has done a svc_get() */
nrservs -= (serv->sv_nrthreads-1);
} else {
spin_lock_bh(&pool->sp_lock);
nrservs -= pool->sp_nrthreads;
spin_unlock_bh(&pool->sp_lock);
}
if (nrservs > 0)
return svc_start_kthreads(serv, pool, nrservs);
if (nrservs < 0)
return svc_signal_kthreads(serv, pool, nrservs);
return 0;
}
| 168,155 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_METHOD(Phar, addFromString)
{
char *localname, *cont_str;
size_t localname_len, cont_len;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &localname, &localname_len, &cont_str, &cont_len) == FAILURE) {
return;
}
phar_add_file(&(phar_obj->archive), localname, localname_len, cont_str, cont_len, NULL);
}
Commit Message:
CWE ID: CWE-20
|
PHP_METHOD(Phar, addFromString)
{
char *localname, *cont_str;
size_t localname_len, cont_len;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ps", &localname, &localname_len, &cont_str, &cont_len) == FAILURE) {
return;
}
phar_add_file(&(phar_obj->archive), localname, localname_len, cont_str, cont_len, NULL);
}
| 165,071 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void BaseRenderingContext2D::Reset() {
ValidateStateStack();
UnwindStateStack();
state_stack_.resize(1);
state_stack_.front() = CanvasRenderingContext2DState::Create();
path_.Clear();
if (PaintCanvas* c = ExistingDrawingCanvas()) {
DCHECK_EQ(c->getSaveCount(), 2);
c->restore();
c->save();
DCHECK(c->getTotalMatrix().isIdentity());
#if DCHECK_IS_ON()
SkIRect clip_bounds;
DCHECK(c->getDeviceClipBounds(&clip_bounds));
DCHECK(clip_bounds == c->imageInfo().bounds());
#endif
}
ValidateStateStack();
}
Commit Message: [PE] Distinguish between tainting due to canvas content and filter.
A filter on a canvas can itself lead to origin tainting, for reasons
other than that the canvas contents are tainted. This CL changes
to distinguish these two causes, so that we recompute filters
on content-tainting change.
Bug: 778506
Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6
Reviewed-on: https://chromium-review.googlesource.com/811767
Reviewed-by: Fredrik Söderquist <[email protected]>
Commit-Queue: Chris Harrelson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#522274}
CWE ID: CWE-200
|
void BaseRenderingContext2D::Reset() {
ValidateStateStack();
UnwindStateStack();
state_stack_.resize(1);
state_stack_.front() = CanvasRenderingContext2DState::Create();
path_.Clear();
if (PaintCanvas* c = ExistingDrawingCanvas()) {
DCHECK_EQ(c->getSaveCount(), 2);
c->restore();
c->save();
DCHECK(c->getTotalMatrix().isIdentity());
#if DCHECK_IS_ON()
SkIRect clip_bounds;
DCHECK(c->getDeviceClipBounds(&clip_bounds));
DCHECK(clip_bounds == c->imageInfo().bounds());
#endif
}
ValidateStateStack();
origin_tainted_by_content_ = false;
}
| 172,906 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: zend_object_iterator *spl_filesystem_tree_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC)
{
spl_filesystem_iterator *iterator;
spl_filesystem_object *dir_object;
if (by_ref) {
zend_error(E_ERROR, "An iterator cannot be used with foreach by reference");
}
dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC);
iterator = spl_filesystem_object_to_iterator(dir_object);
/* initialize iterator if wasn't gotten before */
if (iterator->intern.data == NULL) {
iterator->intern.data = object;
iterator->intern.funcs = &spl_filesystem_tree_it_funcs;
}
zval_add_ref(&object);
return (zend_object_iterator*)iterator;
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
zend_object_iterator *spl_filesystem_tree_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC)
{
spl_filesystem_iterator *iterator;
spl_filesystem_object *dir_object;
if (by_ref) {
zend_error(E_ERROR, "An iterator cannot be used with foreach by reference");
}
dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC);
iterator = spl_filesystem_object_to_iterator(dir_object);
/* initialize iterator if wasn't gotten before */
if (iterator->intern.data == NULL) {
iterator->intern.data = object;
iterator->intern.funcs = &spl_filesystem_tree_it_funcs;
}
zval_add_ref(&object);
return (zend_object_iterator*)iterator;
}
| 167,086 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial)
{
cac_private_data_t * priv = CAC_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);
if (card->serialnr.len) {
*serial = card->serialnr;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
if (priv->cac_id_len) {
serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR);
memcpy(serial->value, priv->cac_id, priv->cac_id_len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND);
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415
|
static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial)
{
cac_private_data_t * priv = CAC_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);
if (card->serialnr.len) {
*serial = card->serialnr;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
if (priv->cac_id_len) {
serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR);
memcpy(serial->value, priv->cac_id, serial->len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND);
}
| 169,071 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void testTimeout(void* self)
{
CCLayerTreeHostTest* test = static_cast<CCLayerTreeHostTest*>(self);
if (!test->m_running)
return;
test->m_timedOut = true;
test->endTest();
}
Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests
https://bugs.webkit.org/show_bug.cgi?id=70161
Reviewed by David Levin.
Source/WebCore:
Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor
thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was
destroyed.
This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit
task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the
CCThreadProxy have been drained.
Covered by the now-enabled CCLayerTreeHostTest* unit tests.
* WebCore.gypi:
* platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added.
(WebCore::CCScopedMainThreadProxy::create):
(WebCore::CCScopedMainThreadProxy::postTask):
(WebCore::CCScopedMainThreadProxy::shutdown):
(WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy):
(WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown):
* platform/graphics/chromium/cc/CCThreadProxy.cpp:
(WebCore::CCThreadProxy::CCThreadProxy):
(WebCore::CCThreadProxy::~CCThreadProxy):
(WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread):
* platform/graphics/chromium/cc/CCThreadProxy.h:
Source/WebKit/chromium:
Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple
thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor
thread scheduling draws by itself.
* tests/CCLayerTreeHostTest.cpp:
(::CCLayerTreeHostTest::timeout):
(::CCLayerTreeHostTest::clearTimeout):
(::CCLayerTreeHostTest::CCLayerTreeHostTest):
(::CCLayerTreeHostTest::onEndTest):
(::CCLayerTreeHostTest::TimeoutTask::TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::clearTest):
(::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::Run):
(::CCLayerTreeHostTest::runTest):
(::CCLayerTreeHostTest::doBeginTest):
(::CCLayerTreeHostTestThreadOnly::runTest):
(::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread):
git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
static void testTimeout(void* self)
| 170,297 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int yam_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct yam_port *yp = netdev_priv(dev);
struct yamdrv_ioctl_cfg yi;
struct yamdrv_ioctl_mcs *ym;
int ioctl_cmd;
if (copy_from_user(&ioctl_cmd, ifr->ifr_data, sizeof(int)))
return -EFAULT;
if (yp->magic != YAM_MAGIC)
return -EINVAL;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (cmd != SIOCDEVPRIVATE)
return -EINVAL;
switch (ioctl_cmd) {
case SIOCYAMRESERVED:
return -EINVAL; /* unused */
case SIOCYAMSMCS:
if (netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if ((ym = kmalloc(sizeof(struct yamdrv_ioctl_mcs), GFP_KERNEL)) == NULL)
return -ENOBUFS;
if (copy_from_user(ym, ifr->ifr_data, sizeof(struct yamdrv_ioctl_mcs))) {
kfree(ym);
return -EFAULT;
}
if (ym->bitrate > YAM_MAXBITRATE) {
kfree(ym);
return -EINVAL;
}
/* setting predef as 0 for loading userdefined mcs data */
add_mcs(ym->bits, ym->bitrate, 0);
kfree(ym);
break;
case SIOCYAMSCFG:
if (!capable(CAP_SYS_RAWIO))
return -EPERM;
if (copy_from_user(&yi, ifr->ifr_data, sizeof(struct yamdrv_ioctl_cfg)))
return -EFAULT;
if ((yi.cfg.mask & YAM_IOBASE) && netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if ((yi.cfg.mask & YAM_IRQ) && netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if ((yi.cfg.mask & YAM_BITRATE) && netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if ((yi.cfg.mask & YAM_BAUDRATE) && netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if (yi.cfg.mask & YAM_IOBASE) {
yp->iobase = yi.cfg.iobase;
dev->base_addr = yi.cfg.iobase;
}
if (yi.cfg.mask & YAM_IRQ) {
if (yi.cfg.irq > 15)
return -EINVAL;
yp->irq = yi.cfg.irq;
dev->irq = yi.cfg.irq;
}
if (yi.cfg.mask & YAM_BITRATE) {
if (yi.cfg.bitrate > YAM_MAXBITRATE)
return -EINVAL;
yp->bitrate = yi.cfg.bitrate;
}
if (yi.cfg.mask & YAM_BAUDRATE) {
if (yi.cfg.baudrate > YAM_MAXBAUDRATE)
return -EINVAL;
yp->baudrate = yi.cfg.baudrate;
}
if (yi.cfg.mask & YAM_MODE) {
if (yi.cfg.mode > YAM_MAXMODE)
return -EINVAL;
yp->dupmode = yi.cfg.mode;
}
if (yi.cfg.mask & YAM_HOLDDLY) {
if (yi.cfg.holddly > YAM_MAXHOLDDLY)
return -EINVAL;
yp->holdd = yi.cfg.holddly;
}
if (yi.cfg.mask & YAM_TXDELAY) {
if (yi.cfg.txdelay > YAM_MAXTXDELAY)
return -EINVAL;
yp->txd = yi.cfg.txdelay;
}
if (yi.cfg.mask & YAM_TXTAIL) {
if (yi.cfg.txtail > YAM_MAXTXTAIL)
return -EINVAL;
yp->txtail = yi.cfg.txtail;
}
if (yi.cfg.mask & YAM_PERSIST) {
if (yi.cfg.persist > YAM_MAXPERSIST)
return -EINVAL;
yp->pers = yi.cfg.persist;
}
if (yi.cfg.mask & YAM_SLOTTIME) {
if (yi.cfg.slottime > YAM_MAXSLOTTIME)
return -EINVAL;
yp->slot = yi.cfg.slottime;
yp->slotcnt = yp->slot / 10;
}
break;
case SIOCYAMGCFG:
yi.cfg.mask = 0xffffffff;
yi.cfg.iobase = yp->iobase;
yi.cfg.irq = yp->irq;
yi.cfg.bitrate = yp->bitrate;
yi.cfg.baudrate = yp->baudrate;
yi.cfg.mode = yp->dupmode;
yi.cfg.txdelay = yp->txd;
yi.cfg.holddly = yp->holdd;
yi.cfg.txtail = yp->txtail;
yi.cfg.persist = yp->pers;
yi.cfg.slottime = yp->slot;
if (copy_to_user(ifr->ifr_data, &yi, sizeof(struct yamdrv_ioctl_cfg)))
return -EFAULT;
break;
default:
return -EINVAL;
}
return 0;
}
Commit Message: hamradio/yam: fix info leak in ioctl
The yam_ioctl() code fails to initialise the cmd field
of the struct yamdrv_ioctl_cfg. Add an explicit memset(0)
before filling the structure to avoid the 4-byte info leak.
Signed-off-by: Salva Peiró <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
|
static int yam_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct yam_port *yp = netdev_priv(dev);
struct yamdrv_ioctl_cfg yi;
struct yamdrv_ioctl_mcs *ym;
int ioctl_cmd;
if (copy_from_user(&ioctl_cmd, ifr->ifr_data, sizeof(int)))
return -EFAULT;
if (yp->magic != YAM_MAGIC)
return -EINVAL;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (cmd != SIOCDEVPRIVATE)
return -EINVAL;
switch (ioctl_cmd) {
case SIOCYAMRESERVED:
return -EINVAL; /* unused */
case SIOCYAMSMCS:
if (netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if ((ym = kmalloc(sizeof(struct yamdrv_ioctl_mcs), GFP_KERNEL)) == NULL)
return -ENOBUFS;
if (copy_from_user(ym, ifr->ifr_data, sizeof(struct yamdrv_ioctl_mcs))) {
kfree(ym);
return -EFAULT;
}
if (ym->bitrate > YAM_MAXBITRATE) {
kfree(ym);
return -EINVAL;
}
/* setting predef as 0 for loading userdefined mcs data */
add_mcs(ym->bits, ym->bitrate, 0);
kfree(ym);
break;
case SIOCYAMSCFG:
if (!capable(CAP_SYS_RAWIO))
return -EPERM;
if (copy_from_user(&yi, ifr->ifr_data, sizeof(struct yamdrv_ioctl_cfg)))
return -EFAULT;
if ((yi.cfg.mask & YAM_IOBASE) && netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if ((yi.cfg.mask & YAM_IRQ) && netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if ((yi.cfg.mask & YAM_BITRATE) && netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if ((yi.cfg.mask & YAM_BAUDRATE) && netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if (yi.cfg.mask & YAM_IOBASE) {
yp->iobase = yi.cfg.iobase;
dev->base_addr = yi.cfg.iobase;
}
if (yi.cfg.mask & YAM_IRQ) {
if (yi.cfg.irq > 15)
return -EINVAL;
yp->irq = yi.cfg.irq;
dev->irq = yi.cfg.irq;
}
if (yi.cfg.mask & YAM_BITRATE) {
if (yi.cfg.bitrate > YAM_MAXBITRATE)
return -EINVAL;
yp->bitrate = yi.cfg.bitrate;
}
if (yi.cfg.mask & YAM_BAUDRATE) {
if (yi.cfg.baudrate > YAM_MAXBAUDRATE)
return -EINVAL;
yp->baudrate = yi.cfg.baudrate;
}
if (yi.cfg.mask & YAM_MODE) {
if (yi.cfg.mode > YAM_MAXMODE)
return -EINVAL;
yp->dupmode = yi.cfg.mode;
}
if (yi.cfg.mask & YAM_HOLDDLY) {
if (yi.cfg.holddly > YAM_MAXHOLDDLY)
return -EINVAL;
yp->holdd = yi.cfg.holddly;
}
if (yi.cfg.mask & YAM_TXDELAY) {
if (yi.cfg.txdelay > YAM_MAXTXDELAY)
return -EINVAL;
yp->txd = yi.cfg.txdelay;
}
if (yi.cfg.mask & YAM_TXTAIL) {
if (yi.cfg.txtail > YAM_MAXTXTAIL)
return -EINVAL;
yp->txtail = yi.cfg.txtail;
}
if (yi.cfg.mask & YAM_PERSIST) {
if (yi.cfg.persist > YAM_MAXPERSIST)
return -EINVAL;
yp->pers = yi.cfg.persist;
}
if (yi.cfg.mask & YAM_SLOTTIME) {
if (yi.cfg.slottime > YAM_MAXSLOTTIME)
return -EINVAL;
yp->slot = yi.cfg.slottime;
yp->slotcnt = yp->slot / 10;
}
break;
case SIOCYAMGCFG:
memset(&yi, 0, sizeof(yi));
yi.cfg.mask = 0xffffffff;
yi.cfg.iobase = yp->iobase;
yi.cfg.irq = yp->irq;
yi.cfg.bitrate = yp->bitrate;
yi.cfg.baudrate = yp->baudrate;
yi.cfg.mode = yp->dupmode;
yi.cfg.txdelay = yp->txd;
yi.cfg.holddly = yp->holdd;
yi.cfg.txtail = yp->txtail;
yi.cfg.persist = yp->pers;
yi.cfg.slottime = yp->slot;
if (copy_to_user(ifr->ifr_data, &yi, sizeof(struct yamdrv_ioctl_cfg)))
return -EFAULT;
break;
default:
return -EINVAL;
}
return 0;
}
| 166,437 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int mincore_unmapped_range(unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
walk->private += __mincore_unmapped_range(addr, end,
walk->vma, walk->private);
return 0;
}
Commit Message: Change mincore() to count "mapped" pages rather than "cached" pages
The semantics of what "in core" means for the mincore() system call are
somewhat unclear, but Linux has always (since 2.3.52, which is when
mincore() was initially done) treated it as "page is available in page
cache" rather than "page is mapped in the mapping".
The problem with that traditional semantic is that it exposes a lot of
system cache state that it really probably shouldn't, and that users
shouldn't really even care about.
So let's try to avoid that information leak by simply changing the
semantics to be that mincore() counts actual mapped pages, not pages
that might be cheaply mapped if they were faulted (note the "might be"
part of the old semantics: being in the cache doesn't actually guarantee
that you can access them without IO anyway, since things like network
filesystems may have to revalidate the cache before use).
In many ways the old semantics were somewhat insane even aside from the
information leak issue. From the very beginning (and that beginning is
a long time ago: 2.3.52 was released in March 2000, I think), the code
had a comment saying
Later we can get more picky about what "in core" means precisely.
and this is that "later". Admittedly it is much later than is really
comfortable.
NOTE! This is a real semantic change, and it is for example known to
change the output of "fincore", since that program literally does a
mmmap without populating it, and then doing "mincore()" on that mapping
that doesn't actually have any pages in it.
I'm hoping that nobody actually has any workflow that cares, and the
info leak is real.
We may have to do something different if it turns out that people have
valid reasons to want the old semantics, and if we can limit the
information leak sanely.
Cc: Kevin Easton <[email protected]>
Cc: Jiri Kosina <[email protected]>
Cc: Masatake YAMATO <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: Greg KH <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Michal Hocko <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-200
|
static int mincore_unmapped_range(unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
unsigned char *vec = walk->private;
unsigned long nr = (end - addr) >> PAGE_SHIFT;
memset(vec, 0, nr);
walk->private += nr;
return 0;
}
| 169,748 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void hub_activate(struct usb_hub *hub, enum hub_activation_type type)
{
struct usb_device *hdev = hub->hdev;
struct usb_hcd *hcd;
int ret;
int port1;
int status;
bool need_debounce_delay = false;
unsigned delay;
/* Continue a partial initialization */
if (type == HUB_INIT2)
goto init2;
if (type == HUB_INIT3)
goto init3;
/* The superspeed hub except for root hub has to use Hub Depth
* value as an offset into the route string to locate the bits
* it uses to determine the downstream port number. So hub driver
* should send a set hub depth request to superspeed hub after
* the superspeed hub is set configuration in initialization or
* reset procedure.
*
* After a resume, port power should still be on.
* For any other type of activation, turn it on.
*/
if (type != HUB_RESUME) {
if (hdev->parent && hub_is_superspeed(hdev)) {
ret = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
HUB_SET_DEPTH, USB_RT_HUB,
hdev->level - 1, 0, NULL, 0,
USB_CTRL_SET_TIMEOUT);
if (ret < 0)
dev_err(hub->intfdev,
"set hub depth failed\n");
}
/* Speed up system boot by using a delayed_work for the
* hub's initial power-up delays. This is pretty awkward
* and the implementation looks like a home-brewed sort of
* setjmp/longjmp, but it saves at least 100 ms for each
* root hub (assuming usbcore is compiled into the kernel
* rather than as a module). It adds up.
*
* This can't be done for HUB_RESUME or HUB_RESET_RESUME
* because for those activation types the ports have to be
* operational when we return. In theory this could be done
* for HUB_POST_RESET, but it's easier not to.
*/
if (type == HUB_INIT) {
delay = hub_power_on_good_delay(hub);
hub_power_on(hub, false);
INIT_DELAYED_WORK(&hub->init_work, hub_init_func2);
queue_delayed_work(system_power_efficient_wq,
&hub->init_work,
msecs_to_jiffies(delay));
/* Suppress autosuspend until init is done */
usb_autopm_get_interface_no_resume(
to_usb_interface(hub->intfdev));
return; /* Continues at init2: below */
} else if (type == HUB_RESET_RESUME) {
/* The internal host controller state for the hub device
* may be gone after a host power loss on system resume.
* Update the device's info so the HW knows it's a hub.
*/
hcd = bus_to_hcd(hdev->bus);
if (hcd->driver->update_hub_device) {
ret = hcd->driver->update_hub_device(hcd, hdev,
&hub->tt, GFP_NOIO);
if (ret < 0) {
dev_err(hub->intfdev, "Host not "
"accepting hub info "
"update.\n");
dev_err(hub->intfdev, "LS/FS devices "
"and hubs may not work "
"under this hub\n.");
}
}
hub_power_on(hub, true);
} else {
hub_power_on(hub, true);
}
}
init2:
/*
* Check each port and set hub->change_bits to let hub_wq know
* which ports need attention.
*/
for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
struct usb_port *port_dev = hub->ports[port1 - 1];
struct usb_device *udev = port_dev->child;
u16 portstatus, portchange;
portstatus = portchange = 0;
status = hub_port_status(hub, port1, &portstatus, &portchange);
if (udev || (portstatus & USB_PORT_STAT_CONNECTION))
dev_dbg(&port_dev->dev, "status %04x change %04x\n",
portstatus, portchange);
/*
* After anything other than HUB_RESUME (i.e., initialization
* or any sort of reset), every port should be disabled.
* Unconnected ports should likewise be disabled (paranoia),
* and so should ports for which we have no usb_device.
*/
if ((portstatus & USB_PORT_STAT_ENABLE) && (
type != HUB_RESUME ||
!(portstatus & USB_PORT_STAT_CONNECTION) ||
!udev ||
udev->state == USB_STATE_NOTATTACHED)) {
/*
* USB3 protocol ports will automatically transition
* to Enabled state when detect an USB3.0 device attach.
* Do not disable USB3 protocol ports, just pretend
* power was lost
*/
portstatus &= ~USB_PORT_STAT_ENABLE;
if (!hub_is_superspeed(hdev))
usb_clear_port_feature(hdev, port1,
USB_PORT_FEAT_ENABLE);
}
/* Clear status-change flags; we'll debounce later */
if (portchange & USB_PORT_STAT_C_CONNECTION) {
need_debounce_delay = true;
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_CONNECTION);
}
if (portchange & USB_PORT_STAT_C_ENABLE) {
need_debounce_delay = true;
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_ENABLE);
}
if (portchange & USB_PORT_STAT_C_RESET) {
need_debounce_delay = true;
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_RESET);
}
if ((portchange & USB_PORT_STAT_C_BH_RESET) &&
hub_is_superspeed(hub->hdev)) {
need_debounce_delay = true;
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_BH_PORT_RESET);
}
/* We can forget about a "removed" device when there's a
* physical disconnect or the connect status changes.
*/
if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
(portchange & USB_PORT_STAT_C_CONNECTION))
clear_bit(port1, hub->removed_bits);
if (!udev || udev->state == USB_STATE_NOTATTACHED) {
/* Tell hub_wq to disconnect the device or
* check for a new connection
*/
if (udev || (portstatus & USB_PORT_STAT_CONNECTION) ||
(portstatus & USB_PORT_STAT_OVERCURRENT))
set_bit(port1, hub->change_bits);
} else if (portstatus & USB_PORT_STAT_ENABLE) {
bool port_resumed = (portstatus &
USB_PORT_STAT_LINK_STATE) ==
USB_SS_PORT_LS_U0;
/* The power session apparently survived the resume.
* If there was an overcurrent or suspend change
* (i.e., remote wakeup request), have hub_wq
* take care of it. Look at the port link state
* for USB 3.0 hubs, since they don't have a suspend
* change bit, and they don't set the port link change
* bit on device-initiated resume.
*/
if (portchange || (hub_is_superspeed(hub->hdev) &&
port_resumed))
set_bit(port1, hub->change_bits);
} else if (udev->persist_enabled) {
#ifdef CONFIG_PM
udev->reset_resume = 1;
#endif
/* Don't set the change_bits when the device
* was powered off.
*/
if (test_bit(port1, hub->power_bits))
set_bit(port1, hub->change_bits);
} else {
/* The power session is gone; tell hub_wq */
usb_set_device_state(udev, USB_STATE_NOTATTACHED);
set_bit(port1, hub->change_bits);
}
}
/* If no port-status-change flags were set, we don't need any
* debouncing. If flags were set we can try to debounce the
* ports all at once right now, instead of letting hub_wq do them
* one at a time later on.
*
* If any port-status changes do occur during this delay, hub_wq
* will see them later and handle them normally.
*/
if (need_debounce_delay) {
delay = HUB_DEBOUNCE_STABLE;
/* Don't do a long sleep inside a workqueue routine */
if (type == HUB_INIT2) {
INIT_DELAYED_WORK(&hub->init_work, hub_init_func3);
queue_delayed_work(system_power_efficient_wq,
&hub->init_work,
msecs_to_jiffies(delay));
return; /* Continues at init3: below */
} else {
msleep(delay);
}
}
init3:
hub->quiescing = 0;
status = usb_submit_urb(hub->urb, GFP_NOIO);
if (status < 0)
dev_err(hub->intfdev, "activate --> %d\n", status);
if (hub->has_indicators && blinkenlights)
queue_delayed_work(system_power_efficient_wq,
&hub->leds, LED_CYCLE_PERIOD);
/* Scan all ports that need attention */
kick_hub_wq(hub);
/* Allow autosuspend if it was suppressed */
if (type <= HUB_INIT3)
usb_autopm_put_interface_async(to_usb_interface(hub->intfdev));
}
Commit Message: USB: fix invalid memory access in hub_activate()
Commit 8520f38099cc ("USB: change hub initialization sleeps to
delayed_work") changed the hub_activate() routine to make part of it
run in a workqueue. However, the commit failed to take a reference to
the usb_hub structure or to lock the hub interface while doing so. As
a result, if a hub is plugged in and quickly unplugged before the work
routine can run, the routine will try to access memory that has been
deallocated. Or, if the hub is unplugged while the routine is
running, the memory may be deallocated while it is in active use.
This patch fixes the problem by taking a reference to the usb_hub at
the start of hub_activate() and releasing it at the end (when the work
is finished), and by locking the hub interface while the work routine
is running. It also adds a check at the start of the routine to see
if the hub has already been disconnected, in which nothing should be
done.
Signed-off-by: Alan Stern <[email protected]>
Reported-by: Alexandru Cornea <[email protected]>
Tested-by: Alexandru Cornea <[email protected]>
Fixes: 8520f38099cc ("USB: change hub initialization sleeps to delayed_work")
CC: <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID:
|
static void hub_activate(struct usb_hub *hub, enum hub_activation_type type)
{
struct usb_device *hdev = hub->hdev;
struct usb_hcd *hcd;
int ret;
int port1;
int status;
bool need_debounce_delay = false;
unsigned delay;
/* Continue a partial initialization */
if (type == HUB_INIT2 || type == HUB_INIT3) {
device_lock(hub->intfdev);
/* Was the hub disconnected while we were waiting? */
if (hub->disconnected) {
device_unlock(hub->intfdev);
kref_put(&hub->kref, hub_release);
return;
}
if (type == HUB_INIT2)
goto init2;
goto init3;
}
kref_get(&hub->kref);
/* The superspeed hub except for root hub has to use Hub Depth
* value as an offset into the route string to locate the bits
* it uses to determine the downstream port number. So hub driver
* should send a set hub depth request to superspeed hub after
* the superspeed hub is set configuration in initialization or
* reset procedure.
*
* After a resume, port power should still be on.
* For any other type of activation, turn it on.
*/
if (type != HUB_RESUME) {
if (hdev->parent && hub_is_superspeed(hdev)) {
ret = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
HUB_SET_DEPTH, USB_RT_HUB,
hdev->level - 1, 0, NULL, 0,
USB_CTRL_SET_TIMEOUT);
if (ret < 0)
dev_err(hub->intfdev,
"set hub depth failed\n");
}
/* Speed up system boot by using a delayed_work for the
* hub's initial power-up delays. This is pretty awkward
* and the implementation looks like a home-brewed sort of
* setjmp/longjmp, but it saves at least 100 ms for each
* root hub (assuming usbcore is compiled into the kernel
* rather than as a module). It adds up.
*
* This can't be done for HUB_RESUME or HUB_RESET_RESUME
* because for those activation types the ports have to be
* operational when we return. In theory this could be done
* for HUB_POST_RESET, but it's easier not to.
*/
if (type == HUB_INIT) {
delay = hub_power_on_good_delay(hub);
hub_power_on(hub, false);
INIT_DELAYED_WORK(&hub->init_work, hub_init_func2);
queue_delayed_work(system_power_efficient_wq,
&hub->init_work,
msecs_to_jiffies(delay));
/* Suppress autosuspend until init is done */
usb_autopm_get_interface_no_resume(
to_usb_interface(hub->intfdev));
return; /* Continues at init2: below */
} else if (type == HUB_RESET_RESUME) {
/* The internal host controller state for the hub device
* may be gone after a host power loss on system resume.
* Update the device's info so the HW knows it's a hub.
*/
hcd = bus_to_hcd(hdev->bus);
if (hcd->driver->update_hub_device) {
ret = hcd->driver->update_hub_device(hcd, hdev,
&hub->tt, GFP_NOIO);
if (ret < 0) {
dev_err(hub->intfdev, "Host not "
"accepting hub info "
"update.\n");
dev_err(hub->intfdev, "LS/FS devices "
"and hubs may not work "
"under this hub\n.");
}
}
hub_power_on(hub, true);
} else {
hub_power_on(hub, true);
}
}
init2:
/*
* Check each port and set hub->change_bits to let hub_wq know
* which ports need attention.
*/
for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
struct usb_port *port_dev = hub->ports[port1 - 1];
struct usb_device *udev = port_dev->child;
u16 portstatus, portchange;
portstatus = portchange = 0;
status = hub_port_status(hub, port1, &portstatus, &portchange);
if (udev || (portstatus & USB_PORT_STAT_CONNECTION))
dev_dbg(&port_dev->dev, "status %04x change %04x\n",
portstatus, portchange);
/*
* After anything other than HUB_RESUME (i.e., initialization
* or any sort of reset), every port should be disabled.
* Unconnected ports should likewise be disabled (paranoia),
* and so should ports for which we have no usb_device.
*/
if ((portstatus & USB_PORT_STAT_ENABLE) && (
type != HUB_RESUME ||
!(portstatus & USB_PORT_STAT_CONNECTION) ||
!udev ||
udev->state == USB_STATE_NOTATTACHED)) {
/*
* USB3 protocol ports will automatically transition
* to Enabled state when detect an USB3.0 device attach.
* Do not disable USB3 protocol ports, just pretend
* power was lost
*/
portstatus &= ~USB_PORT_STAT_ENABLE;
if (!hub_is_superspeed(hdev))
usb_clear_port_feature(hdev, port1,
USB_PORT_FEAT_ENABLE);
}
/* Clear status-change flags; we'll debounce later */
if (portchange & USB_PORT_STAT_C_CONNECTION) {
need_debounce_delay = true;
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_CONNECTION);
}
if (portchange & USB_PORT_STAT_C_ENABLE) {
need_debounce_delay = true;
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_ENABLE);
}
if (portchange & USB_PORT_STAT_C_RESET) {
need_debounce_delay = true;
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_RESET);
}
if ((portchange & USB_PORT_STAT_C_BH_RESET) &&
hub_is_superspeed(hub->hdev)) {
need_debounce_delay = true;
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_BH_PORT_RESET);
}
/* We can forget about a "removed" device when there's a
* physical disconnect or the connect status changes.
*/
if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
(portchange & USB_PORT_STAT_C_CONNECTION))
clear_bit(port1, hub->removed_bits);
if (!udev || udev->state == USB_STATE_NOTATTACHED) {
/* Tell hub_wq to disconnect the device or
* check for a new connection
*/
if (udev || (portstatus & USB_PORT_STAT_CONNECTION) ||
(portstatus & USB_PORT_STAT_OVERCURRENT))
set_bit(port1, hub->change_bits);
} else if (portstatus & USB_PORT_STAT_ENABLE) {
bool port_resumed = (portstatus &
USB_PORT_STAT_LINK_STATE) ==
USB_SS_PORT_LS_U0;
/* The power session apparently survived the resume.
* If there was an overcurrent or suspend change
* (i.e., remote wakeup request), have hub_wq
* take care of it. Look at the port link state
* for USB 3.0 hubs, since they don't have a suspend
* change bit, and they don't set the port link change
* bit on device-initiated resume.
*/
if (portchange || (hub_is_superspeed(hub->hdev) &&
port_resumed))
set_bit(port1, hub->change_bits);
} else if (udev->persist_enabled) {
#ifdef CONFIG_PM
udev->reset_resume = 1;
#endif
/* Don't set the change_bits when the device
* was powered off.
*/
if (test_bit(port1, hub->power_bits))
set_bit(port1, hub->change_bits);
} else {
/* The power session is gone; tell hub_wq */
usb_set_device_state(udev, USB_STATE_NOTATTACHED);
set_bit(port1, hub->change_bits);
}
}
/* If no port-status-change flags were set, we don't need any
* debouncing. If flags were set we can try to debounce the
* ports all at once right now, instead of letting hub_wq do them
* one at a time later on.
*
* If any port-status changes do occur during this delay, hub_wq
* will see them later and handle them normally.
*/
if (need_debounce_delay) {
delay = HUB_DEBOUNCE_STABLE;
/* Don't do a long sleep inside a workqueue routine */
if (type == HUB_INIT2) {
INIT_DELAYED_WORK(&hub->init_work, hub_init_func3);
queue_delayed_work(system_power_efficient_wq,
&hub->init_work,
msecs_to_jiffies(delay));
device_unlock(hub->intfdev);
return; /* Continues at init3: below */
} else {
msleep(delay);
}
}
init3:
hub->quiescing = 0;
status = usb_submit_urb(hub->urb, GFP_NOIO);
if (status < 0)
dev_err(hub->intfdev, "activate --> %d\n", status);
if (hub->has_indicators && blinkenlights)
queue_delayed_work(system_power_efficient_wq,
&hub->leds, LED_CYCLE_PERIOD);
/* Scan all ports that need attention */
kick_hub_wq(hub);
/* Allow autosuspend if it was suppressed */
if (type <= HUB_INIT3)
usb_autopm_put_interface_async(to_usb_interface(hub->intfdev));
if (type == HUB_INIT2 || type == HUB_INIT3)
device_unlock(hub->intfdev);
kref_put(&hub->kref, hub_release);
}
| 167,494 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int virtnet_probe(struct virtio_device *vdev)
{
int i, err;
struct net_device *dev;
struct virtnet_info *vi;
u16 max_queue_pairs;
if (!vdev->config->get) {
dev_err(&vdev->dev, "%s failure: config access disabled\n",
__func__);
return -EINVAL;
}
if (!virtnet_validate_features(vdev))
return -EINVAL;
/* Find if host supports multiqueue virtio_net device */
err = virtio_cread_feature(vdev, VIRTIO_NET_F_MQ,
struct virtio_net_config,
max_virtqueue_pairs, &max_queue_pairs);
/* We need at least 2 queue's */
if (err || max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
max_queue_pairs = 1;
/* Allocate ourselves a network device with room for our info */
dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
if (!dev)
return -ENOMEM;
/* Set up network device as normal. */
dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE;
dev->netdev_ops = &virtnet_netdev;
dev->features = NETIF_F_HIGHDMA;
dev->ethtool_ops = &virtnet_ethtool_ops;
SET_NETDEV_DEV(dev, &vdev->dev);
/* Do we support "hardware" checksums? */
if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
/* This opens up the world of extra features. */
dev->hw_features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST;
if (csum)
dev->features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST;
if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
dev->hw_features |= NETIF_F_TSO | NETIF_F_UFO
| NETIF_F_TSO_ECN | NETIF_F_TSO6;
}
/* Individual feature bits: what can host handle? */
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
dev->hw_features |= NETIF_F_TSO;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
dev->hw_features |= NETIF_F_TSO6;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
dev->hw_features |= NETIF_F_TSO_ECN;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_UFO))
dev->hw_features |= NETIF_F_UFO;
dev->features |= NETIF_F_GSO_ROBUST;
if (gso)
dev->features |= dev->hw_features & (NETIF_F_ALL_TSO|NETIF_F_UFO);
/* (!csum && gso) case will be fixed by register_netdev() */
}
if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
dev->features |= NETIF_F_RXCSUM;
dev->vlan_features = dev->features;
/* Configuration may specify what MAC to use. Otherwise random. */
if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC))
virtio_cread_bytes(vdev,
offsetof(struct virtio_net_config, mac),
dev->dev_addr, dev->addr_len);
else
eth_hw_addr_random(dev);
/* Set up our device-specific information */
vi = netdev_priv(dev);
vi->dev = dev;
vi->vdev = vdev;
vdev->priv = vi;
vi->stats = alloc_percpu(struct virtnet_stats);
err = -ENOMEM;
if (vi->stats == NULL)
goto free;
for_each_possible_cpu(i) {
struct virtnet_stats *virtnet_stats;
virtnet_stats = per_cpu_ptr(vi->stats, i);
u64_stats_init(&virtnet_stats->tx_syncp);
u64_stats_init(&virtnet_stats->rx_syncp);
}
INIT_WORK(&vi->config_work, virtnet_config_changed_work);
/* If we can receive ANY GSO packets, we must allocate large ones. */
if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_UFO))
vi->big_packets = true;
if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
vi->mergeable_rx_bufs = true;
if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
else
vi->hdr_len = sizeof(struct virtio_net_hdr);
if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
vi->any_header_sg = true;
if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
vi->has_cvq = true;
if (vi->any_header_sg)
dev->needed_headroom = vi->hdr_len;
/* Use single tx/rx queue pair as default */
vi->curr_queue_pairs = 1;
vi->max_queue_pairs = max_queue_pairs;
/* Allocate/initialize the rx/tx queues, and invoke find_vqs */
err = init_vqs(vi);
if (err)
goto free_stats;
#ifdef CONFIG_SYSFS
if (vi->mergeable_rx_bufs)
dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
#endif
netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
err = register_netdev(dev);
if (err) {
pr_debug("virtio_net: registering device failed\n");
goto free_vqs;
}
virtio_device_ready(vdev);
/* Last of all, set up some receive buffers. */
for (i = 0; i < vi->curr_queue_pairs; i++) {
try_fill_recv(vi, &vi->rq[i], GFP_KERNEL);
/* If we didn't even get one input buffer, we're useless. */
if (vi->rq[i].vq->num_free ==
virtqueue_get_vring_size(vi->rq[i].vq)) {
free_unused_bufs(vi);
err = -ENOMEM;
goto free_recv_bufs;
}
}
vi->nb.notifier_call = &virtnet_cpu_callback;
err = register_hotcpu_notifier(&vi->nb);
if (err) {
pr_debug("virtio_net: registering cpu notifier failed\n");
goto free_recv_bufs;
}
/* Assume link up if device can't report link status,
otherwise get link status from config. */
if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
netif_carrier_off(dev);
schedule_work(&vi->config_work);
} else {
vi->status = VIRTIO_NET_S_LINK_UP;
netif_carrier_on(dev);
}
pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
dev->name, max_queue_pairs);
return 0;
free_recv_bufs:
vi->vdev->config->reset(vdev);
free_receive_bufs(vi);
unregister_netdev(dev);
free_vqs:
cancel_delayed_work_sync(&vi->refill);
free_receive_page_frags(vi);
virtnet_del_vqs(vi);
free_stats:
free_percpu(vi->stats);
free:
free_netdev(dev);
return err;
}
Commit Message: virtio-net: drop NETIF_F_FRAGLIST
virtio declares support for NETIF_F_FRAGLIST, but assumes
that there are at most MAX_SKB_FRAGS + 2 fragments which isn't
always true with a fraglist.
A longer fraglist in the skb will make the call to skb_to_sgvec overflow
the sg array, leading to memory corruption.
Drop NETIF_F_FRAGLIST so we only get what we can handle.
Cc: Michael S. Tsirkin <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
Acked-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
|
static int virtnet_probe(struct virtio_device *vdev)
{
int i, err;
struct net_device *dev;
struct virtnet_info *vi;
u16 max_queue_pairs;
if (!vdev->config->get) {
dev_err(&vdev->dev, "%s failure: config access disabled\n",
__func__);
return -EINVAL;
}
if (!virtnet_validate_features(vdev))
return -EINVAL;
/* Find if host supports multiqueue virtio_net device */
err = virtio_cread_feature(vdev, VIRTIO_NET_F_MQ,
struct virtio_net_config,
max_virtqueue_pairs, &max_queue_pairs);
/* We need at least 2 queue's */
if (err || max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
max_queue_pairs = 1;
/* Allocate ourselves a network device with room for our info */
dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
if (!dev)
return -ENOMEM;
/* Set up network device as normal. */
dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE;
dev->netdev_ops = &virtnet_netdev;
dev->features = NETIF_F_HIGHDMA;
dev->ethtool_ops = &virtnet_ethtool_ops;
SET_NETDEV_DEV(dev, &vdev->dev);
/* Do we support "hardware" checksums? */
if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
/* This opens up the world of extra features. */
dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
if (csum)
dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
dev->hw_features |= NETIF_F_TSO | NETIF_F_UFO
| NETIF_F_TSO_ECN | NETIF_F_TSO6;
}
/* Individual feature bits: what can host handle? */
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
dev->hw_features |= NETIF_F_TSO;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
dev->hw_features |= NETIF_F_TSO6;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
dev->hw_features |= NETIF_F_TSO_ECN;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_UFO))
dev->hw_features |= NETIF_F_UFO;
dev->features |= NETIF_F_GSO_ROBUST;
if (gso)
dev->features |= dev->hw_features & (NETIF_F_ALL_TSO|NETIF_F_UFO);
/* (!csum && gso) case will be fixed by register_netdev() */
}
if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
dev->features |= NETIF_F_RXCSUM;
dev->vlan_features = dev->features;
/* Configuration may specify what MAC to use. Otherwise random. */
if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC))
virtio_cread_bytes(vdev,
offsetof(struct virtio_net_config, mac),
dev->dev_addr, dev->addr_len);
else
eth_hw_addr_random(dev);
/* Set up our device-specific information */
vi = netdev_priv(dev);
vi->dev = dev;
vi->vdev = vdev;
vdev->priv = vi;
vi->stats = alloc_percpu(struct virtnet_stats);
err = -ENOMEM;
if (vi->stats == NULL)
goto free;
for_each_possible_cpu(i) {
struct virtnet_stats *virtnet_stats;
virtnet_stats = per_cpu_ptr(vi->stats, i);
u64_stats_init(&virtnet_stats->tx_syncp);
u64_stats_init(&virtnet_stats->rx_syncp);
}
INIT_WORK(&vi->config_work, virtnet_config_changed_work);
/* If we can receive ANY GSO packets, we must allocate large ones. */
if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_UFO))
vi->big_packets = true;
if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
vi->mergeable_rx_bufs = true;
if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
else
vi->hdr_len = sizeof(struct virtio_net_hdr);
if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
vi->any_header_sg = true;
if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
vi->has_cvq = true;
if (vi->any_header_sg)
dev->needed_headroom = vi->hdr_len;
/* Use single tx/rx queue pair as default */
vi->curr_queue_pairs = 1;
vi->max_queue_pairs = max_queue_pairs;
/* Allocate/initialize the rx/tx queues, and invoke find_vqs */
err = init_vqs(vi);
if (err)
goto free_stats;
#ifdef CONFIG_SYSFS
if (vi->mergeable_rx_bufs)
dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
#endif
netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
err = register_netdev(dev);
if (err) {
pr_debug("virtio_net: registering device failed\n");
goto free_vqs;
}
virtio_device_ready(vdev);
/* Last of all, set up some receive buffers. */
for (i = 0; i < vi->curr_queue_pairs; i++) {
try_fill_recv(vi, &vi->rq[i], GFP_KERNEL);
/* If we didn't even get one input buffer, we're useless. */
if (vi->rq[i].vq->num_free ==
virtqueue_get_vring_size(vi->rq[i].vq)) {
free_unused_bufs(vi);
err = -ENOMEM;
goto free_recv_bufs;
}
}
vi->nb.notifier_call = &virtnet_cpu_callback;
err = register_hotcpu_notifier(&vi->nb);
if (err) {
pr_debug("virtio_net: registering cpu notifier failed\n");
goto free_recv_bufs;
}
/* Assume link up if device can't report link status,
otherwise get link status from config. */
if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
netif_carrier_off(dev);
schedule_work(&vi->config_work);
} else {
vi->status = VIRTIO_NET_S_LINK_UP;
netif_carrier_on(dev);
}
pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
dev->name, max_queue_pairs);
return 0;
free_recv_bufs:
vi->vdev->config->reset(vdev);
free_receive_bufs(vi);
unregister_netdev(dev);
free_vqs:
cancel_delayed_work_sync(&vi->refill);
free_receive_page_frags(vi);
virtnet_del_vqs(vi);
free_stats:
free_percpu(vi->stats);
free:
free_netdev(dev);
return err;
}
| 166,610 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void GpuProcessHost::DidFailInitialize() {
UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", false);
status_ = FAILURE;
GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
gpu_data_manager->FallBackToNextGpuMode();
RunRequestGPUInfoCallbacks(gpu_data_manager->GetGPUInfo());
}
Commit Message: Fix GPU process fallback logic.
1. In GpuProcessHost::OnProcessCrashed() record the process crash first.
This means the GPU mode fallback will happen before a new GPU process
is started.
2. Don't call FallBackToNextGpuMode() if GPU process initialization
fails for an unsandboxed GPU process. The unsandboxed GPU is only
used for collect information and it's failure doesn't indicate a need
to change GPU modes.
Bug: 869419
Change-Id: I8bd0a03268f0ea8809f3df8458d4e6a92db9391f
Reviewed-on: https://chromium-review.googlesource.com/1157164
Reviewed-by: Zhenyao Mo <[email protected]>
Commit-Queue: kylechar <[email protected]>
Cr-Commit-Position: refs/heads/master@{#579625}
CWE ID:
|
void GpuProcessHost::DidFailInitialize() {
UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", false);
status_ = FAILURE;
GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
if (kind_ == GPU_PROCESS_KIND_SANDBOXED)
gpu_data_manager->FallBackToNextGpuMode();
RunRequestGPUInfoCallbacks(gpu_data_manager->GetGPUInfo());
}
| 172,241 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: my_object_async_increment (MyObject *obj, gint32 x, DBusGMethodInvocation *context)
{
IncrementData *data = g_new0 (IncrementData, 1);
data->x = x;
data->context = context;
g_idle_add ((GSourceFunc)do_async_increment, data);
}
Commit Message:
CWE ID: CWE-264
|
my_object_async_increment (MyObject *obj, gint32 x, DBusGMethodInvocation *context)
| 165,088 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: PHP_FUNCTION(imagepsencodefont)
{
zval *fnt;
char *enc, **enc_vector;
int enc_len, *f_ind;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &fnt, &enc, &enc_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font);
if ((enc_vector = T1_LoadEncoding(enc)) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't load encoding vector from %s", enc);
RETURN_FALSE;
}
T1_DeleteAllSizes(*f_ind);
if (T1_ReencodeFont(*f_ind, enc_vector)) {
T1_DeleteEncoding(enc_vector);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't re-encode font");
RETURN_FALSE;
}
zend_list_insert(enc_vector, le_ps_enc TSRMLS_CC);
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-254
|
PHP_FUNCTION(imagepsencodefont)
{
zval *fnt;
char *enc, **enc_vector;
int enc_len, *f_ind;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rp", &fnt, &enc, &enc_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font);
if ((enc_vector = T1_LoadEncoding(enc)) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't load encoding vector from %s", enc);
RETURN_FALSE;
}
T1_DeleteAllSizes(*f_ind);
if (T1_ReencodeFont(*f_ind, enc_vector)) {
T1_DeleteEncoding(enc_vector);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't re-encode font");
RETURN_FALSE;
}
zend_list_insert(enc_vector, le_ps_enc TSRMLS_CC);
RETURN_TRUE;
}
| 165,312 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool ParamTraits<SkBitmap>::Read(const base::Pickle* m,
base::PickleIterator* iter,
SkBitmap* r) {
const char* fixed_data;
int fixed_data_size = 0;
if (!iter->ReadData(&fixed_data, &fixed_data_size) ||
(fixed_data_size <= 0)) {
return false;
}
if (fixed_data_size != sizeof(SkBitmap_Data))
return false; // Message is malformed.
const char* variable_data;
int variable_data_size = 0;
if (!iter->ReadData(&variable_data, &variable_data_size) ||
(variable_data_size < 0)) {
return false;
}
const SkBitmap_Data* bmp_data =
reinterpret_cast<const SkBitmap_Data*>(fixed_data);
return bmp_data->InitSkBitmapFromData(r, variable_data, variable_data_size);
}
Commit Message: Update IPC ParamTraits for SkBitmap to follow best practices.
Using memcpy() to serialize a POD struct is highly discouraged. Just use
the standard IPC param traits macros for doing it.
Bug: 779428
Change-Id: I48f52c1f5c245ba274d595829ed92e8b3cb41334
Reviewed-on: https://chromium-review.googlesource.com/899649
Reviewed-by: Tom Sepez <[email protected]>
Commit-Queue: Daniel Cheng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#534562}
CWE ID: CWE-125
|
bool ParamTraits<SkBitmap>::Read(const base::Pickle* m,
base::PickleIterator* iter,
SkBitmap* r) {
SkImageInfo image_info;
if (!ReadParam(m, iter, &image_info))
return false;
const char* bitmap_data;
int bitmap_data_size = 0;
if (!iter->ReadData(&bitmap_data, &bitmap_data_size))
return false;
// ReadData() only returns true if bitmap_data_size >= 0.
if (!r->tryAllocPixels(image_info))
return false;
if (static_cast<size_t>(bitmap_data_size) != r->computeByteSize())
return false;
memcpy(r->getPixels(), bitmap_data, bitmap_data_size);
return true;
}
| 172,894 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void copy_asoundrc(void) {
char *src = RUN_ASOUNDRC_FILE ;
char *dest;
if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
drop_privs(0);
int rv = copy_file(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR);
if (rv)
fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
waitpid(child, NULL, 0);
unlink(src);
}
Commit Message: replace copy_file with copy_file_as_user
CWE ID: CWE-269
|
static void copy_asoundrc(void) {
char *src = RUN_ASOUNDRC_FILE ;
char *dest;
if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR);
fs_logger2("clone", dest);
unlink(src);
}
| 170,091 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: sec_recv(RD_BOOL * is_fastpath)
{
uint8 fastpath_hdr, fastpath_flags;
uint16 sec_flags;
uint16 channel;
STREAM s;
while ((s = mcs_recv(&channel, is_fastpath, &fastpath_hdr)) != NULL)
{
if (*is_fastpath == True)
{
/* If fastpath packet is encrypted, read data
signature and decrypt */
/* FIXME: extracting flags from hdr could be made less obscure */
fastpath_flags = (fastpath_hdr & 0xC0) >> 6;
if (fastpath_flags & FASTPATH_OUTPUT_ENCRYPTED)
{
in_uint8s(s, 8); /* signature */
sec_decrypt(s->p, s->end - s->p);
}
return s;
}
if (g_encryption || (!g_licence_issued && !g_licence_error_result))
{
/* TS_SECURITY_HEADER */
in_uint16_le(s, sec_flags);
in_uint8s(s, 2); /* skip sec_flags_hi */
if (g_encryption)
{
if (sec_flags & SEC_ENCRYPT)
{
in_uint8s(s, 8); /* signature */
sec_decrypt(s->p, s->end - s->p);
}
if (sec_flags & SEC_LICENSE_PKT)
{
licence_process(s);
continue;
}
if (sec_flags & SEC_REDIRECTION_PKT)
{
uint8 swapbyte;
in_uint8s(s, 8); /* signature */
sec_decrypt(s->p, s->end - s->p);
/* Check for a redirect packet, starts with 00 04 */
if (s->p[0] == 0 && s->p[1] == 4)
{
/* for some reason the PDU and the length seem to be swapped.
This isn't good, but we're going to do a byte for byte
swap. So the first four value appear as: 00 04 XX YY,
where XX YY is the little endian length. We're going to
use 04 00 as the PDU type, so after our swap this will look
like: XX YY 04 00 */
swapbyte = s->p[0];
s->p[0] = s->p[2];
s->p[2] = swapbyte;
swapbyte = s->p[1];
s->p[1] = s->p[3];
s->p[3] = swapbyte;
swapbyte = s->p[2];
s->p[2] = s->p[3];
s->p[3] = swapbyte;
}
}
}
else
{
if (sec_flags & SEC_LICENSE_PKT)
{
licence_process(s);
continue;
}
s->p -= 4;
}
}
if (channel != MCS_GLOBAL_CHANNEL)
{
channel_process(s, channel);
continue;
}
return s;
}
return NULL;
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119
|
sec_recv(RD_BOOL * is_fastpath)
{
uint8 fastpath_hdr, fastpath_flags;
uint16 sec_flags;
uint16 channel;
STREAM s;
struct stream packet;
while ((s = mcs_recv(&channel, is_fastpath, &fastpath_hdr)) != NULL)
{
packet = *s;
if (*is_fastpath == True)
{
/* If fastpath packet is encrypted, read data
signature and decrypt */
/* FIXME: extracting flags from hdr could be made less obscure */
fastpath_flags = (fastpath_hdr & 0xC0) >> 6;
if (fastpath_flags & FASTPATH_OUTPUT_ENCRYPTED)
{
if (!s_check_rem(s, 8)) {
rdp_protocol_error("sec_recv(), consume fastpath signature from stream would overrun", &packet);
}
in_uint8s(s, 8); /* signature */
sec_decrypt(s->p, s->end - s->p);
}
return s;
}
if (g_encryption || (!g_licence_issued && !g_licence_error_result))
{
/* TS_SECURITY_HEADER */
in_uint16_le(s, sec_flags);
in_uint8s(s, 2); /* skip sec_flags_hi */
if (g_encryption)
{
if (sec_flags & SEC_ENCRYPT)
{
if (!s_check_rem(s, 8)) {
rdp_protocol_error("sec_recv(), consume encrypt signature from stream would overrun", &packet);
}
in_uint8s(s, 8); /* signature */
sec_decrypt(s->p, s->end - s->p);
}
if (sec_flags & SEC_LICENSE_PKT)
{
licence_process(s);
continue;
}
if (sec_flags & SEC_REDIRECTION_PKT)
{
uint8 swapbyte;
if (!s_check_rem(s, 8)) {
rdp_protocol_error("sec_recv(), consume redirect signature from stream would overrun", &packet);
}
in_uint8s(s, 8); /* signature */
sec_decrypt(s->p, s->end - s->p);
/* Check for a redirect packet, starts with 00 04 */
if (s->p[0] == 0 && s->p[1] == 4)
{
/* for some reason the PDU and the length seem to be swapped.
This isn't good, but we're going to do a byte for byte
swap. So the first four value appear as: 00 04 XX YY,
where XX YY is the little endian length. We're going to
use 04 00 as the PDU type, so after our swap this will look
like: XX YY 04 00 */
swapbyte = s->p[0];
s->p[0] = s->p[2];
s->p[2] = swapbyte;
swapbyte = s->p[1];
s->p[1] = s->p[3];
s->p[3] = swapbyte;
swapbyte = s->p[2];
s->p[2] = s->p[3];
s->p[3] = swapbyte;
}
}
}
else
{
if (sec_flags & SEC_LICENSE_PKT)
{
licence_process(s);
continue;
}
s->p -= 4;
}
}
if (channel != MCS_GLOBAL_CHANNEL)
{
channel_process(s, channel);
continue;
}
return s;
}
return NULL;
}
| 169,811 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: seamless_process_line(const char *line, void *data)
{
UNUSED(data);
char *p, *l;
char *tok1, *tok3, *tok4, *tok5, *tok6, *tok7, *tok8;
unsigned long id, flags;
char *endptr;
l = xstrdup(line);
p = l;
logger(Core, Debug, "seamless_process_line(), got '%s'", p);
tok1 = seamless_get_token(&p);
(void) seamless_get_token(&p);
tok3 = seamless_get_token(&p);
tok4 = seamless_get_token(&p);
tok5 = seamless_get_token(&p);
tok6 = seamless_get_token(&p);
tok7 = seamless_get_token(&p);
tok8 = seamless_get_token(&p);
if (!strcmp("CREATE", tok1))
{
unsigned long group, parent;
if (!tok6)
return False;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
group = strtoul(tok4, &endptr, 0);
if (*endptr)
return False;
parent = strtoul(tok5, &endptr, 0);
if (*endptr)
return False;
flags = strtoul(tok6, &endptr, 0);
if (*endptr)
return False;
ui_seamless_create_window(id, group, parent, flags);
}
else if (!strcmp("DESTROY", tok1))
{
if (!tok4)
return False;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
flags = strtoul(tok4, &endptr, 0);
if (*endptr)
return False;
ui_seamless_destroy_window(id, flags);
}
else if (!strcmp("DESTROYGRP", tok1))
{
if (!tok4)
return False;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
flags = strtoul(tok4, &endptr, 0);
if (*endptr)
return False;
ui_seamless_destroy_group(id, flags);
}
else if (!strcmp("SETICON", tok1))
{
int chunk, width, height, len;
char byte[3];
if (!tok8)
return False;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
chunk = strtoul(tok4, &endptr, 0);
if (*endptr)
return False;
width = strtoul(tok6, &endptr, 0);
if (*endptr)
return False;
height = strtoul(tok7, &endptr, 0);
if (*endptr)
return False;
byte[2] = '\0';
len = 0;
while (*tok8 != '\0')
{
byte[0] = *tok8;
tok8++;
if (*tok8 == '\0')
return False;
byte[1] = *tok8;
tok8++;
icon_buf[len] = strtol(byte, NULL, 16);
len++;
}
ui_seamless_seticon(id, tok5, width, height, chunk, icon_buf, len);
}
else if (!strcmp("DELICON", tok1))
{
int width, height;
if (!tok6)
return False;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
width = strtoul(tok5, &endptr, 0);
if (*endptr)
return False;
height = strtoul(tok6, &endptr, 0);
if (*endptr)
return False;
ui_seamless_delicon(id, tok4, width, height);
}
else if (!strcmp("POSITION", tok1))
{
int x, y, width, height;
if (!tok8)
return False;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
x = strtol(tok4, &endptr, 0);
if (*endptr)
return False;
y = strtol(tok5, &endptr, 0);
if (*endptr)
return False;
width = strtol(tok6, &endptr, 0);
if (*endptr)
return False;
height = strtol(tok7, &endptr, 0);
if (*endptr)
return False;
flags = strtoul(tok8, &endptr, 0);
if (*endptr)
return False;
ui_seamless_move_window(id, x, y, width, height, flags);
}
else if (!strcmp("ZCHANGE", tok1))
{
unsigned long behind;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
behind = strtoul(tok4, &endptr, 0);
if (*endptr)
return False;
flags = strtoul(tok5, &endptr, 0);
if (*endptr)
return False;
ui_seamless_restack_window(id, behind, flags);
}
else if (!strcmp("TITLE", tok1))
{
if (!tok5)
return False;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
flags = strtoul(tok5, &endptr, 0);
if (*endptr)
return False;
ui_seamless_settitle(id, tok4, flags);
}
else if (!strcmp("STATE", tok1))
{
unsigned int state;
if (!tok5)
return False;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
state = strtoul(tok4, &endptr, 0);
if (*endptr)
return False;
flags = strtoul(tok5, &endptr, 0);
if (*endptr)
return False;
ui_seamless_setstate(id, state, flags);
}
else if (!strcmp("DEBUG", tok1))
{
logger(Core, Debug, "seamless_process_line(), %s", line);
}
else if (!strcmp("SYNCBEGIN", tok1))
{
if (!tok3)
return False;
flags = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
ui_seamless_syncbegin(flags);
}
else if (!strcmp("SYNCEND", tok1))
{
if (!tok3)
return False;
flags = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
/* do nothing, currently */
}
else if (!strcmp("HELLO", tok1))
{
if (!tok3)
return False;
flags = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
ui_seamless_begin(! !(flags & SEAMLESSRDP_HELLO_HIDDEN));
}
else if (!strcmp("ACK", tok1))
{
unsigned int serial;
serial = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
ui_seamless_ack(serial);
}
else if (!strcmp("HIDE", tok1))
{
if (!tok3)
return False;
flags = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
ui_seamless_hide_desktop();
}
else if (!strcmp("UNHIDE", tok1))
{
if (!tok3)
return False;
flags = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
ui_seamless_unhide_desktop();
}
xfree(l);
return True;
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119
|
seamless_process_line(const char *line, void *data)
{
UNUSED(data);
char *p, *l;
char *tok1, *tok3, *tok4, *tok5, *tok6, *tok7, *tok8;
unsigned long id, flags;
char *endptr;
l = xstrdup(line);
p = l;
logger(Core, Debug, "seamless_process_line(), got '%s'", p);
tok1 = seamless_get_token(&p);
(void) seamless_get_token(&p);
tok3 = seamless_get_token(&p);
tok4 = seamless_get_token(&p);
tok5 = seamless_get_token(&p);
tok6 = seamless_get_token(&p);
tok7 = seamless_get_token(&p);
tok8 = seamless_get_token(&p);
if (!strcmp("CREATE", tok1))
{
unsigned long group, parent;
if (!tok6)
return False;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
group = strtoul(tok4, &endptr, 0);
if (*endptr)
return False;
parent = strtoul(tok5, &endptr, 0);
if (*endptr)
return False;
flags = strtoul(tok6, &endptr, 0);
if (*endptr)
return False;
ui_seamless_create_window(id, group, parent, flags);
}
else if (!strcmp("DESTROY", tok1))
{
if (!tok4)
return False;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
flags = strtoul(tok4, &endptr, 0);
if (*endptr)
return False;
ui_seamless_destroy_window(id, flags);
}
else if (!strcmp("DESTROYGRP", tok1))
{
if (!tok4)
return False;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
flags = strtoul(tok4, &endptr, 0);
if (*endptr)
return False;
ui_seamless_destroy_group(id, flags);
}
else if (!strcmp("SETICON", tok1))
{
int chunk, width, height, len;
char byte[3];
if (!tok8)
return False;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
chunk = strtoul(tok4, &endptr, 0);
if (*endptr)
return False;
width = strtoul(tok6, &endptr, 0);
if (*endptr)
return False;
height = strtoul(tok7, &endptr, 0);
if (*endptr)
return False;
byte[2] = '\0';
len = 0;
while (*tok8 != '\0')
{
byte[0] = *tok8;
tok8++;
if (*tok8 == '\0')
return False;
byte[1] = *tok8;
tok8++;
icon_buf[len] = strtol(byte, NULL, 16);
len++;
if ((size_t)len >= sizeof(icon_buf))
{
logger(Protocol, Warning, "seamless_process_line(), icon data would overrun icon_buf");
break;
}
}
ui_seamless_seticon(id, tok5, width, height, chunk, icon_buf, len);
}
else if (!strcmp("DELICON", tok1))
{
int width, height;
if (!tok6)
return False;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
width = strtoul(tok5, &endptr, 0);
if (*endptr)
return False;
height = strtoul(tok6, &endptr, 0);
if (*endptr)
return False;
ui_seamless_delicon(id, tok4, width, height);
}
else if (!strcmp("POSITION", tok1))
{
int x, y, width, height;
if (!tok8)
return False;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
x = strtol(tok4, &endptr, 0);
if (*endptr)
return False;
y = strtol(tok5, &endptr, 0);
if (*endptr)
return False;
width = strtol(tok6, &endptr, 0);
if (*endptr)
return False;
height = strtol(tok7, &endptr, 0);
if (*endptr)
return False;
flags = strtoul(tok8, &endptr, 0);
if (*endptr)
return False;
ui_seamless_move_window(id, x, y, width, height, flags);
}
else if (!strcmp("ZCHANGE", tok1))
{
unsigned long behind;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
behind = strtoul(tok4, &endptr, 0);
if (*endptr)
return False;
flags = strtoul(tok5, &endptr, 0);
if (*endptr)
return False;
ui_seamless_restack_window(id, behind, flags);
}
else if (!strcmp("TITLE", tok1))
{
if (!tok5)
return False;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
flags = strtoul(tok5, &endptr, 0);
if (*endptr)
return False;
ui_seamless_settitle(id, tok4, flags);
}
else if (!strcmp("STATE", tok1))
{
unsigned int state;
if (!tok5)
return False;
id = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
state = strtoul(tok4, &endptr, 0);
if (*endptr)
return False;
flags = strtoul(tok5, &endptr, 0);
if (*endptr)
return False;
ui_seamless_setstate(id, state, flags);
}
else if (!strcmp("DEBUG", tok1))
{
logger(Core, Debug, "seamless_process_line(), %s", line);
}
else if (!strcmp("SYNCBEGIN", tok1))
{
if (!tok3)
return False;
flags = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
ui_seamless_syncbegin(flags);
}
else if (!strcmp("SYNCEND", tok1))
{
if (!tok3)
return False;
flags = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
/* do nothing, currently */
}
else if (!strcmp("HELLO", tok1))
{
if (!tok3)
return False;
flags = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
ui_seamless_begin(! !(flags & SEAMLESSRDP_HELLO_HIDDEN));
}
else if (!strcmp("ACK", tok1))
{
unsigned int serial;
serial = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
ui_seamless_ack(serial);
}
else if (!strcmp("HIDE", tok1))
{
if (!tok3)
return False;
flags = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
ui_seamless_hide_desktop();
}
else if (!strcmp("UNHIDE", tok1))
{
if (!tok3)
return False;
flags = strtoul(tok3, &endptr, 0);
if (*endptr)
return False;
ui_seamless_unhide_desktop();
}
xfree(l);
return True;
}
| 169,809 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: varbit_in(PG_FUNCTION_ARGS)
{
char *input_string = PG_GETARG_CSTRING(0);
#ifdef NOT_USED
Oid typelem = PG_GETARG_OID(1);
#endif
int32 atttypmod = PG_GETARG_INT32(2);
VarBit *result; /* The resulting bit string */
char *sp; /* pointer into the character string */
bits8 *r; /* pointer into the result */
int len, /* Length of the whole data structure */
bitlen, /* Number of bits in the bit string */
slen; /* Length of the input string */
bool bit_not_hex; /* false = hex string true = bit string */
int bc;
bits8 x = 0;
/* Check that the first character is a b or an x */
if (input_string[0] == 'b' || input_string[0] == 'B')
{
bit_not_hex = true;
sp = input_string + 1;
}
else if (input_string[0] == 'x' || input_string[0] == 'X')
{
bit_not_hex = false;
sp = input_string + 1;
}
else
{
bit_not_hex = true;
sp = input_string;
}
slen = strlen(sp);
/* Determine bitlength from input string */
if (bit_not_hex)
bitlen = slen;
else
bitlen = slen * 4;
/*
* Sometimes atttypmod is not supplied. If it is supplied we need to make
* sure that the bitstring fits.
*/
if (atttypmod <= 0)
atttypmod = bitlen;
else if (bitlen > atttypmod)
ereport(ERROR,
(errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),
errmsg("bit string too long for type bit varying(%d)",
atttypmod)));
len = VARBITTOTALLEN(bitlen);
/* set to 0 so that *r is always initialised and string is zero-padded */
result = (VarBit *) palloc0(len);
SET_VARSIZE(result, len);
VARBITLEN(result) = Min(bitlen, atttypmod);
r = VARBITS(result);
if (bit_not_hex)
{
/* Parse the bit representation of the string */
/* We know it fits, as bitlen was compared to atttypmod */
x = HIGHBIT;
for (; *sp; sp++)
{
if (*sp == '1')
*r |= x;
else if (*sp != '0')
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("\"%c\" is not a valid binary digit",
*sp)));
x >>= 1;
if (x == 0)
{
x = HIGHBIT;
r++;
}
}
}
else
{
/* Parse the hex representation of the string */
for (bc = 0; *sp; sp++)
{
if (*sp >= '0' && *sp <= '9')
x = (bits8) (*sp - '0');
else if (*sp >= 'A' && *sp <= 'F')
x = (bits8) (*sp - 'A') + 10;
else if (*sp >= 'a' && *sp <= 'f')
x = (bits8) (*sp - 'a') + 10;
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("\"%c\" is not a valid hexadecimal digit",
*sp)));
if (bc)
{
*r++ |= x;
bc = 0;
}
else
{
*r = x << 4;
bc = 1;
}
}
}
PG_RETURN_VARBIT_P(result);
}
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
|
varbit_in(PG_FUNCTION_ARGS)
{
char *input_string = PG_GETARG_CSTRING(0);
#ifdef NOT_USED
Oid typelem = PG_GETARG_OID(1);
#endif
int32 atttypmod = PG_GETARG_INT32(2);
VarBit *result; /* The resulting bit string */
char *sp; /* pointer into the character string */
bits8 *r; /* pointer into the result */
int len, /* Length of the whole data structure */
bitlen, /* Number of bits in the bit string */
slen; /* Length of the input string */
bool bit_not_hex; /* false = hex string true = bit string */
int bc;
bits8 x = 0;
/* Check that the first character is a b or an x */
if (input_string[0] == 'b' || input_string[0] == 'B')
{
bit_not_hex = true;
sp = input_string + 1;
}
else if (input_string[0] == 'x' || input_string[0] == 'X')
{
bit_not_hex = false;
sp = input_string + 1;
}
else
{
bit_not_hex = true;
sp = input_string;
}
/*
* Determine bitlength from input string. MaxAllocSize ensures a regular
* input is small enough, but we must check hex input.
*/
slen = strlen(sp);
if (bit_not_hex)
bitlen = slen;
else
{
if (slen > VARBITMAXLEN / 4)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("bit string length exceeds the maximum allowed (%d)",
VARBITMAXLEN)));
bitlen = slen * 4;
}
/*
* Sometimes atttypmod is not supplied. If it is supplied we need to make
* sure that the bitstring fits.
*/
if (atttypmod <= 0)
atttypmod = bitlen;
else if (bitlen > atttypmod)
ereport(ERROR,
(errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),
errmsg("bit string too long for type bit varying(%d)",
atttypmod)));
len = VARBITTOTALLEN(bitlen);
/* set to 0 so that *r is always initialised and string is zero-padded */
result = (VarBit *) palloc0(len);
SET_VARSIZE(result, len);
VARBITLEN(result) = Min(bitlen, atttypmod);
r = VARBITS(result);
if (bit_not_hex)
{
/* Parse the bit representation of the string */
/* We know it fits, as bitlen was compared to atttypmod */
x = HIGHBIT;
for (; *sp; sp++)
{
if (*sp == '1')
*r |= x;
else if (*sp != '0')
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("\"%c\" is not a valid binary digit",
*sp)));
x >>= 1;
if (x == 0)
{
x = HIGHBIT;
r++;
}
}
}
else
{
/* Parse the hex representation of the string */
for (bc = 0; *sp; sp++)
{
if (*sp >= '0' && *sp <= '9')
x = (bits8) (*sp - '0');
else if (*sp >= 'A' && *sp <= 'F')
x = (bits8) (*sp - 'A') + 10;
else if (*sp >= 'a' && *sp <= 'f')
x = (bits8) (*sp - 'a') + 10;
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("\"%c\" is not a valid hexadecimal digit",
*sp)));
if (bc)
{
*r++ |= x;
bc = 0;
}
else
{
*r = x << 4;
bc = 1;
}
}
}
PG_RETURN_VARBIT_P(result);
}
| 166,419 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ShellWindowFrameView::Init(views::Widget* frame) {
frame_ = frame;
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
close_button_ = new views::ImageButton(this);
close_button_->SetImage(views::CustomButton::BS_NORMAL,
rb.GetNativeImageNamed(IDR_CLOSE_BAR).ToImageSkia());
close_button_->SetImage(views::CustomButton::BS_HOT,
rb.GetNativeImageNamed(IDR_CLOSE_BAR_H).ToImageSkia());
close_button_->SetImage(views::CustomButton::BS_PUSHED,
rb.GetNativeImageNamed(IDR_CLOSE_BAR_P).ToImageSkia());
close_button_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_APP_ACCNAME_CLOSE));
AddChildView(close_button_);
#if defined(USE_ASH)
aura::Window* window = frame->GetNativeWindow();
int outside_bounds = ui::GetDisplayLayout() == ui::LAYOUT_TOUCH ?
kResizeOutsideBoundsSizeTouch :
kResizeOutsideBoundsSize;
window->set_hit_test_bounds_override_outer(
gfx::Insets(-outside_bounds, -outside_bounds,
-outside_bounds, -outside_bounds));
window->set_hit_test_bounds_override_inner(
gfx::Insets(kResizeInsideBoundsSize, kResizeInsideBoundsSize,
kResizeInsideBoundsSize, kResizeInsideBoundsSize));
#endif
}
Commit Message: [views] Remove header bar on shell windows created with {frame: none}.
BUG=130182
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10597003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79
|
void ShellWindowFrameView::Init(views::Widget* frame) {
frame_ = frame;
if (!is_frameless_) {
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
close_button_ = new views::ImageButton(this);
close_button_->SetImage(views::CustomButton::BS_NORMAL,
rb.GetNativeImageNamed(IDR_CLOSE_BAR).ToImageSkia());
close_button_->SetImage(views::CustomButton::BS_HOT,
rb.GetNativeImageNamed(IDR_CLOSE_BAR_H).ToImageSkia());
close_button_->SetImage(views::CustomButton::BS_PUSHED,
rb.GetNativeImageNamed(IDR_CLOSE_BAR_P).ToImageSkia());
close_button_->SetAccessibleName(
l10n_util::GetStringUTF16(IDS_APP_ACCNAME_CLOSE));
AddChildView(close_button_);
}
#if defined(USE_ASH)
aura::Window* window = frame->GetNativeWindow();
int outside_bounds = ui::GetDisplayLayout() == ui::LAYOUT_TOUCH ?
kResizeOutsideBoundsSizeTouch :
kResizeOutsideBoundsSize;
window->set_hit_test_bounds_override_outer(
gfx::Insets(-outside_bounds, -outside_bounds,
-outside_bounds, -outside_bounds));
window->set_hit_test_bounds_override_inner(
gfx::Insets(kResizeInsideBoundsSize, kResizeInsideBoundsSize,
kResizeInsideBoundsSize, kResizeInsideBoundsSize));
#endif
}
| 170,715 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int walk_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
pmd_t *pmd;
unsigned long next;
int err = 0;
pmd = pmd_offset(pud, addr);
do {
again:
next = pmd_addr_end(addr, end);
if (pmd_none(*pmd)) {
if (walk->pte_hole)
err = walk->pte_hole(addr, next, walk);
if (err)
break;
continue;
}
/*
* This implies that each ->pmd_entry() handler
* needs to know about pmd_trans_huge() pmds
*/
if (walk->pmd_entry)
err = walk->pmd_entry(pmd, addr, next, walk);
if (err)
break;
/*
* Check this here so we only break down trans_huge
* pages when we _need_ to
*/
if (!walk->pte_entry)
continue;
split_huge_page_pmd(walk->mm, pmd);
if (pmd_none_or_clear_bad(pmd))
goto again;
err = walk_pte_range(pmd, addr, next, walk);
if (err)
break;
} while (pmd++, addr = next, addr != end);
return err;
}
Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode
commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream.
In some cases it may happen that pmd_none_or_clear_bad() is called with
the mmap_sem hold in read mode. In those cases the huge page faults can
allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a
false positive from pmd_bad() that will not like to see a pmd
materializing as trans huge.
It's not khugepaged causing the problem, khugepaged holds the mmap_sem
in write mode (and all those sites must hold the mmap_sem in read mode
to prevent pagetables to go away from under them, during code review it
seems vm86 mode on 32bit kernels requires that too unless it's
restricted to 1 thread per process or UP builds). The race is only with
the huge pagefaults that can convert a pmd_none() into a
pmd_trans_huge().
Effectively all these pmd_none_or_clear_bad() sites running with
mmap_sem in read mode are somewhat speculative with the page faults, and
the result is always undefined when they run simultaneously. This is
probably why it wasn't common to run into this. For example if the
madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page
fault, the hugepage will not be zapped, if the page fault runs first it
will be zapped.
Altering pmd_bad() not to error out if it finds hugepmds won't be enough
to fix this, because zap_pmd_range would then proceed to call
zap_pte_range (which would be incorrect if the pmd become a
pmd_trans_huge()).
The simplest way to fix this is to read the pmd in the local stack
(regardless of what we read, no need of actual CPU barriers, only
compiler barrier needed), and be sure it is not changing under the code
that computes its value. Even if the real pmd is changing under the
value we hold on the stack, we don't care. If we actually end up in
zap_pte_range it means the pmd was not none already and it was not huge,
and it can't become huge from under us (khugepaged locking explained
above).
All we need is to enforce that there is no way anymore that in a code
path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad
can run into a hugepmd. The overhead of a barrier() is just a compiler
tweak and should not be measurable (I only added it for THP builds). I
don't exclude different compiler versions may have prevented the race
too by caching the value of *pmd on the stack (that hasn't been
verified, but it wouldn't be impossible considering
pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines
and there's no external function called in between pmd_trans_huge and
pmd_none_or_clear_bad).
if (pmd_trans_huge(*pmd)) {
if (next-addr != HPAGE_PMD_SIZE) {
VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));
split_huge_page_pmd(vma->vm_mm, pmd);
} else if (zap_huge_pmd(tlb, vma, pmd, addr))
continue;
/* fall through */
}
if (pmd_none_or_clear_bad(pmd))
Because this race condition could be exercised without special
privileges this was reported in CVE-2012-1179.
The race was identified and fully explained by Ulrich who debugged it.
I'm quoting his accurate explanation below, for reference.
====== start quote =======
mapcount 0 page_mapcount 1
kernel BUG at mm/huge_memory.c:1384!
At some point prior to the panic, a "bad pmd ..." message similar to the
following is logged on the console:
mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).
The "bad pmd ..." message is logged by pmd_clear_bad() before it clears
the page's PMD table entry.
143 void pmd_clear_bad(pmd_t *pmd)
144 {
-> 145 pmd_ERROR(*pmd);
146 pmd_clear(pmd);
147 }
After the PMD table entry has been cleared, there is an inconsistency
between the actual number of PMD table entries that are mapping the page
and the page's map count (_mapcount field in struct page). When the page
is subsequently reclaimed, __split_huge_page() detects this inconsistency.
1381 if (mapcount != page_mapcount(page))
1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1383 mapcount, page_mapcount(page));
-> 1384 BUG_ON(mapcount != page_mapcount(page));
The root cause of the problem is a race of two threads in a multithreaded
process. Thread B incurs a page fault on a virtual address that has never
been accessed (PMD entry is zero) while Thread A is executing an madvise()
system call on a virtual address within the same 2 MB (huge page) range.
virtual address space
.---------------------.
| |
| |
.-|---------------------|
| | |
| | |<-- B(fault)
| | |
2 MB | |/////////////////////|-.
huge < |/////////////////////| > A(range)
page | |/////////////////////|-'
| | |
| | |
'-|---------------------|
| |
| |
'---------------------'
- Thread A is executing an madvise(..., MADV_DONTNEED) system call
on the virtual address range "A(range)" shown in the picture.
sys_madvise
// Acquire the semaphore in shared mode.
down_read(¤t->mm->mmap_sem)
...
madvise_vma
switch (behavior)
case MADV_DONTNEED:
madvise_dontneed
zap_page_range
unmap_vmas
unmap_page_range
zap_pud_range
zap_pmd_range
//
// Assume that this huge page has never been accessed.
// I.e. content of the PMD entry is zero (not mapped).
//
if (pmd_trans_huge(*pmd)) {
// We don't get here due to the above assumption.
}
//
// Assume that Thread B incurred a page fault and
.---------> // sneaks in here as shown below.
| //
| if (pmd_none_or_clear_bad(pmd))
| {
| if (unlikely(pmd_bad(*pmd)))
| pmd_clear_bad
| {
| pmd_ERROR
| // Log "bad pmd ..." message here.
| pmd_clear
| // Clear the page's PMD entry.
| // Thread B incremented the map count
| // in page_add_new_anon_rmap(), but
| // now the page is no longer mapped
| // by a PMD entry (-> inconsistency).
| }
| }
|
v
- Thread B is handling a page fault on virtual address "B(fault)" shown
in the picture.
...
do_page_fault
__do_page_fault
// Acquire the semaphore in shared mode.
down_read_trylock(&mm->mmap_sem)
...
handle_mm_fault
if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))
// We get here due to the above assumption (PMD entry is zero).
do_huge_pmd_anonymous_page
alloc_hugepage_vma
// Allocate a new transparent huge page here.
...
__do_huge_pmd_anonymous_page
...
spin_lock(&mm->page_table_lock)
...
page_add_new_anon_rmap
// Here we increment the page's map count (starts at -1).
atomic_set(&page->_mapcount, 0)
set_pmd_at
// Here we set the page's PMD entry which will be cleared
// when Thread A calls pmd_clear_bad().
...
spin_unlock(&mm->page_table_lock)
The mmap_sem does not prevent the race because both threads are acquiring
it in shared mode (down_read). Thread B holds the page_table_lock while
the page's map count and PMD table entry are updated. However, Thread A
does not synchronize on that lock.
====== end quote =======
[[email protected]: checkpatch fixes]
Reported-by: Ulrich Obergfell <[email protected]>
Signed-off-by: Andrea Arcangeli <[email protected]>
Acked-by: Johannes Weiner <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Dave Jones <[email protected]>
Acked-by: Larry Woodman <[email protected]>
Acked-by: Rik van Riel <[email protected]>
Cc: Mark Salter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-264
|
static int walk_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
pmd_t *pmd;
unsigned long next;
int err = 0;
pmd = pmd_offset(pud, addr);
do {
again:
next = pmd_addr_end(addr, end);
if (pmd_none(*pmd)) {
if (walk->pte_hole)
err = walk->pte_hole(addr, next, walk);
if (err)
break;
continue;
}
/*
* This implies that each ->pmd_entry() handler
* needs to know about pmd_trans_huge() pmds
*/
if (walk->pmd_entry)
err = walk->pmd_entry(pmd, addr, next, walk);
if (err)
break;
/*
* Check this here so we only break down trans_huge
* pages when we _need_ to
*/
if (!walk->pte_entry)
continue;
split_huge_page_pmd(walk->mm, pmd);
if (pmd_none_or_trans_huge_or_clear_bad(pmd))
goto again;
err = walk_pte_range(pmd, addr, next, walk);
if (err)
break;
} while (pmd++, addr = next, addr != end);
return err;
}
| 165,636 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ih264d_rest_of_residual_cav_chroma_dc_block(UWORD32 u4_total_coeff_trail_one,
dec_bit_stream_t *ps_bitstrm)
{
UWORD32 u4_total_zeroes;
WORD16 i;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 u4_bitstream_offset = ps_bitstrm->u4_ofst;
UWORD32 u4_trailing_ones = u4_total_coeff_trail_one & 0xFFFF;
UWORD32 u4_total_coeff = u4_total_coeff_trail_one >> 16;
WORD16 i2_level_arr[4];
tu_sblk4x4_coeff_data_t *ps_tu_4x4;
WORD16 *pi2_coeff_data;
dec_struct_t *ps_dec = (dec_struct_t *)ps_bitstrm->pv_codec_handle;
ps_tu_4x4 = (tu_sblk4x4_coeff_data_t *)ps_dec->pv_parse_tu_coeff_data;
ps_tu_4x4->u2_sig_coeff_map = 0;
pi2_coeff_data = &ps_tu_4x4->ai2_level[0];
i = u4_total_coeff - 1;
if(u4_trailing_ones)
{
/*********************************************************************/
/* Decode Trailing Ones */
/* read the sign of T1's and put them in level array */
/*********************************************************************/
UWORD32 u4_signs, u4_cnt = u4_trailing_ones;
WORD16 (*ppi2_trlone_lkup)[3] =
(WORD16 (*)[3])gai2_ih264d_trailing_one_level;
WORD16 *pi2_trlone_lkup;
GETBITS(u4_signs, u4_bitstream_offset, pu4_bitstrm_buf, u4_cnt);
pi2_trlone_lkup = ppi2_trlone_lkup[(1 << u4_cnt) - 2 + u4_signs];
while(u4_cnt--)
i2_level_arr[i--] = *pi2_trlone_lkup++;
}
/****************************************************************/
/* Decoding Levels Begins */
/****************************************************************/
if(i >= 0)
{
/****************************************************************/
/* First level is decoded outside the loop as it has lot of */
/* special cases. */
/****************************************************************/
UWORD32 u4_lev_suffix, u4_suffix_len, u4_lev_suffix_size;
UWORD16 u2_lev_code, u2_abs_value;
UWORD32 u4_lev_prefix;
/***************************************************************/
/* u4_suffix_len = 0, Find leading zeros in next 32 bits */
/***************************************************************/
FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset,
pu4_bitstrm_buf);
/*********************************************************/
/* Special decoding case when trailing ones are 3 */
/*********************************************************/
u2_lev_code = MIN(15, u4_lev_prefix);
u2_lev_code += (3 == u4_trailing_ones) ? 0 : (2);
if(14 == u4_lev_prefix)
u4_lev_suffix_size = 4;
else if(15 <= u4_lev_prefix)
{
u2_lev_code += 15;
u4_lev_suffix_size = u4_lev_prefix - 3;
}
else
u4_lev_suffix_size = 0;
if(16 <= u4_lev_prefix)
{
u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096);
}
if(u4_lev_suffix_size)
{
GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf,
u4_lev_suffix_size);
u2_lev_code += u4_lev_suffix;
}
u2_abs_value = (u2_lev_code + 2) >> 1;
/*********************************************************/
/* If Level code is odd, level is negative else positive */
/*********************************************************/
i2_level_arr[i--] = (u2_lev_code & 1) ? -u2_abs_value : u2_abs_value;
u4_suffix_len = (u2_abs_value > 3) ? 2 : 1;
/*********************************************************/
/* Now loop over the remaining levels */
/*********************************************************/
while(i >= 0)
{
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset,
pu4_bitstrm_buf);
u4_lev_suffix_size =
(15 <= u4_lev_prefix) ?
(u4_lev_prefix - 3) : u4_suffix_len;
/*********************************************************/
/* Compute level code using prefix and suffix */
/*********************************************************/
GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf,
u4_lev_suffix_size);
u2_lev_code = (MIN(u4_lev_prefix,15) << u4_suffix_len)
+ u4_lev_suffix;
if(16 <= u4_lev_prefix)
{
u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096);
}
u2_abs_value = (u2_lev_code + 2) >> 1;
/*********************************************************/
/* If Level code is odd, level is negative else positive */
/*********************************************************/
i2_level_arr[i--] =
(u2_lev_code & 1) ? -u2_abs_value : u2_abs_value;
/*********************************************************/
/* Increment suffix length if required */
/*********************************************************/
u4_suffix_len += (u2_abs_value > (3 << (u4_suffix_len - 1)));
}
/****************************************************************/
/* Decoding Levels Ends */
/****************************************************************/
}
if(u4_total_coeff < 4)
{
UWORD32 u4_max_ldz = (4 - u4_total_coeff);
FIND_ONE_IN_STREAM_LEN(u4_total_zeroes, u4_bitstream_offset,
pu4_bitstrm_buf, u4_max_ldz);
}
else
u4_total_zeroes = 0;
/**************************************************************/
/* Decode the runs and form the coefficient buffer */
/**************************************************************/
{
const UWORD8 *pu1_table_runbefore;
UWORD32 u4_run;
UWORD32 u4_scan_pos = (u4_total_coeff + u4_total_zeroes - 1);
UWORD32 u4_zeroes_left = u4_total_zeroes;
i = u4_total_coeff - 1;
/**************************************************************/
/* Decoding Runs for 0 < zeros left <=6 */
/**************************************************************/
pu1_table_runbefore = (UWORD8 *)gau1_ih264d_table_run_before;
while(u4_zeroes_left && i)
{
UWORD32 u4_code;
NEXTBITS(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 3);
u4_code = pu1_table_runbefore[u4_code + (u4_zeroes_left << 3)];
u4_run = u4_code >> 2;
FLUSHBITS(u4_bitstream_offset, (u4_code & 0x03));
SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos);
*pi2_coeff_data++ = i2_level_arr[i--];
u4_zeroes_left -= u4_run;
u4_scan_pos -= (u4_run + 1);
}
/**************************************************************/
/* Decoding Runs End */
/**************************************************************/
/**************************************************************/
/* Copy the remaining coefficients */
/**************************************************************/
while(i >= 0)
{
SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos);
*pi2_coeff_data++ = i2_level_arr[i--];
u4_scan_pos--;
}
}
{
WORD32 offset;
offset = (UWORD8 *)pi2_coeff_data - (UWORD8 *)ps_tu_4x4;
offset = ALIGN4(offset);
ps_dec->pv_parse_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_parse_tu_coeff_data + offset);
}
ps_bitstrm->u4_ofst = u4_bitstream_offset;
}
Commit Message: Decoder: Fix stack underflow in CAVLC 4x4 parse functions
Bug: 26399350
Change-Id: Id768751672a7b093ab6e53d4fc0b3188d470920e
CWE ID: CWE-119
|
void ih264d_rest_of_residual_cav_chroma_dc_block(UWORD32 u4_total_coeff_trail_one,
dec_bit_stream_t *ps_bitstrm)
{
UWORD32 u4_total_zeroes;
WORD16 i;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 u4_bitstream_offset = ps_bitstrm->u4_ofst;
UWORD32 u4_trailing_ones = u4_total_coeff_trail_one & 0xFFFF;
UWORD32 u4_total_coeff = u4_total_coeff_trail_one >> 16;
// To avoid error check at 4x4 level, allocating for 3 extra levels(4+3)
// since u4_trailing_ones can at the max be 3. This will be required when
// u4_total_coeff is less than u4_trailing_ones
WORD16 ai2_level_arr[7];//
WORD16 *i2_level_arr = &ai2_level_arr[3];
tu_sblk4x4_coeff_data_t *ps_tu_4x4;
WORD16 *pi2_coeff_data;
dec_struct_t *ps_dec = (dec_struct_t *)ps_bitstrm->pv_codec_handle;
ps_tu_4x4 = (tu_sblk4x4_coeff_data_t *)ps_dec->pv_parse_tu_coeff_data;
ps_tu_4x4->u2_sig_coeff_map = 0;
pi2_coeff_data = &ps_tu_4x4->ai2_level[0];
i = u4_total_coeff - 1;
if(u4_trailing_ones)
{
/*********************************************************************/
/* Decode Trailing Ones */
/* read the sign of T1's and put them in level array */
/*********************************************************************/
UWORD32 u4_signs, u4_cnt = u4_trailing_ones;
WORD16 (*ppi2_trlone_lkup)[3] =
(WORD16 (*)[3])gai2_ih264d_trailing_one_level;
WORD16 *pi2_trlone_lkup;
GETBITS(u4_signs, u4_bitstream_offset, pu4_bitstrm_buf, u4_cnt);
pi2_trlone_lkup = ppi2_trlone_lkup[(1 << u4_cnt) - 2 + u4_signs];
while(u4_cnt--)
i2_level_arr[i--] = *pi2_trlone_lkup++;
}
/****************************************************************/
/* Decoding Levels Begins */
/****************************************************************/
if(i >= 0)
{
/****************************************************************/
/* First level is decoded outside the loop as it has lot of */
/* special cases. */
/****************************************************************/
UWORD32 u4_lev_suffix, u4_suffix_len, u4_lev_suffix_size;
UWORD16 u2_lev_code, u2_abs_value;
UWORD32 u4_lev_prefix;
/***************************************************************/
/* u4_suffix_len = 0, Find leading zeros in next 32 bits */
/***************************************************************/
FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset,
pu4_bitstrm_buf);
/*********************************************************/
/* Special decoding case when trailing ones are 3 */
/*********************************************************/
u2_lev_code = MIN(15, u4_lev_prefix);
u2_lev_code += (3 == u4_trailing_ones) ? 0 : (2);
if(14 == u4_lev_prefix)
u4_lev_suffix_size = 4;
else if(15 <= u4_lev_prefix)
{
u2_lev_code += 15;
u4_lev_suffix_size = u4_lev_prefix - 3;
}
else
u4_lev_suffix_size = 0;
if(16 <= u4_lev_prefix)
{
u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096);
}
if(u4_lev_suffix_size)
{
GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf,
u4_lev_suffix_size);
u2_lev_code += u4_lev_suffix;
}
u2_abs_value = (u2_lev_code + 2) >> 1;
/*********************************************************/
/* If Level code is odd, level is negative else positive */
/*********************************************************/
i2_level_arr[i--] = (u2_lev_code & 1) ? -u2_abs_value : u2_abs_value;
u4_suffix_len = (u2_abs_value > 3) ? 2 : 1;
/*********************************************************/
/* Now loop over the remaining levels */
/*********************************************************/
while(i >= 0)
{
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset,
pu4_bitstrm_buf);
u4_lev_suffix_size =
(15 <= u4_lev_prefix) ?
(u4_lev_prefix - 3) : u4_suffix_len;
/*********************************************************/
/* Compute level code using prefix and suffix */
/*********************************************************/
GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf,
u4_lev_suffix_size);
u2_lev_code = (MIN(u4_lev_prefix,15) << u4_suffix_len)
+ u4_lev_suffix;
if(16 <= u4_lev_prefix)
{
u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096);
}
u2_abs_value = (u2_lev_code + 2) >> 1;
/*********************************************************/
/* If Level code is odd, level is negative else positive */
/*********************************************************/
i2_level_arr[i--] =
(u2_lev_code & 1) ? -u2_abs_value : u2_abs_value;
/*********************************************************/
/* Increment suffix length if required */
/*********************************************************/
u4_suffix_len += (u2_abs_value > (3 << (u4_suffix_len - 1)));
}
/****************************************************************/
/* Decoding Levels Ends */
/****************************************************************/
}
if(u4_total_coeff < 4)
{
UWORD32 u4_max_ldz = (4 - u4_total_coeff);
FIND_ONE_IN_STREAM_LEN(u4_total_zeroes, u4_bitstream_offset,
pu4_bitstrm_buf, u4_max_ldz);
}
else
u4_total_zeroes = 0;
/**************************************************************/
/* Decode the runs and form the coefficient buffer */
/**************************************************************/
{
const UWORD8 *pu1_table_runbefore;
UWORD32 u4_run;
UWORD32 u4_scan_pos = (u4_total_coeff + u4_total_zeroes - 1);
UWORD32 u4_zeroes_left = u4_total_zeroes;
i = u4_total_coeff - 1;
/**************************************************************/
/* Decoding Runs for 0 < zeros left <=6 */
/**************************************************************/
pu1_table_runbefore = (UWORD8 *)gau1_ih264d_table_run_before;
while(u4_zeroes_left && i)
{
UWORD32 u4_code;
NEXTBITS(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 3);
u4_code = pu1_table_runbefore[u4_code + (u4_zeroes_left << 3)];
u4_run = u4_code >> 2;
FLUSHBITS(u4_bitstream_offset, (u4_code & 0x03));
SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos);
*pi2_coeff_data++ = i2_level_arr[i--];
u4_zeroes_left -= u4_run;
u4_scan_pos -= (u4_run + 1);
}
/**************************************************************/
/* Decoding Runs End */
/**************************************************************/
/**************************************************************/
/* Copy the remaining coefficients */
/**************************************************************/
while(i >= 0)
{
SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos);
*pi2_coeff_data++ = i2_level_arr[i--];
u4_scan_pos--;
}
}
{
WORD32 offset;
offset = (UWORD8 *)pi2_coeff_data - (UWORD8 *)ps_tu_4x4;
offset = ALIGN4(offset);
ps_dec->pv_parse_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_parse_tu_coeff_data + offset);
}
ps_bitstrm->u4_ofst = u4_bitstream_offset;
}
| 173,915 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void V8Window::namedPropertyGetterCustom(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{
if (!name->IsString())
return;
auto nameString = name.As<v8::String>();
LocalDOMWindow* window = toLocalDOMWindow(V8Window::toImpl(info.Holder()));
if (!window)
return;
LocalFrame* frame = window->frame();
if (!frame)
return;
AtomicString propName = toCoreAtomicString(nameString);
Frame* child = frame->tree().scopedChild(propName);
if (child) {
v8SetReturnValueFast(info, child->domWindow(), window);
return;
}
if (!info.Holder()->GetRealNamedProperty(nameString).IsEmpty())
return;
Document* doc = frame->document();
if (doc && doc->isHTMLDocument()) {
if (toHTMLDocument(doc)->hasNamedItem(propName) || doc->hasElementWithId(propName)) {
RefPtrWillBeRawPtr<HTMLCollection> items = doc->windowNamedItems(propName);
if (!items->isEmpty()) {
if (items->hasExactlyOneItem()) {
v8SetReturnValueFast(info, items->item(0), window);
return;
}
v8SetReturnValueFast(info, items.release(), window);
return;
}
}
}
}
Commit Message: Reload frame in V8Window::namedPropertyGetterCustom after js call
[email protected]
BUG=454954
Review URL: https://codereview.chromium.org/901053006
git-svn-id: svn://svn.chromium.org/blink/trunk@189574 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
|
void V8Window::namedPropertyGetterCustom(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{
if (!name->IsString())
return;
auto nameString = name.As<v8::String>();
LocalDOMWindow* window = toLocalDOMWindow(V8Window::toImpl(info.Holder()));
if (!window)
return;
LocalFrame* frame = window->frame();
if (!frame)
return;
AtomicString propName = toCoreAtomicString(nameString);
Frame* child = frame->tree().scopedChild(propName);
if (child) {
v8SetReturnValueFast(info, child->domWindow(), window);
return;
}
if (!info.Holder()->GetRealNamedProperty(nameString).IsEmpty())
return;
// Frame could have been detached in call to GetRealNamedProperty.
frame = window->frame();
// window is detached.
if (!frame)
return;
Document* doc = frame->document();
if (doc && doc->isHTMLDocument()) {
if (toHTMLDocument(doc)->hasNamedItem(propName) || doc->hasElementWithId(propName)) {
RefPtrWillBeRawPtr<HTMLCollection> items = doc->windowNamedItems(propName);
if (!items->isEmpty()) {
if (items->hasExactlyOneItem()) {
v8SetReturnValueFast(info, items->item(0), window);
return;
}
v8SetReturnValueFast(info, items.release(), window);
return;
}
}
}
}
| 172,024 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: xmlParseAttributeListDecl(xmlParserCtxtPtr ctxt) {
const xmlChar *elemName;
const xmlChar *attrName;
xmlEnumerationPtr tree;
if (CMP9(CUR_PTR, '<', '!', 'A', 'T', 'T', 'L', 'I', 'S', 'T')) {
xmlParserInputPtr input = ctxt->input;
SKIP(9);
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '<!ATTLIST'\n");
}
SKIP_BLANKS;
elemName = xmlParseName(ctxt);
if (elemName == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"ATTLIST: no name for Element\n");
return;
}
SKIP_BLANKS;
GROW;
while (RAW != '>') {
const xmlChar *check = CUR_PTR;
int type;
int def;
xmlChar *defaultValue = NULL;
GROW;
tree = NULL;
attrName = xmlParseName(ctxt);
if (attrName == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"ATTLIST: no name for Attribute\n");
break;
}
GROW;
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the attribute name\n");
break;
}
SKIP_BLANKS;
type = xmlParseAttributeType(ctxt, &tree);
if (type <= 0) {
break;
}
GROW;
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the attribute type\n");
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
SKIP_BLANKS;
def = xmlParseDefaultDecl(ctxt, &defaultValue);
if (def <= 0) {
if (defaultValue != NULL)
xmlFree(defaultValue);
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
if ((type != XML_ATTRIBUTE_CDATA) && (defaultValue != NULL))
xmlAttrNormalizeSpace(defaultValue, defaultValue);
GROW;
if (RAW != '>') {
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the attribute default value\n");
if (defaultValue != NULL)
xmlFree(defaultValue);
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
SKIP_BLANKS;
}
if (check == CUR_PTR) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"in xmlParseAttributeListDecl\n");
if (defaultValue != NULL)
xmlFree(defaultValue);
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
(ctxt->sax->attributeDecl != NULL))
ctxt->sax->attributeDecl(ctxt->userData, elemName, attrName,
type, def, defaultValue, tree);
else if (tree != NULL)
xmlFreeEnumeration(tree);
if ((ctxt->sax2) && (defaultValue != NULL) &&
(def != XML_ATTRIBUTE_IMPLIED) &&
(def != XML_ATTRIBUTE_REQUIRED)) {
xmlAddDefAttrs(ctxt, elemName, attrName, defaultValue);
}
if (ctxt->sax2) {
xmlAddSpecialAttr(ctxt, elemName, attrName, type);
}
if (defaultValue != NULL)
xmlFree(defaultValue);
GROW;
}
if (RAW == '>') {
if (input != ctxt->input) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Attribute list declaration doesn't start and stop in the same entity\n",
NULL, NULL);
}
NEXT;
}
}
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
xmlParseAttributeListDecl(xmlParserCtxtPtr ctxt) {
const xmlChar *elemName;
const xmlChar *attrName;
xmlEnumerationPtr tree;
if (CMP9(CUR_PTR, '<', '!', 'A', 'T', 'T', 'L', 'I', 'S', 'T')) {
xmlParserInputPtr input = ctxt->input;
SKIP(9);
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '<!ATTLIST'\n");
}
SKIP_BLANKS;
elemName = xmlParseName(ctxt);
if (elemName == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"ATTLIST: no name for Element\n");
return;
}
SKIP_BLANKS;
GROW;
while ((RAW != '>') && (ctxt->instate != XML_PARSER_EOF)) {
const xmlChar *check = CUR_PTR;
int type;
int def;
xmlChar *defaultValue = NULL;
GROW;
tree = NULL;
attrName = xmlParseName(ctxt);
if (attrName == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"ATTLIST: no name for Attribute\n");
break;
}
GROW;
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the attribute name\n");
break;
}
SKIP_BLANKS;
type = xmlParseAttributeType(ctxt, &tree);
if (type <= 0) {
break;
}
GROW;
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the attribute type\n");
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
SKIP_BLANKS;
def = xmlParseDefaultDecl(ctxt, &defaultValue);
if (def <= 0) {
if (defaultValue != NULL)
xmlFree(defaultValue);
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
if ((type != XML_ATTRIBUTE_CDATA) && (defaultValue != NULL))
xmlAttrNormalizeSpace(defaultValue, defaultValue);
GROW;
if (RAW != '>') {
if (!IS_BLANK_CH(CUR)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the attribute default value\n");
if (defaultValue != NULL)
xmlFree(defaultValue);
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
SKIP_BLANKS;
}
if (check == CUR_PTR) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"in xmlParseAttributeListDecl\n");
if (defaultValue != NULL)
xmlFree(defaultValue);
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
if ((ctxt->sax != NULL) && (!ctxt->disableSAX) &&
(ctxt->sax->attributeDecl != NULL))
ctxt->sax->attributeDecl(ctxt->userData, elemName, attrName,
type, def, defaultValue, tree);
else if (tree != NULL)
xmlFreeEnumeration(tree);
if ((ctxt->sax2) && (defaultValue != NULL) &&
(def != XML_ATTRIBUTE_IMPLIED) &&
(def != XML_ATTRIBUTE_REQUIRED)) {
xmlAddDefAttrs(ctxt, elemName, attrName, defaultValue);
}
if (ctxt->sax2) {
xmlAddSpecialAttr(ctxt, elemName, attrName, type);
}
if (defaultValue != NULL)
xmlFree(defaultValue);
GROW;
}
if (RAW == '>') {
if (input != ctxt->input) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Attribute list declaration doesn't start and stop in the same entity\n",
NULL, NULL);
}
NEXT;
}
}
}
| 171,272 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool RenderWidgetHostViewAura::ShouldFastACK(uint64 surface_id) {
ui::Texture* container = image_transport_clients_[surface_id];
DCHECK(container);
if (can_lock_compositor_ == NO_PENDING_RENDERER_FRAME ||
can_lock_compositor_ == NO_PENDING_COMMIT ||
resize_locks_.empty())
return false;
gfx::Size container_size = ConvertSizeToDIP(this, container->size());
ResizeLockList::iterator it = resize_locks_.begin();
while (it != resize_locks_.end()) {
if ((*it)->expected_size() == container_size)
break;
++it;
}
return it == resize_locks_.end() || ++it != resize_locks_.end();
}
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:
|
bool RenderWidgetHostViewAura::ShouldFastACK(uint64 surface_id) {
bool RenderWidgetHostViewAura::ShouldSkipFrame(const gfx::Size& size) {
if (can_lock_compositor_ == NO_PENDING_RENDERER_FRAME ||
can_lock_compositor_ == NO_PENDING_COMMIT ||
resize_locks_.empty())
return false;
gfx::Size container_size = ConvertSizeToDIP(this, size);
ResizeLockList::iterator it = resize_locks_.begin();
while (it != resize_locks_.end()) {
if ((*it)->expected_size() == container_size)
break;
++it;
}
return it == resize_locks_.end() || ++it != resize_locks_.end();
}
| 171,386 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: _gnutls_server_name_recv_params (gnutls_session_t session,
const opaque * data, size_t _data_size)
{
int i;
const unsigned char *p;
uint16_t len, type;
ssize_t data_size = _data_size;
int server_names = 0;
if (session->security_parameters.entity == GNUTLS_SERVER)
{
DECR_LENGTH_RET (data_size, 2, 0);
len = _gnutls_read_uint16 (data);
if (len != data_size)
{
/* This is unexpected packet length, but
* just ignore it, for now.
*/
gnutls_assert ();
return 0;
}
p = data + 2;
/* Count all server_names in the packet. */
while (data_size > 0)
{
DECR_LENGTH_RET (data_size, 1, 0);
p++;
DECR_LEN (data_size, 2);
len = _gnutls_read_uint16 (p);
p += 2;
DECR_LENGTH_RET (data_size, len, 0);
server_names++;
p += len;
}
session->security_parameters.extensions.server_names_size =
if (server_names == 0)
return 0; /* no names found */
/* we cannot accept more server names.
*/
if (server_names > MAX_SERVER_NAME_EXTENSIONS)
server_names = MAX_SERVER_NAME_EXTENSIONS;
p = data + 2;
for (i = 0; i < server_names; i++)
server_names[i].name, p, len);
session->security_parameters.extensions.
server_names[i].name_length = len;
session->security_parameters.extensions.
server_names[i].type = GNUTLS_NAME_DNS;
break;
}
}
Commit Message:
CWE ID: CWE-189
|
_gnutls_server_name_recv_params (gnutls_session_t session,
const opaque * data, size_t _data_size)
{
int i;
const unsigned char *p;
uint16_t len, type;
ssize_t data_size = _data_size;
int server_names = 0;
if (session->security_parameters.entity == GNUTLS_SERVER)
{
DECR_LENGTH_RET (data_size, 2, 0);
len = _gnutls_read_uint16 (data);
if (len != data_size)
{
/* This is unexpected packet length, but
* just ignore it, for now.
*/
gnutls_assert ();
return 0;
}
p = data + 2;
/* Count all server_names in the packet. */
while (data_size > 0)
{
DECR_LENGTH_RET (data_size, 1, 0);
p++;
DECR_LEN (data_size, 2);
len = _gnutls_read_uint16 (p);
p += 2;
if (len > 0)
{
DECR_LENGTH_RET (data_size, len, 0);
server_names++;
p += len;
}
else
_gnutls_handshake_log
("HSK[%x]: Received zero size server name (under attack?)\n",
session);
}
/* we cannot accept more server names.
*/
if (server_names > MAX_SERVER_NAME_EXTENSIONS)
{
_gnutls_handshake_log
("HSK[%x]: Too many server names received (under attack?)\n",
session);
server_names = MAX_SERVER_NAME_EXTENSIONS;
}
session->security_parameters.extensions.server_names_size =
if (server_names == 0)
return 0; /* no names found */
p = data + 2;
for (i = 0; i < server_names; i++)
server_names[i].name, p, len);
session->security_parameters.extensions.
server_names[i].name_length = len;
session->security_parameters.extensions.
server_names[i].type = GNUTLS_NAME_DNS;
break;
}
}
| 165,145 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: long follow_hugetlb_page(struct mm_struct *mm, struct vm_area_struct *vma,
struct page **pages, struct vm_area_struct **vmas,
unsigned long *position, unsigned long *nr_pages,
long i, unsigned int flags, int *nonblocking)
{
unsigned long pfn_offset;
unsigned long vaddr = *position;
unsigned long remainder = *nr_pages;
struct hstate *h = hstate_vma(vma);
int err = -EFAULT;
while (vaddr < vma->vm_end && remainder) {
pte_t *pte;
spinlock_t *ptl = NULL;
int absent;
struct page *page;
/*
* If we have a pending SIGKILL, don't keep faulting pages and
* potentially allocating memory.
*/
if (fatal_signal_pending(current)) {
remainder = 0;
break;
}
/*
* Some archs (sparc64, sh*) have multiple pte_ts to
* each hugepage. We have to make sure we get the
* first, for the page indexing below to work.
*
* Note that page table lock is not held when pte is null.
*/
pte = huge_pte_offset(mm, vaddr & huge_page_mask(h),
huge_page_size(h));
if (pte)
ptl = huge_pte_lock(h, mm, pte);
absent = !pte || huge_pte_none(huge_ptep_get(pte));
/*
* When coredumping, it suits get_dump_page if we just return
* an error where there's an empty slot with no huge pagecache
* to back it. This way, we avoid allocating a hugepage, and
* the sparse dumpfile avoids allocating disk blocks, but its
* huge holes still show up with zeroes where they need to be.
*/
if (absent && (flags & FOLL_DUMP) &&
!hugetlbfs_pagecache_present(h, vma, vaddr)) {
if (pte)
spin_unlock(ptl);
remainder = 0;
break;
}
/*
* We need call hugetlb_fault for both hugepages under migration
* (in which case hugetlb_fault waits for the migration,) and
* hwpoisoned hugepages (in which case we need to prevent the
* caller from accessing to them.) In order to do this, we use
* here is_swap_pte instead of is_hugetlb_entry_migration and
* is_hugetlb_entry_hwpoisoned. This is because it simply covers
* both cases, and because we can't follow correct pages
* directly from any kind of swap entries.
*/
if (absent || is_swap_pte(huge_ptep_get(pte)) ||
((flags & FOLL_WRITE) &&
!huge_pte_write(huge_ptep_get(pte)))) {
vm_fault_t ret;
unsigned int fault_flags = 0;
if (pte)
spin_unlock(ptl);
if (flags & FOLL_WRITE)
fault_flags |= FAULT_FLAG_WRITE;
if (nonblocking)
fault_flags |= FAULT_FLAG_ALLOW_RETRY;
if (flags & FOLL_NOWAIT)
fault_flags |= FAULT_FLAG_ALLOW_RETRY |
FAULT_FLAG_RETRY_NOWAIT;
if (flags & FOLL_TRIED) {
VM_WARN_ON_ONCE(fault_flags &
FAULT_FLAG_ALLOW_RETRY);
fault_flags |= FAULT_FLAG_TRIED;
}
ret = hugetlb_fault(mm, vma, vaddr, fault_flags);
if (ret & VM_FAULT_ERROR) {
err = vm_fault_to_errno(ret, flags);
remainder = 0;
break;
}
if (ret & VM_FAULT_RETRY) {
if (nonblocking &&
!(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
*nonblocking = 0;
*nr_pages = 0;
/*
* VM_FAULT_RETRY must not return an
* error, it will return zero
* instead.
*
* No need to update "position" as the
* caller will not check it after
* *nr_pages is set to 0.
*/
return i;
}
continue;
}
pfn_offset = (vaddr & ~huge_page_mask(h)) >> PAGE_SHIFT;
page = pte_page(huge_ptep_get(pte));
same_page:
if (pages) {
pages[i] = mem_map_offset(page, pfn_offset);
get_page(pages[i]);
}
if (vmas)
vmas[i] = vma;
vaddr += PAGE_SIZE;
++pfn_offset;
--remainder;
++i;
if (vaddr < vma->vm_end && remainder &&
pfn_offset < pages_per_huge_page(h)) {
/*
* We use pfn_offset to avoid touching the pageframes
* of this compound page.
*/
goto same_page;
}
spin_unlock(ptl);
}
*nr_pages = remainder;
/*
* setting position is actually required only if remainder is
* not zero but it's faster not to add a "if (remainder)"
* branch.
*/
*position = vaddr;
return i ? i : err;
}
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
|
long follow_hugetlb_page(struct mm_struct *mm, struct vm_area_struct *vma,
struct page **pages, struct vm_area_struct **vmas,
unsigned long *position, unsigned long *nr_pages,
long i, unsigned int flags, int *nonblocking)
{
unsigned long pfn_offset;
unsigned long vaddr = *position;
unsigned long remainder = *nr_pages;
struct hstate *h = hstate_vma(vma);
int err = -EFAULT;
while (vaddr < vma->vm_end && remainder) {
pte_t *pte;
spinlock_t *ptl = NULL;
int absent;
struct page *page;
/*
* If we have a pending SIGKILL, don't keep faulting pages and
* potentially allocating memory.
*/
if (fatal_signal_pending(current)) {
remainder = 0;
break;
}
/*
* Some archs (sparc64, sh*) have multiple pte_ts to
* each hugepage. We have to make sure we get the
* first, for the page indexing below to work.
*
* Note that page table lock is not held when pte is null.
*/
pte = huge_pte_offset(mm, vaddr & huge_page_mask(h),
huge_page_size(h));
if (pte)
ptl = huge_pte_lock(h, mm, pte);
absent = !pte || huge_pte_none(huge_ptep_get(pte));
/*
* When coredumping, it suits get_dump_page if we just return
* an error where there's an empty slot with no huge pagecache
* to back it. This way, we avoid allocating a hugepage, and
* the sparse dumpfile avoids allocating disk blocks, but its
* huge holes still show up with zeroes where they need to be.
*/
if (absent && (flags & FOLL_DUMP) &&
!hugetlbfs_pagecache_present(h, vma, vaddr)) {
if (pte)
spin_unlock(ptl);
remainder = 0;
break;
}
/*
* We need call hugetlb_fault for both hugepages under migration
* (in which case hugetlb_fault waits for the migration,) and
* hwpoisoned hugepages (in which case we need to prevent the
* caller from accessing to them.) In order to do this, we use
* here is_swap_pte instead of is_hugetlb_entry_migration and
* is_hugetlb_entry_hwpoisoned. This is because it simply covers
* both cases, and because we can't follow correct pages
* directly from any kind of swap entries.
*/
if (absent || is_swap_pte(huge_ptep_get(pte)) ||
((flags & FOLL_WRITE) &&
!huge_pte_write(huge_ptep_get(pte)))) {
vm_fault_t ret;
unsigned int fault_flags = 0;
if (pte)
spin_unlock(ptl);
if (flags & FOLL_WRITE)
fault_flags |= FAULT_FLAG_WRITE;
if (nonblocking)
fault_flags |= FAULT_FLAG_ALLOW_RETRY;
if (flags & FOLL_NOWAIT)
fault_flags |= FAULT_FLAG_ALLOW_RETRY |
FAULT_FLAG_RETRY_NOWAIT;
if (flags & FOLL_TRIED) {
VM_WARN_ON_ONCE(fault_flags &
FAULT_FLAG_ALLOW_RETRY);
fault_flags |= FAULT_FLAG_TRIED;
}
ret = hugetlb_fault(mm, vma, vaddr, fault_flags);
if (ret & VM_FAULT_ERROR) {
err = vm_fault_to_errno(ret, flags);
remainder = 0;
break;
}
if (ret & VM_FAULT_RETRY) {
if (nonblocking &&
!(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
*nonblocking = 0;
*nr_pages = 0;
/*
* VM_FAULT_RETRY must not return an
* error, it will return zero
* instead.
*
* No need to update "position" as the
* caller will not check it after
* *nr_pages is set to 0.
*/
return i;
}
continue;
}
pfn_offset = (vaddr & ~huge_page_mask(h)) >> PAGE_SHIFT;
page = pte_page(huge_ptep_get(pte));
/*
* Instead of doing 'try_get_page()' below in the same_page
* loop, just check the count once here.
*/
if (unlikely(page_count(page) <= 0)) {
if (pages) {
spin_unlock(ptl);
remainder = 0;
err = -ENOMEM;
break;
}
}
same_page:
if (pages) {
pages[i] = mem_map_offset(page, pfn_offset);
get_page(pages[i]);
}
if (vmas)
vmas[i] = vma;
vaddr += PAGE_SIZE;
++pfn_offset;
--remainder;
++i;
if (vaddr < vma->vm_end && remainder &&
pfn_offset < pages_per_huge_page(h)) {
/*
* We use pfn_offset to avoid touching the pageframes
* of this compound page.
*/
goto same_page;
}
spin_unlock(ptl);
}
*nr_pages = remainder;
/*
* setting position is actually required only if remainder is
* not zero but it's faster not to add a "if (remainder)"
* branch.
*/
*position = vaddr;
return i ? i : err;
}
| 170,229 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void sas_init_port(struct asd_sas_port *port,
struct sas_ha_struct *sas_ha, int i)
{
memset(port, 0, sizeof(*port));
port->id = i;
INIT_LIST_HEAD(&port->dev_list);
INIT_LIST_HEAD(&port->disco_list);
INIT_LIST_HEAD(&port->destroy_list);
spin_lock_init(&port->phy_list_lock);
INIT_LIST_HEAD(&port->phy_list);
port->ha = sas_ha;
spin_lock_init(&port->dev_list_lock);
}
Commit Message: scsi: libsas: direct call probe and destruct
In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery
competing with ata error handling") introduced disco mutex to prevent
rediscovery competing with ata error handling and put the whole
revalidation in the mutex. But the rphy add/remove needs to wait for the
error handling which also grabs the disco mutex. This may leads to dead
lock.So the probe and destruct event were introduce to do the rphy
add/remove asynchronously and out of the lock.
The asynchronously processed workers makes the whole discovery process
not atomic, the other events may interrupt the process. For example,
if a loss of signal event inserted before the probe event, the
sas_deform_port() is called and the port will be deleted.
And sas_port_delete() may run before the destruct event, but the
port-x:x is the top parent of end device or expander. This leads to
a kernel WARNING such as:
[ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22'
[ 82.042983] ------------[ cut here ]------------
[ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237
sysfs_remove_group+0x94/0xa0
[ 82.043059] Call trace:
[ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0
[ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70
[ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308
[ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60
[ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80
[ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0
[ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50
[ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0
[ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0
[ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490
[ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128
[ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50
Make probe and destruct a direct call in the disco and revalidate function,
but put them outside the lock. The whole discovery or revalidate won't
be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT
event are deleted as a result of the direct call.
Introduce a new list to destruct the sas_port and put the port delete after
the destruct. This makes sure the right order of destroying the sysfs
kobject and fix the warning above.
In sas_ex_revalidate_domain() have a loop to find all broadcasted
device, and sometimes we have a chance to find the same expander twice.
Because the sas_port will be deleted at the end of the whole revalidate
process, sas_port with the same name cannot be added before this.
Otherwise the sysfs will complain of creating duplicate filename. Since
the LLDD will send broadcast for every device change, we can only
process one expander's revalidation.
[mkp: kbuild test robot warning]
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: Johannes Thumshirn <[email protected]>
CC: Ewan Milne <[email protected]>
CC: Christoph Hellwig <[email protected]>
CC: Tomas Henzl <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Hannes Reinecke <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID:
|
static void sas_init_port(struct asd_sas_port *port,
struct sas_ha_struct *sas_ha, int i)
{
memset(port, 0, sizeof(*port));
port->id = i;
INIT_LIST_HEAD(&port->dev_list);
INIT_LIST_HEAD(&port->disco_list);
INIT_LIST_HEAD(&port->destroy_list);
INIT_LIST_HEAD(&port->sas_port_del_list);
spin_lock_init(&port->phy_list_lock);
INIT_LIST_HEAD(&port->phy_list);
port->ha = sas_ha;
spin_lock_init(&port->dev_list_lock);
}
| 169,394 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void HTMLScriptRunner::executePendingScriptAndDispatchEvent(PendingScript& pendingScript, PendingScript::Type pendingScriptType)
{
bool errorOccurred = false;
double loadFinishTime = pendingScript.resource() && pendingScript.resource()->url().protocolIsInHTTPFamily() ? pendingScript.resource()->loadFinishTime() : 0;
ScriptSourceCode sourceCode = pendingScript.getSource(documentURLForScriptExecution(m_document), errorOccurred);
pendingScript.stopWatchingForLoad(this);
if (!isExecutingScript()) {
Microtask::performCheckpoint();
if (pendingScriptType == PendingScript::ParsingBlocking) {
m_hasScriptsWaitingForResources = !m_document->isScriptExecutionReady();
if (m_hasScriptsWaitingForResources)
return;
}
}
RefPtrWillBeRawPtr<Element> element = pendingScript.releaseElementAndClear();
double compilationFinishTime = 0;
if (ScriptLoader* scriptLoader = toScriptLoaderIfPossible(element.get())) {
NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel);
IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_document);
if (errorOccurred)
scriptLoader->dispatchErrorEvent();
else {
ASSERT(isExecutingScript());
if (!scriptLoader->executeScript(sourceCode, &compilationFinishTime)) {
scriptLoader->dispatchErrorEvent();
} else {
element->dispatchEvent(createScriptLoadEvent());
}
}
}
const double epsilon = 1;
if (pendingScriptType == PendingScript::ParsingBlocking && !m_parserBlockingScriptAlreadyLoaded && compilationFinishTime > epsilon && loadFinishTime > epsilon) {
Platform::current()->histogramCustomCounts("WebCore.Scripts.ParsingBlocking.TimeBetweenLoadedAndCompiled", (compilationFinishTime - loadFinishTime) * 1000, 0, 10000, 50);
}
ASSERT(!isExecutingScript());
}
Commit Message: Correctly keep track of isolates for microtask execution
BUG=487155
[email protected]
Review URL: https://codereview.chromium.org/1161823002
git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-254
|
void HTMLScriptRunner::executePendingScriptAndDispatchEvent(PendingScript& pendingScript, PendingScript::Type pendingScriptType)
{
bool errorOccurred = false;
double loadFinishTime = pendingScript.resource() && pendingScript.resource()->url().protocolIsInHTTPFamily() ? pendingScript.resource()->loadFinishTime() : 0;
ScriptSourceCode sourceCode = pendingScript.getSource(documentURLForScriptExecution(m_document), errorOccurred);
pendingScript.stopWatchingForLoad(this);
if (!isExecutingScript()) {
Microtask::performCheckpoint(V8PerIsolateData::mainThreadIsolate());
if (pendingScriptType == PendingScript::ParsingBlocking) {
m_hasScriptsWaitingForResources = !m_document->isScriptExecutionReady();
if (m_hasScriptsWaitingForResources)
return;
}
}
RefPtrWillBeRawPtr<Element> element = pendingScript.releaseElementAndClear();
double compilationFinishTime = 0;
if (ScriptLoader* scriptLoader = toScriptLoaderIfPossible(element.get())) {
NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel);
IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_document);
if (errorOccurred)
scriptLoader->dispatchErrorEvent();
else {
ASSERT(isExecutingScript());
if (!scriptLoader->executeScript(sourceCode, &compilationFinishTime)) {
scriptLoader->dispatchErrorEvent();
} else {
element->dispatchEvent(createScriptLoadEvent());
}
}
}
const double epsilon = 1;
if (pendingScriptType == PendingScript::ParsingBlocking && !m_parserBlockingScriptAlreadyLoaded && compilationFinishTime > epsilon && loadFinishTime > epsilon) {
Platform::current()->histogramCustomCounts("WebCore.Scripts.ParsingBlocking.TimeBetweenLoadedAndCompiled", (compilationFinishTime - loadFinishTime) * 1000, 0, 10000, 50);
}
ASSERT(!isExecutingScript());
}
| 171,946 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: i915_gem_do_execbuffer(struct drm_device *dev, void *data,
struct drm_file *file,
struct drm_i915_gem_execbuffer2 *args,
struct drm_i915_gem_exec_object2 *exec)
{
drm_i915_private_t *dev_priv = dev->dev_private;
struct list_head objects;
struct eb_objects *eb;
struct drm_i915_gem_object *batch_obj;
struct drm_clip_rect *cliprects = NULL;
struct intel_ring_buffer *ring;
u32 exec_start, exec_len;
u32 seqno;
u32 mask;
int ret, mode, i;
if (!i915_gem_check_execbuffer(args)) {
DRM_DEBUG("execbuf with invalid offset/length\n");
return -EINVAL;
}
ret = validate_exec_list(exec, args->buffer_count);
if (ret)
return ret;
switch (args->flags & I915_EXEC_RING_MASK) {
case I915_EXEC_DEFAULT:
case I915_EXEC_RENDER:
ring = &dev_priv->ring[RCS];
break;
case I915_EXEC_BSD:
if (!HAS_BSD(dev)) {
DRM_DEBUG("execbuf with invalid ring (BSD)\n");
return -EINVAL;
}
ring = &dev_priv->ring[VCS];
break;
case I915_EXEC_BLT:
if (!HAS_BLT(dev)) {
DRM_DEBUG("execbuf with invalid ring (BLT)\n");
return -EINVAL;
}
ring = &dev_priv->ring[BCS];
break;
default:
DRM_DEBUG("execbuf with unknown ring: %d\n",
(int)(args->flags & I915_EXEC_RING_MASK));
return -EINVAL;
}
mode = args->flags & I915_EXEC_CONSTANTS_MASK;
mask = I915_EXEC_CONSTANTS_MASK;
switch (mode) {
case I915_EXEC_CONSTANTS_REL_GENERAL:
case I915_EXEC_CONSTANTS_ABSOLUTE:
case I915_EXEC_CONSTANTS_REL_SURFACE:
if (ring == &dev_priv->ring[RCS] &&
mode != dev_priv->relative_constants_mode) {
if (INTEL_INFO(dev)->gen < 4)
return -EINVAL;
if (INTEL_INFO(dev)->gen > 5 &&
mode == I915_EXEC_CONSTANTS_REL_SURFACE)
return -EINVAL;
/* The HW changed the meaning on this bit on gen6 */
if (INTEL_INFO(dev)->gen >= 6)
mask &= ~I915_EXEC_CONSTANTS_REL_SURFACE;
}
break;
default:
DRM_DEBUG("execbuf with unknown constants: %d\n", mode);
return -EINVAL;
}
if (args->buffer_count < 1) {
DRM_DEBUG("execbuf with %d buffers\n", args->buffer_count);
return -EINVAL;
}
if (args->num_cliprects != 0) {
if (ring != &dev_priv->ring[RCS]) {
DRM_DEBUG("clip rectangles are only valid with the render ring\n");
return -EINVAL;
}
cliprects = kmalloc(args->num_cliprects * sizeof(*cliprects),
GFP_KERNEL);
if (cliprects == NULL) {
ret = -ENOMEM;
goto pre_mutex_err;
}
if (copy_from_user(cliprects,
(struct drm_clip_rect __user *)(uintptr_t)
args->cliprects_ptr,
sizeof(*cliprects)*args->num_cliprects)) {
ret = -EFAULT;
goto pre_mutex_err;
}
}
ret = i915_mutex_lock_interruptible(dev);
if (ret)
goto pre_mutex_err;
if (dev_priv->mm.suspended) {
mutex_unlock(&dev->struct_mutex);
ret = -EBUSY;
goto pre_mutex_err;
}
eb = eb_create(args->buffer_count);
if (eb == NULL) {
mutex_unlock(&dev->struct_mutex);
ret = -ENOMEM;
goto pre_mutex_err;
}
/* Look up object handles */
INIT_LIST_HEAD(&objects);
for (i = 0; i < args->buffer_count; i++) {
struct drm_i915_gem_object *obj;
obj = to_intel_bo(drm_gem_object_lookup(dev, file,
exec[i].handle));
if (&obj->base == NULL) {
DRM_DEBUG("Invalid object handle %d at index %d\n",
exec[i].handle, i);
/* prevent error path from reading uninitialized data */
ret = -ENOENT;
goto err;
}
if (!list_empty(&obj->exec_list)) {
DRM_DEBUG("Object %p [handle %d, index %d] appears more than once in object list\n",
obj, exec[i].handle, i);
ret = -EINVAL;
goto err;
}
list_add_tail(&obj->exec_list, &objects);
obj->exec_handle = exec[i].handle;
obj->exec_entry = &exec[i];
eb_add_object(eb, obj);
}
/* take note of the batch buffer before we might reorder the lists */
batch_obj = list_entry(objects.prev,
struct drm_i915_gem_object,
exec_list);
/* Move the objects en-masse into the GTT, evicting if necessary. */
ret = i915_gem_execbuffer_reserve(ring, file, &objects);
if (ret)
goto err;
/* The objects are in their final locations, apply the relocations. */
ret = i915_gem_execbuffer_relocate(dev, eb, &objects);
if (ret) {
if (ret == -EFAULT) {
ret = i915_gem_execbuffer_relocate_slow(dev, file, ring,
&objects, eb,
exec,
args->buffer_count);
BUG_ON(!mutex_is_locked(&dev->struct_mutex));
}
if (ret)
goto err;
}
/* Set the pending read domains for the batch buffer to COMMAND */
if (batch_obj->base.pending_write_domain) {
DRM_DEBUG("Attempting to use self-modifying batch buffer\n");
ret = -EINVAL;
goto err;
}
batch_obj->base.pending_read_domains |= I915_GEM_DOMAIN_COMMAND;
ret = i915_gem_execbuffer_move_to_gpu(ring, &objects);
if (ret)
goto err;
seqno = i915_gem_next_request_seqno(ring);
for (i = 0; i < ARRAY_SIZE(ring->sync_seqno); i++) {
if (seqno < ring->sync_seqno[i]) {
/* The GPU can not handle its semaphore value wrapping,
* so every billion or so execbuffers, we need to stall
* the GPU in order to reset the counters.
*/
ret = i915_gpu_idle(dev, true);
if (ret)
goto err;
BUG_ON(ring->sync_seqno[i]);
}
}
if (ring == &dev_priv->ring[RCS] &&
mode != dev_priv->relative_constants_mode) {
ret = intel_ring_begin(ring, 4);
if (ret)
goto err;
intel_ring_emit(ring, MI_NOOP);
intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
intel_ring_emit(ring, INSTPM);
intel_ring_emit(ring, mask << 16 | mode);
intel_ring_advance(ring);
dev_priv->relative_constants_mode = mode;
}
if (args->flags & I915_EXEC_GEN7_SOL_RESET) {
ret = i915_reset_gen7_sol_offsets(dev, ring);
if (ret)
goto err;
}
trace_i915_gem_ring_dispatch(ring, seqno);
exec_start = batch_obj->gtt_offset + args->batch_start_offset;
exec_len = args->batch_len;
if (cliprects) {
for (i = 0; i < args->num_cliprects; i++) {
ret = i915_emit_box(dev, &cliprects[i],
args->DR1, args->DR4);
if (ret)
goto err;
ret = ring->dispatch_execbuffer(ring,
exec_start, exec_len);
if (ret)
goto err;
}
} else {
ret = ring->dispatch_execbuffer(ring, exec_start, exec_len);
if (ret)
goto err;
}
i915_gem_execbuffer_move_to_active(&objects, ring, seqno);
i915_gem_execbuffer_retire_commands(dev, file, ring);
err:
eb_destroy(eb);
while (!list_empty(&objects)) {
struct drm_i915_gem_object *obj;
obj = list_first_entry(&objects,
struct drm_i915_gem_object,
exec_list);
list_del_init(&obj->exec_list);
drm_gem_object_unreference(&obj->base);
}
mutex_unlock(&dev->struct_mutex);
pre_mutex_err:
kfree(cliprects);
return ret;
}
Commit Message: drm/i915: fix integer overflow in i915_gem_do_execbuffer()
On 32-bit systems, a large args->num_cliprects from userspace via ioctl
may overflow the allocation size, leading to out-of-bounds access.
This vulnerability was introduced in commit 432e58ed ("drm/i915: Avoid
allocation for execbuffer object list").
Signed-off-by: Xi Wang <[email protected]>
Reviewed-by: Chris Wilson <[email protected]>
Cc: [email protected]
Signed-off-by: Daniel Vetter <[email protected]>
CWE ID: CWE-189
|
i915_gem_do_execbuffer(struct drm_device *dev, void *data,
struct drm_file *file,
struct drm_i915_gem_execbuffer2 *args,
struct drm_i915_gem_exec_object2 *exec)
{
drm_i915_private_t *dev_priv = dev->dev_private;
struct list_head objects;
struct eb_objects *eb;
struct drm_i915_gem_object *batch_obj;
struct drm_clip_rect *cliprects = NULL;
struct intel_ring_buffer *ring;
u32 exec_start, exec_len;
u32 seqno;
u32 mask;
int ret, mode, i;
if (!i915_gem_check_execbuffer(args)) {
DRM_DEBUG("execbuf with invalid offset/length\n");
return -EINVAL;
}
ret = validate_exec_list(exec, args->buffer_count);
if (ret)
return ret;
switch (args->flags & I915_EXEC_RING_MASK) {
case I915_EXEC_DEFAULT:
case I915_EXEC_RENDER:
ring = &dev_priv->ring[RCS];
break;
case I915_EXEC_BSD:
if (!HAS_BSD(dev)) {
DRM_DEBUG("execbuf with invalid ring (BSD)\n");
return -EINVAL;
}
ring = &dev_priv->ring[VCS];
break;
case I915_EXEC_BLT:
if (!HAS_BLT(dev)) {
DRM_DEBUG("execbuf with invalid ring (BLT)\n");
return -EINVAL;
}
ring = &dev_priv->ring[BCS];
break;
default:
DRM_DEBUG("execbuf with unknown ring: %d\n",
(int)(args->flags & I915_EXEC_RING_MASK));
return -EINVAL;
}
mode = args->flags & I915_EXEC_CONSTANTS_MASK;
mask = I915_EXEC_CONSTANTS_MASK;
switch (mode) {
case I915_EXEC_CONSTANTS_REL_GENERAL:
case I915_EXEC_CONSTANTS_ABSOLUTE:
case I915_EXEC_CONSTANTS_REL_SURFACE:
if (ring == &dev_priv->ring[RCS] &&
mode != dev_priv->relative_constants_mode) {
if (INTEL_INFO(dev)->gen < 4)
return -EINVAL;
if (INTEL_INFO(dev)->gen > 5 &&
mode == I915_EXEC_CONSTANTS_REL_SURFACE)
return -EINVAL;
/* The HW changed the meaning on this bit on gen6 */
if (INTEL_INFO(dev)->gen >= 6)
mask &= ~I915_EXEC_CONSTANTS_REL_SURFACE;
}
break;
default:
DRM_DEBUG("execbuf with unknown constants: %d\n", mode);
return -EINVAL;
}
if (args->buffer_count < 1) {
DRM_DEBUG("execbuf with %d buffers\n", args->buffer_count);
return -EINVAL;
}
if (args->num_cliprects != 0) {
if (ring != &dev_priv->ring[RCS]) {
DRM_DEBUG("clip rectangles are only valid with the render ring\n");
return -EINVAL;
}
if (args->num_cliprects > UINT_MAX / sizeof(*cliprects)) {
DRM_DEBUG("execbuf with %u cliprects\n",
args->num_cliprects);
return -EINVAL;
}
cliprects = kmalloc(args->num_cliprects * sizeof(*cliprects),
GFP_KERNEL);
if (cliprects == NULL) {
ret = -ENOMEM;
goto pre_mutex_err;
}
if (copy_from_user(cliprects,
(struct drm_clip_rect __user *)(uintptr_t)
args->cliprects_ptr,
sizeof(*cliprects)*args->num_cliprects)) {
ret = -EFAULT;
goto pre_mutex_err;
}
}
ret = i915_mutex_lock_interruptible(dev);
if (ret)
goto pre_mutex_err;
if (dev_priv->mm.suspended) {
mutex_unlock(&dev->struct_mutex);
ret = -EBUSY;
goto pre_mutex_err;
}
eb = eb_create(args->buffer_count);
if (eb == NULL) {
mutex_unlock(&dev->struct_mutex);
ret = -ENOMEM;
goto pre_mutex_err;
}
/* Look up object handles */
INIT_LIST_HEAD(&objects);
for (i = 0; i < args->buffer_count; i++) {
struct drm_i915_gem_object *obj;
obj = to_intel_bo(drm_gem_object_lookup(dev, file,
exec[i].handle));
if (&obj->base == NULL) {
DRM_DEBUG("Invalid object handle %d at index %d\n",
exec[i].handle, i);
/* prevent error path from reading uninitialized data */
ret = -ENOENT;
goto err;
}
if (!list_empty(&obj->exec_list)) {
DRM_DEBUG("Object %p [handle %d, index %d] appears more than once in object list\n",
obj, exec[i].handle, i);
ret = -EINVAL;
goto err;
}
list_add_tail(&obj->exec_list, &objects);
obj->exec_handle = exec[i].handle;
obj->exec_entry = &exec[i];
eb_add_object(eb, obj);
}
/* take note of the batch buffer before we might reorder the lists */
batch_obj = list_entry(objects.prev,
struct drm_i915_gem_object,
exec_list);
/* Move the objects en-masse into the GTT, evicting if necessary. */
ret = i915_gem_execbuffer_reserve(ring, file, &objects);
if (ret)
goto err;
/* The objects are in their final locations, apply the relocations. */
ret = i915_gem_execbuffer_relocate(dev, eb, &objects);
if (ret) {
if (ret == -EFAULT) {
ret = i915_gem_execbuffer_relocate_slow(dev, file, ring,
&objects, eb,
exec,
args->buffer_count);
BUG_ON(!mutex_is_locked(&dev->struct_mutex));
}
if (ret)
goto err;
}
/* Set the pending read domains for the batch buffer to COMMAND */
if (batch_obj->base.pending_write_domain) {
DRM_DEBUG("Attempting to use self-modifying batch buffer\n");
ret = -EINVAL;
goto err;
}
batch_obj->base.pending_read_domains |= I915_GEM_DOMAIN_COMMAND;
ret = i915_gem_execbuffer_move_to_gpu(ring, &objects);
if (ret)
goto err;
seqno = i915_gem_next_request_seqno(ring);
for (i = 0; i < ARRAY_SIZE(ring->sync_seqno); i++) {
if (seqno < ring->sync_seqno[i]) {
/* The GPU can not handle its semaphore value wrapping,
* so every billion or so execbuffers, we need to stall
* the GPU in order to reset the counters.
*/
ret = i915_gpu_idle(dev, true);
if (ret)
goto err;
BUG_ON(ring->sync_seqno[i]);
}
}
if (ring == &dev_priv->ring[RCS] &&
mode != dev_priv->relative_constants_mode) {
ret = intel_ring_begin(ring, 4);
if (ret)
goto err;
intel_ring_emit(ring, MI_NOOP);
intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
intel_ring_emit(ring, INSTPM);
intel_ring_emit(ring, mask << 16 | mode);
intel_ring_advance(ring);
dev_priv->relative_constants_mode = mode;
}
if (args->flags & I915_EXEC_GEN7_SOL_RESET) {
ret = i915_reset_gen7_sol_offsets(dev, ring);
if (ret)
goto err;
}
trace_i915_gem_ring_dispatch(ring, seqno);
exec_start = batch_obj->gtt_offset + args->batch_start_offset;
exec_len = args->batch_len;
if (cliprects) {
for (i = 0; i < args->num_cliprects; i++) {
ret = i915_emit_box(dev, &cliprects[i],
args->DR1, args->DR4);
if (ret)
goto err;
ret = ring->dispatch_execbuffer(ring,
exec_start, exec_len);
if (ret)
goto err;
}
} else {
ret = ring->dispatch_execbuffer(ring, exec_start, exec_len);
if (ret)
goto err;
}
i915_gem_execbuffer_move_to_active(&objects, ring, seqno);
i915_gem_execbuffer_retire_commands(dev, file, ring);
err:
eb_destroy(eb);
while (!list_empty(&objects)) {
struct drm_i915_gem_object *obj;
obj = list_first_entry(&objects,
struct drm_i915_gem_object,
exec_list);
list_del_init(&obj->exec_list);
drm_gem_object_unreference(&obj->base);
}
mutex_unlock(&dev->struct_mutex);
pre_mutex_err:
kfree(cliprects);
return ret;
}
| 165,596 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool WtsSessionProcessDelegate::Core::Initialize(uint32 session_id) {
if (base::win::GetVersion() == base::win::VERSION_XP)
launch_elevated_ = false;
if (launch_elevated_) {
process_exit_event_.Set(CreateEvent(NULL, TRUE, FALSE, NULL));
if (!process_exit_event_.IsValid()) {
LOG(ERROR) << "Failed to create a nameless event";
return false;
}
io_task_runner_->PostTask(FROM_HERE,
base::Bind(&Core::InitializeJob, this));
}
return CreateSessionToken(session_id, &session_token_);
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool WtsSessionProcessDelegate::Core::Initialize(uint32 session_id) {
if (base::win::GetVersion() == base::win::VERSION_XP)
launch_elevated_ = false;
if (launch_elevated_) {
// GetNamedPipeClientProcessId() is available starting from Vista.
HMODULE kernel32 = ::GetModuleHandle(L"kernel32.dll");
CHECK(kernel32 != NULL);
get_named_pipe_client_pid_ =
reinterpret_cast<GetNamedPipeClientProcessIdFn>(
GetProcAddress(kernel32, "GetNamedPipeClientProcessId"));
CHECK(get_named_pipe_client_pid_ != NULL);
process_exit_event_.Set(CreateEvent(NULL, TRUE, FALSE, NULL));
if (!process_exit_event_.IsValid()) {
LOG(ERROR) << "Failed to create a nameless event";
return false;
}
io_task_runner_->PostTask(FROM_HERE,
base::Bind(&Core::InitializeJob, this));
}
return CreateSessionToken(session_id, &session_token_);
}
| 171,558 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void i8042_stop(struct serio *serio)
{
struct i8042_port *port = serio->port_data;
port->exists = false;
/*
* We synchronize with both AUX and KBD IRQs because there is
* a (very unlikely) chance that AUX IRQ is raised for KBD port
* and vice versa.
*/
synchronize_irq(I8042_AUX_IRQ);
synchronize_irq(I8042_KBD_IRQ);
port->serio = NULL;
}
Commit Message: Input: i8042 - fix crash at boot time
The driver checks port->exists twice in i8042_interrupt(), first when
trying to assign temporary "serio" variable, and second time when deciding
whether it should call serio_interrupt(). The value of port->exists may
change between the 2 checks, and we may end up calling serio_interrupt()
with a NULL pointer:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000050
IP: [<ffffffff8150feaf>] _spin_lock_irqsave+0x1f/0x40
PGD 0
Oops: 0002 [#1] SMP
last sysfs file:
CPU 0
Modules linked in:
Pid: 1, comm: swapper Not tainted 2.6.32-358.el6.x86_64 #1 QEMU Standard PC (i440FX + PIIX, 1996)
RIP: 0010:[<ffffffff8150feaf>] [<ffffffff8150feaf>] _spin_lock_irqsave+0x1f/0x40
RSP: 0018:ffff880028203cc0 EFLAGS: 00010082
RAX: 0000000000010000 RBX: 0000000000000000 RCX: 0000000000000000
RDX: 0000000000000282 RSI: 0000000000000098 RDI: 0000000000000050
RBP: ffff880028203cc0 R08: ffff88013e79c000 R09: ffff880028203ee0
R10: 0000000000000298 R11: 0000000000000282 R12: 0000000000000050
R13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000098
FS: 0000000000000000(0000) GS:ffff880028200000(0000) knlGS:0000000000000000
CS: 0010 DS: 0018 ES: 0018 CR0: 000000008005003b
CR2: 0000000000000050 CR3: 0000000001a85000 CR4: 00000000001407f0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
Process swapper (pid: 1, threadinfo ffff88013e79c000, task ffff88013e79b500)
Stack:
ffff880028203d00 ffffffff813de186 ffffffffffffff02 0000000000000000
<d> 0000000000000000 0000000000000000 0000000000000000 0000000000000098
<d> ffff880028203d70 ffffffff813e0162 ffff880028203d20 ffffffff8103b8ac
Call Trace:
<IRQ>
[<ffffffff813de186>] serio_interrupt+0x36/0xa0
[<ffffffff813e0162>] i8042_interrupt+0x132/0x3a0
[<ffffffff8103b8ac>] ? kvm_clock_read+0x1c/0x20
[<ffffffff8103b8b9>] ? kvm_clock_get_cycles+0x9/0x10
[<ffffffff810e1640>] handle_IRQ_event+0x60/0x170
[<ffffffff8103b154>] ? kvm_guest_apic_eoi_write+0x44/0x50
[<ffffffff810e3d8e>] handle_edge_irq+0xde/0x180
[<ffffffff8100de89>] handle_irq+0x49/0xa0
[<ffffffff81516c8c>] do_IRQ+0x6c/0xf0
[<ffffffff8100b9d3>] ret_from_intr+0x0/0x11
[<ffffffff81076f63>] ? __do_softirq+0x73/0x1e0
[<ffffffff8109b75b>] ? hrtimer_interrupt+0x14b/0x260
[<ffffffff8100c1cc>] ? call_softirq+0x1c/0x30
[<ffffffff8100de05>] ? do_softirq+0x65/0xa0
[<ffffffff81076d95>] ? irq_exit+0x85/0x90
[<ffffffff81516d80>] ? smp_apic_timer_interrupt+0x70/0x9b
[<ffffffff8100bb93>] ? apic_timer_interrupt+0x13/0x20
To avoid the issue let's change the second check to test whether serio is
NULL or not.
Also, let's take i8042_lock in i8042_start() and i8042_stop() instead of
trying to be overly smart and using memory barriers.
Signed-off-by: Chen Hong <[email protected]>
[dtor: take lock in i8042_start()/i8042_stop()]
Cc: [email protected]
Signed-off-by: Dmitry Torokhov <[email protected]>
CWE ID: CWE-476
|
static void i8042_stop(struct serio *serio)
{
struct i8042_port *port = serio->port_data;
spin_lock_irq(&i8042_lock);
port->exists = false;
port->serio = NULL;
spin_unlock_irq(&i8042_lock);
/*
* We need to make sure that interrupt handler finishes using
* our serio port before we return from this function.
* We synchronize with both AUX and KBD IRQs because there is
* a (very unlikely) chance that AUX IRQ is raised for KBD port
* and vice versa.
*/
synchronize_irq(I8042_AUX_IRQ);
synchronize_irq(I8042_KBD_IRQ);
}
| 169,423 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void chain_reply(struct smb_request *req)
{
size_t smblen = smb_len(req->inbuf);
size_t already_used, length_needed;
uint8_t chain_cmd;
uint32_t chain_offset; /* uint32_t to avoid overflow */
uint8_t wct;
uint16_t *vwv;
uint16_t buflen;
uint8_t *buf;
if (IVAL(req->outbuf, smb_rcls) != 0) {
fixup_chain_error_packet(req);
}
/*
* Any of the AndX requests and replies have at least a wct of
* 2. vwv[0] is the next command, vwv[1] is the offset from the
* beginning of the SMB header to the next wct field.
*
* None of the AndX requests put anything valuable in vwv[0] and [1],
* so we can overwrite it here to form the chain.
*/
if ((req->wct < 2) || (CVAL(req->outbuf, smb_wct) < 2)) {
goto error;
}
if (req->chain_outbuf == NULL) {
/*
* In req->chain_outbuf we collect all the replies. Start the
* chain by copying in the first reply.
*
* We do the realloc because later on we depend on
* talloc_get_size to determine the length of
* chain_outbuf. The reply_xxx routines might have
* over-allocated (reply_pipe_read_and_X used to be such an
* example).
*/
req->chain_outbuf = TALLOC_REALLOC_ARRAY(
req, req->outbuf, uint8_t, smb_len(req->outbuf) + 4);
if (req->chain_outbuf == NULL) {
goto error;
}
req->outbuf = NULL;
} else {
/*
* Update smb headers where subsequent chained commands
req->chain_outbuf = TALLOC_REALLOC_ARRAY(
req, req->outbuf, uint8_t, smb_len(req->outbuf) + 4);
if (req->chain_outbuf == NULL) {
goto error;
}
req->outbuf = NULL;
} else {
CVAL(req->outbuf, smb_wct),
(uint16_t *)(req->outbuf + smb_vwv),
0, smb_buflen(req->outbuf),
(uint8_t *)smb_buf(req->outbuf))) {
goto error;
}
TALLOC_FREE(req->outbuf);
}
/*
* We use the old request's vwv field to grab the next chained command
* and offset into the chained fields.
*/
chain_cmd = CVAL(req->vwv+0, 0);
chain_offset = SVAL(req->vwv+1, 0);
if (chain_cmd == 0xff) {
/*
* End of chain, no more requests from the client. So ship the
* replies.
*/
smb_setlen((char *)(req->chain_outbuf),
talloc_get_size(req->chain_outbuf) - 4);
if (!srv_send_smb(smbd_server_fd(), (char *)req->chain_outbuf,
true, req->seqnum+1,
IS_CONN_ENCRYPTED(req->conn)
||req->encrypted,
&req->pcd)) {
exit_server_cleanly("chain_reply: srv_send_smb "
"failed.");
}
TALLOC_FREE(req->chain_outbuf);
req->done = true;
return;
}
/* add a new perfcounter for this element of chain */
SMB_PERFCOUNT_ADD(&req->pcd);
SMB_PERFCOUNT_SET_OP(&req->pcd, chain_cmd);
SMB_PERFCOUNT_SET_MSGLEN_IN(&req->pcd, smblen);
/*
* Check if the client tries to fool us. The request so far uses the
* space to the end of the byte buffer in the request just
* processed. The chain_offset can't point into that area. If that was
* the case, we could end up with an endless processing of the chain,
* we would always handle the same request.
*/
already_used = PTR_DIFF(req->buf+req->buflen, smb_base(req->inbuf));
if (chain_offset < already_used) {
goto error;
}
/*
* Next check: Make sure the chain offset does not point beyond the
* overall smb request length.
*/
length_needed = chain_offset+1; /* wct */
if (length_needed > smblen) {
goto error;
}
/*
* Now comes the pointer magic. Goal here is to set up req->vwv and
* req->buf correctly again to be able to call the subsequent
* switch_message(). The chain offset (the former vwv[1]) points at
* the new wct field.
*/
wct = CVAL(smb_base(req->inbuf), chain_offset);
/*
* Next consistency check: Make the new vwv array fits in the overall
* smb request.
*/
length_needed += (wct+1)*sizeof(uint16_t); /* vwv+buflen */
if (length_needed > smblen) {
goto error;
}
vwv = (uint16_t *)(smb_base(req->inbuf) + chain_offset + 1);
/*
* Now grab the new byte buffer....
*/
buflen = SVAL(vwv+wct, 0);
/*
* .. and check that it fits.
*/
length_needed += buflen;
if (length_needed > smblen) {
goto error;
}
buf = (uint8_t *)(vwv+wct+1);
req->cmd = chain_cmd;
req->wct = wct;
req->vwv = vwv;
req->buflen = buflen;
req->buf = buf;
switch_message(chain_cmd, req, smblen);
if (req->outbuf == NULL) {
/*
* This happens if the chained command has suspended itself or
* if it has called srv_send_smb() itself.
*/
return;
}
/*
* We end up here if the chained command was not itself chained or
* suspended, but for example a close() command. We now need to splice
* the chained commands' outbuf into the already built up chain_outbuf
* and ship the result.
*/
goto done;
error:
/*
* We end up here if there's any error in the chain syntax. Report a
* DOS error, just like Windows does.
*/
reply_force_doserror(req, ERRSRV, ERRerror);
fixup_chain_error_packet(req);
done:
/*
* This scary statement intends to set the
* FLAGS2_32_BIT_ERROR_CODES flg2 field in req->chain_outbuf
* to the value req->outbuf carries
*/
SSVAL(req->chain_outbuf, smb_flg2,
(SVAL(req->chain_outbuf, smb_flg2) & ~FLAGS2_32_BIT_ERROR_CODES)
| (SVAL(req->outbuf, smb_flg2) & FLAGS2_32_BIT_ERROR_CODES));
/*
* Transfer the error codes from the subrequest to the main one
*/
SSVAL(req->chain_outbuf, smb_rcls, SVAL(req->outbuf, smb_rcls));
SSVAL(req->chain_outbuf, smb_err, SVAL(req->outbuf, smb_err));
if (!smb_splice_chain(&req->chain_outbuf,
CVAL(req->outbuf, smb_com),
CVAL(req->outbuf, smb_wct),
(uint16_t *)(req->outbuf + smb_vwv),
0, smb_buflen(req->outbuf),
(uint8_t *)smb_buf(req->outbuf))) {
exit_server_cleanly("chain_reply: smb_splice_chain failed\n");
}
TALLOC_FREE(req->outbuf);
smb_setlen((char *)(req->chain_outbuf),
talloc_get_size(req->chain_outbuf) - 4);
show_msg((char *)(req->chain_outbuf));
if (!srv_send_smb(smbd_server_fd(), (char *)req->chain_outbuf,
true, req->seqnum+1,
IS_CONN_ENCRYPTED(req->conn)||req->encrypted,
&req->pcd)) {
exit_server_cleanly("construct_reply: srv_send_smb failed.");
}
TALLOC_FREE(req->chain_outbuf);
req->done = true;
}
Commit Message:
CWE ID:
|
void chain_reply(struct smb_request *req)
{
size_t smblen = smb_len(req->inbuf);
size_t already_used, length_needed;
uint8_t chain_cmd;
uint32_t chain_offset; /* uint32_t to avoid overflow */
uint8_t wct;
uint16_t *vwv;
uint16_t buflen;
uint8_t *buf;
if (IVAL(req->outbuf, smb_rcls) != 0) {
fixup_chain_error_packet(req);
}
/*
* Any of the AndX requests and replies have at least a wct of
* 2. vwv[0] is the next command, vwv[1] is the offset from the
* beginning of the SMB header to the next wct field.
*
* None of the AndX requests put anything valuable in vwv[0] and [1],
* so we can overwrite it here to form the chain.
*/
if ((req->wct < 2) || (CVAL(req->outbuf, smb_wct) < 2)) {
if (req->chain_outbuf == NULL) {
req->chain_outbuf = TALLOC_REALLOC_ARRAY(
req, req->outbuf, uint8_t,
smb_len(req->outbuf) + 4);
if (req->chain_outbuf == NULL) {
smb_panic("talloc failed");
}
}
req->outbuf = NULL;
goto error;
}
if (req->chain_outbuf == NULL) {
/*
* In req->chain_outbuf we collect all the replies. Start the
* chain by copying in the first reply.
*
* We do the realloc because later on we depend on
* talloc_get_size to determine the length of
* chain_outbuf. The reply_xxx routines might have
* over-allocated (reply_pipe_read_and_X used to be such an
* example).
*/
req->chain_outbuf = TALLOC_REALLOC_ARRAY(
req, req->outbuf, uint8_t, smb_len(req->outbuf) + 4);
if (req->chain_outbuf == NULL) {
goto error;
}
req->outbuf = NULL;
} else {
/*
* Update smb headers where subsequent chained commands
req->chain_outbuf = TALLOC_REALLOC_ARRAY(
req, req->outbuf, uint8_t, smb_len(req->outbuf) + 4);
if (req->chain_outbuf == NULL) {
smb_panic("talloc failed");
}
req->outbuf = NULL;
} else {
CVAL(req->outbuf, smb_wct),
(uint16_t *)(req->outbuf + smb_vwv),
0, smb_buflen(req->outbuf),
(uint8_t *)smb_buf(req->outbuf))) {
goto error;
}
TALLOC_FREE(req->outbuf);
}
/*
* We use the old request's vwv field to grab the next chained command
* and offset into the chained fields.
*/
chain_cmd = CVAL(req->vwv+0, 0);
chain_offset = SVAL(req->vwv+1, 0);
if (chain_cmd == 0xff) {
/*
* End of chain, no more requests from the client. So ship the
* replies.
*/
smb_setlen((char *)(req->chain_outbuf),
talloc_get_size(req->chain_outbuf) - 4);
if (!srv_send_smb(smbd_server_fd(), (char *)req->chain_outbuf,
true, req->seqnum+1,
IS_CONN_ENCRYPTED(req->conn)
||req->encrypted,
&req->pcd)) {
exit_server_cleanly("chain_reply: srv_send_smb "
"failed.");
}
TALLOC_FREE(req->chain_outbuf);
req->done = true;
return;
}
/* add a new perfcounter for this element of chain */
SMB_PERFCOUNT_ADD(&req->pcd);
SMB_PERFCOUNT_SET_OP(&req->pcd, chain_cmd);
SMB_PERFCOUNT_SET_MSGLEN_IN(&req->pcd, smblen);
/*
* Check if the client tries to fool us. The request so far uses the
* space to the end of the byte buffer in the request just
* processed. The chain_offset can't point into that area. If that was
* the case, we could end up with an endless processing of the chain,
* we would always handle the same request.
*/
already_used = PTR_DIFF(req->buf+req->buflen, smb_base(req->inbuf));
if (chain_offset < already_used) {
goto error;
}
/*
* Next check: Make sure the chain offset does not point beyond the
* overall smb request length.
*/
length_needed = chain_offset+1; /* wct */
if (length_needed > smblen) {
goto error;
}
/*
* Now comes the pointer magic. Goal here is to set up req->vwv and
* req->buf correctly again to be able to call the subsequent
* switch_message(). The chain offset (the former vwv[1]) points at
* the new wct field.
*/
wct = CVAL(smb_base(req->inbuf), chain_offset);
/*
* Next consistency check: Make the new vwv array fits in the overall
* smb request.
*/
length_needed += (wct+1)*sizeof(uint16_t); /* vwv+buflen */
if (length_needed > smblen) {
goto error;
}
vwv = (uint16_t *)(smb_base(req->inbuf) + chain_offset + 1);
/*
* Now grab the new byte buffer....
*/
buflen = SVAL(vwv+wct, 0);
/*
* .. and check that it fits.
*/
length_needed += buflen;
if (length_needed > smblen) {
goto error;
}
buf = (uint8_t *)(vwv+wct+1);
req->cmd = chain_cmd;
req->wct = wct;
req->vwv = vwv;
req->buflen = buflen;
req->buf = buf;
switch_message(chain_cmd, req, smblen);
if (req->outbuf == NULL) {
/*
* This happens if the chained command has suspended itself or
* if it has called srv_send_smb() itself.
*/
return;
}
/*
* We end up here if the chained command was not itself chained or
* suspended, but for example a close() command. We now need to splice
* the chained commands' outbuf into the already built up chain_outbuf
* and ship the result.
*/
goto done;
error:
/*
* We end up here if there's any error in the chain syntax. Report a
* DOS error, just like Windows does.
*/
reply_force_doserror(req, ERRSRV, ERRerror);
fixup_chain_error_packet(req);
done:
/*
* This scary statement intends to set the
* FLAGS2_32_BIT_ERROR_CODES flg2 field in req->chain_outbuf
* to the value req->outbuf carries
*/
SSVAL(req->chain_outbuf, smb_flg2,
(SVAL(req->chain_outbuf, smb_flg2) & ~FLAGS2_32_BIT_ERROR_CODES)
| (SVAL(req->outbuf, smb_flg2) & FLAGS2_32_BIT_ERROR_CODES));
/*
* Transfer the error codes from the subrequest to the main one
*/
SSVAL(req->chain_outbuf, smb_rcls, SVAL(req->outbuf, smb_rcls));
SSVAL(req->chain_outbuf, smb_err, SVAL(req->outbuf, smb_err));
if (!smb_splice_chain(&req->chain_outbuf,
CVAL(req->outbuf, smb_com),
CVAL(req->outbuf, smb_wct),
(uint16_t *)(req->outbuf + smb_vwv),
0, smb_buflen(req->outbuf),
(uint8_t *)smb_buf(req->outbuf))) {
exit_server_cleanly("chain_reply: smb_splice_chain failed\n");
}
TALLOC_FREE(req->outbuf);
smb_setlen((char *)(req->chain_outbuf),
talloc_get_size(req->chain_outbuf) - 4);
show_msg((char *)(req->chain_outbuf));
if (!srv_send_smb(smbd_server_fd(), (char *)req->chain_outbuf,
true, req->seqnum+1,
IS_CONN_ENCRYPTED(req->conn)||req->encrypted,
&req->pcd)) {
exit_server_cleanly("construct_reply: srv_send_smb failed.");
}
TALLOC_FREE(req->chain_outbuf);
req->done = true;
}
| 165,055 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: bool VaapiJpegDecoder::Initialize(const base::RepeatingClosure& error_uma_cb) {
vaapi_wrapper_ = VaapiWrapper::Create(VaapiWrapper::kDecode,
VAProfileJPEGBaseline, error_uma_cb);
if (!vaapi_wrapper_) {
VLOGF(1) << "Failed initializing VAAPI";
return false;
}
return true;
}
Commit Message: Move Initialize() to VaapiImageDecoder parent class.
This CL moves the implementation of Initialize() to VaapiImageDecoder,
since it is common to all implementing classes.
Bug: 877694
Test: jpeg_decode_accelerator_unittest
Change-Id: Ic99601953ae1c7a572ba8a0b0bf43675b2b0969d
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1654249
Commit-Queue: Gil Dekel <[email protected]>
Reviewed-by: Andres Calderon Jaramillo <[email protected]>
Reviewed-by: Miguel Casas <[email protected]>
Cr-Commit-Position: refs/heads/master@{#668645}
CWE ID: CWE-79
|
bool VaapiJpegDecoder::Initialize(const base::RepeatingClosure& error_uma_cb) {
| 172,896 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void FrameSelection::MoveCaretSelection(const IntPoint& point) {
DCHECK(!GetDocument().NeedsLayoutTreeUpdate());
Element* const editable =
ComputeVisibleSelectionInDOMTree().RootEditableElement();
if (!editable)
return;
const VisiblePosition position =
VisiblePositionForContentsPoint(point, GetFrame());
SelectionInDOMTree::Builder builder;
builder.SetIsDirectional(GetSelectionInDOMTree().IsDirectional());
builder.SetIsHandleVisible(true);
if (position.IsNotNull())
builder.Collapse(position.ToPositionWithAffinity());
SetSelection(builder.Build(), SetSelectionData::Builder()
.SetShouldCloseTyping(true)
.SetShouldClearTypingStyle(true)
.SetSetSelectionBy(SetSelectionBy::kUser)
.Build());
}
Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection
This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate|
since handle visibility is used only for setting |FrameSelection|, hence it is
a redundant member variable of |SelectionTemplate|.
Bug: 742093
Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e
Reviewed-on: https://chromium-review.googlesource.com/595389
Commit-Queue: Yoshifumi Inoue <[email protected]>
Reviewed-by: Xiaocheng Hu <[email protected]>
Reviewed-by: Kent Tamura <[email protected]>
Cr-Commit-Position: refs/heads/master@{#491660}
CWE ID: CWE-119
|
void FrameSelection::MoveCaretSelection(const IntPoint& point) {
DCHECK(!GetDocument().NeedsLayoutTreeUpdate());
Element* const editable =
ComputeVisibleSelectionInDOMTree().RootEditableElement();
if (!editable)
return;
const VisiblePosition position =
VisiblePositionForContentsPoint(point, GetFrame());
SelectionInDOMTree::Builder builder;
builder.SetIsDirectional(GetSelectionInDOMTree().IsDirectional());
if (position.IsNotNull())
builder.Collapse(position.ToPositionWithAffinity());
SetSelection(builder.Build(), SetSelectionData::Builder()
.SetShouldCloseTyping(true)
.SetShouldClearTypingStyle(true)
.SetSetSelectionBy(SetSelectionBy::kUser)
.SetShouldShowHandle(true)
.Build());
}
| 171,756 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: xsltChoose(xsltTransformContextPtr ctxt, xmlNodePtr contextNode,
xmlNodePtr inst, xsltStylePreCompPtr comp ATTRIBUTE_UNUSED)
{
xmlNodePtr cur;
if ((ctxt == NULL) || (contextNode == NULL) || (inst == NULL))
return;
/*
* TODO: Content model checks should be done only at compilation
* time.
*/
cur = inst->children;
if (cur == NULL) {
xsltTransformError(ctxt, NULL, inst,
"xsl:choose: The instruction has no content.\n");
return;
}
#ifdef XSLT_REFACTORED
/*
* We don't check the content model during transformation.
*/
#else
if ((! IS_XSLT_ELEM(cur)) || (! IS_XSLT_NAME(cur, "when"))) {
xsltTransformError(ctxt, NULL, inst,
"xsl:choose: xsl:when expected first\n");
return;
}
#endif
{
int testRes = 0, res = 0;
xmlXPathContextPtr xpctxt = ctxt->xpathCtxt;
xmlDocPtr oldXPContextDoc = xpctxt->doc;
int oldXPProximityPosition = xpctxt->proximityPosition;
int oldXPContextSize = xpctxt->contextSize;
xmlNsPtr *oldXPNamespaces = xpctxt->namespaces;
int oldXPNsNr = xpctxt->nsNr;
#ifdef XSLT_REFACTORED
xsltStyleItemWhenPtr wcomp = NULL;
#else
xsltStylePreCompPtr wcomp = NULL;
#endif
/*
* Process xsl:when ---------------------------------------------------
*/
while (IS_XSLT_ELEM(cur) && IS_XSLT_NAME(cur, "when")) {
wcomp = cur->psvi;
if ((wcomp == NULL) || (wcomp->test == NULL) ||
(wcomp->comp == NULL))
{
xsltTransformError(ctxt, NULL, cur,
"Internal error in xsltChoose(): "
"The XSLT 'when' instruction was not compiled.\n");
goto error;
}
#ifdef WITH_DEBUGGER
if (xslDebugStatus != XSLT_DEBUG_NONE) {
/*
* TODO: Isn't comp->templ always NULL for xsl:choose?
*/
xslHandleDebugger(cur, contextNode, NULL, ctxt);
}
#endif
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_CHOOSE,xsltGenericDebug(xsltGenericDebugContext,
"xsltChoose: test %s\n", wcomp->test));
#endif
xpctxt->node = contextNode;
xpctxt->doc = oldXPContextDoc;
xpctxt->proximityPosition = oldXPProximityPosition;
xpctxt->contextSize = oldXPContextSize;
#ifdef XSLT_REFACTORED
if (wcomp->inScopeNs != NULL) {
xpctxt->namespaces = wcomp->inScopeNs->list;
xpctxt->nsNr = wcomp->inScopeNs->xpathNumber;
} else {
xpctxt->namespaces = NULL;
xpctxt->nsNr = 0;
}
#else
xpctxt->namespaces = wcomp->nsList;
xpctxt->nsNr = wcomp->nsNr;
#endif
#ifdef XSLT_FAST_IF
res = xmlXPathCompiledEvalToBoolean(wcomp->comp, xpctxt);
if (res == -1) {
ctxt->state = XSLT_STATE_STOPPED;
goto error;
}
testRes = (res == 1) ? 1 : 0;
#else /* XSLT_FAST_IF */
res = xmlXPathCompiledEval(wcomp->comp, xpctxt);
if (res != NULL) {
if (res->type != XPATH_BOOLEAN)
res = xmlXPathConvertBoolean(res);
if (res->type == XPATH_BOOLEAN)
testRes = res->boolval;
else {
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_CHOOSE,xsltGenericDebug(xsltGenericDebugContext,
"xsltChoose: test didn't evaluate to a boolean\n"));
#endif
goto error;
}
xmlXPathFreeObject(res);
res = NULL;
} else {
ctxt->state = XSLT_STATE_STOPPED;
goto error;
}
#endif /* else of XSLT_FAST_IF */
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_CHOOSE,xsltGenericDebug(xsltGenericDebugContext,
"xsltChoose: test evaluate to %d\n", testRes));
#endif
if (testRes)
goto test_is_true;
cur = cur->next;
}
/*
* Process xsl:otherwise ----------------------------------------------
*/
if (IS_XSLT_ELEM(cur) && IS_XSLT_NAME(cur, "otherwise")) {
#ifdef WITH_DEBUGGER
if (xslDebugStatus != XSLT_DEBUG_NONE)
xslHandleDebugger(cur, contextNode, NULL, ctxt);
#endif
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_CHOOSE,xsltGenericDebug(xsltGenericDebugContext,
"evaluating xsl:otherwise\n"));
#endif
goto test_is_true;
}
xpctxt->node = contextNode;
xpctxt->doc = oldXPContextDoc;
xpctxt->proximityPosition = oldXPProximityPosition;
xpctxt->contextSize = oldXPContextSize;
xpctxt->namespaces = oldXPNamespaces;
xpctxt->nsNr = oldXPNsNr;
goto exit;
test_is_true:
xpctxt->node = contextNode;
xpctxt->doc = oldXPContextDoc;
xpctxt->proximityPosition = oldXPProximityPosition;
xpctxt->contextSize = oldXPContextSize;
xpctxt->namespaces = oldXPNamespaces;
xpctxt->nsNr = oldXPNsNr;
goto process_sequence;
}
process_sequence:
/*
* Instantiate the sequence constructor.
*/
xsltApplySequenceConstructor(ctxt, ctxt->node, cur->children,
NULL);
exit:
error:
return;
}
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
|
xsltChoose(xsltTransformContextPtr ctxt, xmlNodePtr contextNode,
xmlNodePtr inst, xsltStylePreCompPtr comp ATTRIBUTE_UNUSED)
{
xmlNodePtr cur;
if ((ctxt == NULL) || (contextNode == NULL) || (inst == NULL))
return;
/*
* TODO: Content model checks should be done only at compilation
* time.
*/
cur = inst->children;
if (cur == NULL) {
xsltTransformError(ctxt, NULL, inst,
"xsl:choose: The instruction has no content.\n");
return;
}
#ifdef XSLT_REFACTORED
/*
* We don't check the content model during transformation.
*/
#else
if ((! IS_XSLT_ELEM(cur)) || (! IS_XSLT_NAME(cur, "when"))) {
xsltTransformError(ctxt, NULL, inst,
"xsl:choose: xsl:when expected first\n");
return;
}
#endif
{
int testRes = 0, res = 0;
#ifdef XSLT_REFACTORED
xsltStyleItemWhenPtr wcomp = NULL;
#else
xsltStylePreCompPtr wcomp = NULL;
#endif
/*
* Process xsl:when ---------------------------------------------------
*/
while (IS_XSLT_ELEM(cur) && IS_XSLT_NAME(cur, "when")) {
wcomp = cur->psvi;
if ((wcomp == NULL) || (wcomp->test == NULL) ||
(wcomp->comp == NULL))
{
xsltTransformError(ctxt, NULL, cur,
"Internal error in xsltChoose(): "
"The XSLT 'when' instruction was not compiled.\n");
goto error;
}
#ifdef WITH_DEBUGGER
if (xslDebugStatus != XSLT_DEBUG_NONE) {
/*
* TODO: Isn't comp->templ always NULL for xsl:choose?
*/
xslHandleDebugger(cur, contextNode, NULL, ctxt);
}
#endif
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_CHOOSE,xsltGenericDebug(xsltGenericDebugContext,
"xsltChoose: test %s\n", wcomp->test));
#endif
#ifdef XSLT_FAST_IF
res = xsltPreCompEvalToBoolean(ctxt, contextNode, wcomp);
if (res == -1) {
ctxt->state = XSLT_STATE_STOPPED;
goto error;
}
testRes = (res == 1) ? 1 : 0;
#else /* XSLT_FAST_IF */
res = xsltPreCompEval(ctxt, cotextNode, wcomp);
if (res != NULL) {
if (res->type != XPATH_BOOLEAN)
res = xmlXPathConvertBoolean(res);
if (res->type == XPATH_BOOLEAN)
testRes = res->boolval;
else {
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_CHOOSE,xsltGenericDebug(xsltGenericDebugContext,
"xsltChoose: test didn't evaluate to a boolean\n"));
#endif
goto error;
}
xmlXPathFreeObject(res);
res = NULL;
} else {
ctxt->state = XSLT_STATE_STOPPED;
goto error;
}
#endif /* else of XSLT_FAST_IF */
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_CHOOSE,xsltGenericDebug(xsltGenericDebugContext,
"xsltChoose: test evaluate to %d\n", testRes));
#endif
if (testRes)
goto test_is_true;
cur = cur->next;
}
/*
* Process xsl:otherwise ----------------------------------------------
*/
if (IS_XSLT_ELEM(cur) && IS_XSLT_NAME(cur, "otherwise")) {
#ifdef WITH_DEBUGGER
if (xslDebugStatus != XSLT_DEBUG_NONE)
xslHandleDebugger(cur, contextNode, NULL, ctxt);
#endif
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_CHOOSE,xsltGenericDebug(xsltGenericDebugContext,
"evaluating xsl:otherwise\n"));
#endif
goto test_is_true;
}
goto exit;
test_is_true:
goto process_sequence;
}
process_sequence:
/*
* Instantiate the sequence constructor.
*/
xsltApplySequenceConstructor(ctxt, ctxt->node, cur->children,
NULL);
exit:
error:
return;
}
| 173,321 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void UrlFetcherDownloader::StartURLFetch(const GURL& url) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (download_dir_.empty()) {
Result result;
result.error = -1;
DownloadMetrics download_metrics;
download_metrics.url = url;
download_metrics.downloader = DownloadMetrics::kUrlFetcher;
download_metrics.error = -1;
download_metrics.downloaded_bytes = -1;
download_metrics.total_bytes = -1;
download_metrics.download_time_ms = 0;
main_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&UrlFetcherDownloader::OnDownloadComplete,
base::Unretained(this), false, result,
download_metrics));
return;
}
const auto file_path = download_dir_.AppendASCII(url.ExtractFileName());
network_fetcher_ = network_fetcher_factory_->Create();
network_fetcher_->DownloadToFile(
url, file_path,
base::BindOnce(&UrlFetcherDownloader::OnResponseStarted,
base::Unretained(this)),
base::BindRepeating(&UrlFetcherDownloader::OnDownloadProgress,
base::Unretained(this)),
base::BindOnce(&UrlFetcherDownloader::OnNetworkFetcherComplete,
base::Unretained(this), file_path));
download_start_time_ = base::TimeTicks::Now();
}
Commit Message: Fix error handling in the request sender and url fetcher downloader.
That means handling the network errors by primarily looking at net_error.
Bug: 1028369
Change-Id: I8181bced25f8b56144ea336a03883d0dceea5108
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1935428
Reviewed-by: Joshua Pawlicki <[email protected]>
Commit-Queue: Sorin Jianu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#719199}
CWE ID: CWE-20
|
void UrlFetcherDownloader::StartURLFetch(const GURL& url) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (download_dir_.empty()) {
Result result;
result.error = -1;
DownloadMetrics download_metrics;
download_metrics.url = url;
download_metrics.downloader = DownloadMetrics::kUrlFetcher;
download_metrics.error = -1;
download_metrics.downloaded_bytes = -1;
download_metrics.total_bytes = -1;
download_metrics.download_time_ms = 0;
main_task_runner()->PostTask(
FROM_HERE, base::BindOnce(&UrlFetcherDownloader::OnDownloadComplete,
base::Unretained(this), false, result,
download_metrics));
return;
}
file_path_ = download_dir_.AppendASCII(url.ExtractFileName());
network_fetcher_ = network_fetcher_factory_->Create();
network_fetcher_->DownloadToFile(
url, file_path_,
base::BindOnce(&UrlFetcherDownloader::OnResponseStarted,
base::Unretained(this)),
base::BindRepeating(&UrlFetcherDownloader::OnDownloadProgress,
base::Unretained(this)),
base::BindOnce(&UrlFetcherDownloader::OnNetworkFetcherComplete,
base::Unretained(this)));
download_start_time_ = base::TimeTicks::Now();
}
| 172,366 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: MediaControlsHeaderView::MediaControlsHeaderView() {
SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kHorizontal, kMediaControlsHeaderInsets,
kMediaControlsHeaderChildSpacing));
auto app_icon_view = std::make_unique<views::ImageView>();
app_icon_view->SetImageSize(gfx::Size(kIconSize, kIconSize));
app_icon_view->SetVerticalAlignment(views::ImageView::Alignment::kLeading);
app_icon_view->SetHorizontalAlignment(views::ImageView::Alignment::kLeading);
app_icon_view->SetBorder(views::CreateEmptyBorder(kIconPadding));
app_icon_view->SetBackground(
views::CreateRoundedRectBackground(SK_ColorWHITE, kIconCornerRadius));
app_icon_view_ = AddChildView(std::move(app_icon_view));
gfx::Font default_font;
int font_size_delta = kHeaderTextFontSize - default_font.GetFontSize();
gfx::Font font = default_font.Derive(font_size_delta, gfx::Font::NORMAL,
gfx::Font::Weight::NORMAL);
gfx::FontList font_list(font);
auto app_name_view = std::make_unique<views::Label>();
app_name_view->SetFontList(font_list);
app_name_view->SetHorizontalAlignment(gfx::ALIGN_LEFT);
app_name_view->SetEnabledColor(SK_ColorWHITE);
app_name_view->SetAutoColorReadabilityEnabled(false);
app_name_view_ = AddChildView(std::move(app_name_view));
}
Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks
This CL rearranges the different components of the CrOS lock screen
media controls based on the newest mocks. This involves resizing most
of the child views and their spacings. The artwork was also resized
and re-positioned. Additionally, the close button was moved from the
main view to the header row child view.
Artist and title data about the current session will eventually be
placed to the right of the artwork, but right now this space is empty.
See the bug for before and after pictures.
Bug: 991647
Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554
Reviewed-by: Xiyuan Xia <[email protected]>
Reviewed-by: Becca Hughes <[email protected]>
Commit-Queue: Mia Bergeron <[email protected]>
Cr-Commit-Position: refs/heads/master@{#686253}
CWE ID: CWE-200
|
MediaControlsHeaderView::MediaControlsHeaderView() {
MediaControlsHeaderView::MediaControlsHeaderView(
base::OnceClosure close_button_cb)
: close_button_cb_(std::move(close_button_cb)) {
auto* layout = SetLayoutManager(std::make_unique<views::FlexLayout>());
layout->SetInteriorMargin(kHeaderViewInsets);
auto app_icon_view = std::make_unique<views::ImageView>();
app_icon_view->SetImageSize(gfx::Size(kIconSize, kIconSize));
app_icon_view->SetVerticalAlignment(views::ImageView::Alignment::kLeading);
app_icon_view->SetHorizontalAlignment(views::ImageView::Alignment::kLeading);
app_icon_view->SetBorder(views::CreateEmptyBorder(kIconPadding));
app_icon_view->SetBackground(
views::CreateRoundedRectBackground(SK_ColorWHITE, kIconCornerRadius));
app_icon_view_ = AddChildView(std::move(app_icon_view));
gfx::Font default_font;
int font_size_delta = kHeaderTextFontSize - default_font.GetFontSize();
gfx::Font font = default_font.Derive(font_size_delta, gfx::Font::NORMAL,
gfx::Font::Weight::NORMAL);
gfx::FontList font_list(font);
auto app_name_view = std::make_unique<views::Label>();
app_name_view->SetFontList(font_list);
app_name_view->SetHorizontalAlignment(gfx::ALIGN_LEFT);
app_name_view->SetEnabledColor(SK_ColorWHITE);
app_name_view->SetAutoColorReadabilityEnabled(false);
app_name_view->SetBorder(views::CreateEmptyBorder(kAppNamePadding));
app_name_view_ = AddChildView(std::move(app_name_view));
// Space between app name and close button.
auto spacer = std::make_unique<NonAccessibleView>();
spacer->SetPreferredSize(kSpacerPreferredSize);
spacer->SetProperty(views::kFlexBehaviorKey,
views::FlexSpecification::ForSizeRule(
views::MinimumFlexSizeRule::kScaleToMinimum,
views::MaximumFlexSizeRule::kUnbounded));
AddChildView(std::move(spacer));
auto close_button = CreateVectorImageButton(this);
SetImageFromVectorIcon(close_button.get(), vector_icons::kCloseRoundedIcon,
kCloseButtonIconSize, gfx::kGoogleGrey700);
close_button->SetPreferredSize(kCloseButtonSize);
close_button->SetFocusBehavior(View::FocusBehavior::ALWAYS);
base::string16 close_button_label(
l10n_util::GetStringUTF16(IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_CLOSE));
close_button->SetAccessibleName(close_button_label);
close_button->SetVisible(false);
close_button_ = AddChildView(std::move(close_button));
}
| 172,344 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: FileTransfer::DoUpload(filesize_t *total_bytes, ReliSock *s)
{
int rc;
MyString fullname;
filesize_t bytes;
bool is_the_executable;
bool upload_success = false;
bool do_download_ack = false;
bool do_upload_ack = false;
bool try_again = false;
int hold_code = 0;
int hold_subcode = 0;
MyString error_desc;
bool I_go_ahead_always = false;
bool peer_goes_ahead_always = false;
DCTransferQueue xfer_queue(m_xfer_queue_contact_info);
CondorError errstack;
bool first_failed_file_transfer_happened = false;
bool first_failed_upload_success = false;
bool first_failed_try_again = false;
int first_failed_hold_code = 0;
int first_failed_hold_subcode = 0;
MyString first_failed_error_desc;
int first_failed_line_number;
*total_bytes = 0;
dprintf(D_FULLDEBUG,"entering FileTransfer::DoUpload\n");
priv_state saved_priv = PRIV_UNKNOWN;
if( want_priv_change ) {
saved_priv = set_priv( desired_priv_state );
}
s->encode();
if( !s->code(m_final_transfer_flag) ) {
dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
if( !s->end_of_message() ) {
dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
bool socket_default_crypto = s->get_encryption();
if( want_priv_change && saved_priv == PRIV_UNKNOWN ) {
saved_priv = set_priv( desired_priv_state );
}
FileTransferList filelist;
ExpandFileTransferList( FilesToSend, filelist );
FileTransferList::iterator filelist_it;
for( filelist_it = filelist.begin();
filelist_it != filelist.end();
filelist_it++ )
{
char const *filename = filelist_it->srcName();
char const *dest_dir = filelist_it->destDir();
if( dest_dir && *dest_dir ) {
dprintf(D_FULLDEBUG,"DoUpload: sending file %s to %s%c\n",filename,dest_dir,DIR_DELIM_CHAR);
}
else {
dprintf(D_FULLDEBUG,"DoUpload: sending file %s\n",filename);
}
bool is_url;
is_url = false;
if( param_boolean("ENABLE_URL_TRANSFERS", true) && IsUrl(filename) ) {
is_url = true;
fullname = filename;
dprintf(D_FULLDEBUG, "DoUpload: sending %s as URL.\n", filename);
} else if( filename[0] != '/' && filename[0] != '\\' && filename[1] != ':' ){
fullname.sprintf("%s%c%s",Iwd,DIR_DELIM_CHAR,filename);
} else {
fullname = filename;
}
#ifdef WIN32
if( !is_url && perm_obj && !is_the_executable &&
(perm_obj->read_access(fullname.Value()) != 1) ) {
upload_success = false;
error_desc.sprintf("error reading from %s: permission denied",fullname.Value());
do_upload_ack = true; // tell receiver that we failed
do_download_ack = true;
try_again = false; // put job on hold
hold_code = CONDOR_HOLD_CODE_UploadFileError;
hold_subcode = EPERM;
return ExitDoUpload(total_bytes,s,saved_priv,socket_default_crypto,
upload_success,do_upload_ack,do_download_ack,
try_again,hold_code,hold_subcode,
error_desc.Value(),__LINE__);
}
#endif
if (is_the_executable) {} // Done to get rid of the compiler set-but-not-used warnings.
int file_command = 1;
int file_subcommand = 0;
if ( DontEncryptFiles->file_contains_withwildcard(filename) ) {
file_command = 3;
}
if ( EncryptFiles->file_contains_withwildcard(filename) ) {
file_command = 2;
}
if ( X509UserProxy && file_strcmp( filename, X509UserProxy ) == 0 &&
DelegateX509Credentials ) {
file_command = 4;
}
if ( is_url ) {
file_command = 5;
}
if ( m_final_transfer_flag && OutputDestination ) {
dprintf(D_FULLDEBUG, "FILETRANSFER: Using command 999:7 for OutputDestionation: %s\n",
OutputDestination);
file_command = 999;
file_subcommand = 7;
}
bool fail_because_mkdir_not_supported = false;
bool fail_because_symlink_not_supported = false;
if( filelist_it->is_directory ) {
if( filelist_it->is_symlink ) {
fail_because_symlink_not_supported = true;
dprintf(D_ALWAYS,"DoUpload: attempting to transfer symlink %s which points to a directory. This is not supported.\n",filename);
}
else if( PeerUnderstandsMkdir ) {
file_command = 6;
}
else {
fail_because_mkdir_not_supported = true;
dprintf(D_ALWAYS,"DoUpload: attempting to transfer directory %s, but the version of Condor we are talking to is too old to support that!\n",
filename);
}
}
dprintf ( D_FULLDEBUG, "FILETRANSFER: outgoing file_command is %i for %s\n",
file_command, filename );
if( !s->snd_int(file_command,FALSE) ) {
dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
if( !s->end_of_message() ) {
dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
if (file_command == 2) {
s->set_crypto_mode(true);
} else if (file_command == 3) {
s->set_crypto_mode(false);
}
else {
s->set_crypto_mode(socket_default_crypto);
}
MyString dest_filename;
if ( ExecFile && !simple_init && (file_strcmp(ExecFile,filename)==0 )) {
is_the_executable = true;
dest_filename = CONDOR_EXEC;
} else {
is_the_executable = false;
if( dest_dir && *dest_dir ) {
dest_filename.sprintf("%s%c",dest_dir,DIR_DELIM_CHAR);
}
dest_filename.sprintf_cat( condor_basename(filename) );
}
if( !s->put(dest_filename.Value()) ) {
dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
if( PeerDoesGoAhead ) {
if( !s->end_of_message() ) {
dprintf(D_FULLDEBUG, "DoUpload: failed on eom before GoAhead; exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
if( !peer_goes_ahead_always ) {
if( !ReceiveTransferGoAhead(s,fullname.Value(),false,peer_goes_ahead_always) ) {
dprintf(D_FULLDEBUG, "DoUpload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
}
if( !I_go_ahead_always ) {
if( !ObtainAndSendTransferGoAhead(xfer_queue,false,s,fullname.Value(),I_go_ahead_always) ) {
dprintf(D_FULLDEBUG, "DoUpload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
}
s->encode();
}
if ( file_command == 999) {
ClassAd file_info;
file_info.Assign("ProtocolVersion", 1);
file_info.Assign("Command", file_command);
file_info.Assign("SubCommand", file_subcommand);
if(file_subcommand == 7) {
MyString source_filename;
source_filename = Iwd;
source_filename += DIR_DELIM_CHAR;
source_filename += filename;
MyString URL;
URL = OutputDestination;
URL += DIR_DELIM_CHAR;
URL += filename;
dprintf (D_FULLDEBUG, "DoUpload: calling IFTP(fn,U): fn\"%s\", U\"%s\"\n", source_filename.Value(), URL.Value());
dprintf (D_FULLDEBUG, "LocalProxyName: %s\n", LocalProxyName.Value());
rc = InvokeFileTransferPlugin(errstack, source_filename.Value(), URL.Value(), LocalProxyName.Value());
dprintf (D_FULLDEBUG, "DoUpload: IFTP(fn,U): fn\"%s\", U\"%s\" returns %i\n", source_filename.Value(), URL.Value(), rc);
file_info.Assign("Filename", source_filename);
file_info.Assign("OutputDestination", URL);
file_info.Assign("Result", rc);
if (rc) {
file_info.Assign("ErrorString", errstack.getFullText());
}
if(!file_info.put(*s)) {
dprintf(D_FULLDEBUG,"DoDownload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
MyString junkbuf;
file_info.sPrint(junkbuf);
bytes = junkbuf.Length();
} else {
dprintf( D_ALWAYS, "DoUpload: invalid subcommand %i, skipping %s.",
file_subcommand, filename);
bytes = 0;
rc = 0;
}
} else if ( file_command == 4 ) {
if ( (PeerDoesGoAhead || s->end_of_message()) ) {
time_t expiration_time = GetDesiredDelegatedJobCredentialExpiration(&jobAd);
rc = s->put_x509_delegation( &bytes, fullname.Value(), expiration_time, NULL );
dprintf( D_FULLDEBUG,
"DoUpload: put_x509_delegation() returned %d\n",
rc );
} else {
rc = -1;
}
} else if (file_command == 5) {
if(!s->code(fullname)) {
dprintf( D_FULLDEBUG, "DoUpload: failed to send fullname: %s\n", fullname.Value());
rc = -1;
} else {
dprintf( D_FULLDEBUG, "DoUpload: sent fullname and NO eom: %s\n", fullname.Value());
rc = 0;
}
bytes = fullname.Length();
} else if( file_command == 6 ) { // mkdir
bytes = sizeof( filelist_it->file_mode );
if( !s->put( filelist_it->file_mode ) ) {
rc = -1;
dprintf(D_ALWAYS,"DoUpload: failed to send mkdir mode\n");
}
else {
rc = 0;
}
} else if( fail_because_mkdir_not_supported || fail_because_symlink_not_supported ) {
if( TransferFilePermissions ) {
rc = s->put_file_with_permissions( &bytes, NULL_FILE );
}
else {
rc = s->put_file( &bytes, NULL_FILE );
}
if( rc == 0 ) {
rc = PUT_FILE_OPEN_FAILED;
errno = EISDIR;
}
} else if ( TransferFilePermissions ) {
rc = s->put_file_with_permissions( &bytes, fullname.Value() );
} else {
rc = s->put_file( &bytes, fullname.Value() );
}
if( rc < 0 ) {
int the_error = errno;
upload_success = false;
error_desc.sprintf("error sending %s",fullname.Value());
if((rc == PUT_FILE_OPEN_FAILED) || (rc == PUT_FILE_PLUGIN_FAILED)) {
if (rc == PUT_FILE_OPEN_FAILED) {
error_desc.replaceString("sending","reading from");
error_desc.sprintf_cat(": (errno %d) %s",the_error,strerror(the_error));
if( fail_because_mkdir_not_supported ) {
error_desc.sprintf_cat("; Remote condor version is too old to transfer directories.");
}
if( fail_because_symlink_not_supported ) {
error_desc.sprintf_cat("; Transfer of symlinks to directories is not supported.");
}
} else {
error_desc.sprintf_cat(": %s", errstack.getFullText());
}
try_again = false; // put job on hold
hold_code = CONDOR_HOLD_CODE_UploadFileError;
hold_subcode = the_error;
if (first_failed_file_transfer_happened == false) {
first_failed_file_transfer_happened = true;
first_failed_upload_success = false;
first_failed_try_again = false;
first_failed_hold_code = hold_code;
first_failed_hold_subcode = the_error;
first_failed_error_desc = error_desc;
first_failed_line_number = __LINE__;
}
}
else {
do_download_ack = true;
do_upload_ack = false;
try_again = true;
return ExitDoUpload(total_bytes,s,saved_priv,
socket_default_crypto,upload_success,
do_upload_ack,do_download_ack,
try_again,hold_code,hold_subcode,
error_desc.Value(),__LINE__);
}
}
if( !s->end_of_message() ) {
dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
*total_bytes += bytes;
if( dest_filename.FindChar(DIR_DELIM_CHAR) < 0 &&
dest_filename != condor_basename(JobStdoutFile.Value()) &&
dest_filename != condor_basename(JobStderrFile.Value()) )
{
Info.addSpooledFile( dest_filename.Value() );
}
}
do_download_ack = true;
do_upload_ack = true;
if (first_failed_file_transfer_happened == true) {
return ExitDoUpload(total_bytes,s,saved_priv,socket_default_crypto,
first_failed_upload_success,do_upload_ack,do_download_ack,
first_failed_try_again,first_failed_hold_code,
first_failed_hold_subcode,first_failed_error_desc.Value(),
first_failed_line_number);
}
upload_success = true;
return ExitDoUpload(total_bytes,s,saved_priv,socket_default_crypto,
upload_success,do_upload_ack,do_download_ack,
try_again,hold_code,hold_subcode,NULL,__LINE__);
}
Commit Message:
CWE ID: CWE-134
|
FileTransfer::DoUpload(filesize_t *total_bytes, ReliSock *s)
{
int rc;
MyString fullname;
filesize_t bytes;
bool is_the_executable;
bool upload_success = false;
bool do_download_ack = false;
bool do_upload_ack = false;
bool try_again = false;
int hold_code = 0;
int hold_subcode = 0;
MyString error_desc;
bool I_go_ahead_always = false;
bool peer_goes_ahead_always = false;
DCTransferQueue xfer_queue(m_xfer_queue_contact_info);
CondorError errstack;
bool first_failed_file_transfer_happened = false;
bool first_failed_upload_success = false;
bool first_failed_try_again = false;
int first_failed_hold_code = 0;
int first_failed_hold_subcode = 0;
MyString first_failed_error_desc;
int first_failed_line_number;
*total_bytes = 0;
dprintf(D_FULLDEBUG,"entering FileTransfer::DoUpload\n");
priv_state saved_priv = PRIV_UNKNOWN;
if( want_priv_change ) {
saved_priv = set_priv( desired_priv_state );
}
s->encode();
if( !s->code(m_final_transfer_flag) ) {
dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
if( !s->end_of_message() ) {
dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
bool socket_default_crypto = s->get_encryption();
if( want_priv_change && saved_priv == PRIV_UNKNOWN ) {
saved_priv = set_priv( desired_priv_state );
}
FileTransferList filelist;
ExpandFileTransferList( FilesToSend, filelist );
FileTransferList::iterator filelist_it;
for( filelist_it = filelist.begin();
filelist_it != filelist.end();
filelist_it++ )
{
char const *filename = filelist_it->srcName();
char const *dest_dir = filelist_it->destDir();
if( dest_dir && *dest_dir ) {
dprintf(D_FULLDEBUG,"DoUpload: sending file %s to %s%c\n",filename,dest_dir,DIR_DELIM_CHAR);
}
else {
dprintf(D_FULLDEBUG,"DoUpload: sending file %s\n",filename);
}
bool is_url;
is_url = false;
if( param_boolean("ENABLE_URL_TRANSFERS", true) && IsUrl(filename) ) {
is_url = true;
fullname = filename;
dprintf(D_FULLDEBUG, "DoUpload: sending %s as URL.\n", filename);
} else if( filename[0] != '/' && filename[0] != '\\' && filename[1] != ':' ){
fullname.sprintf("%s%c%s",Iwd,DIR_DELIM_CHAR,filename);
} else {
fullname = filename;
}
#ifdef WIN32
if( !is_url && perm_obj && !is_the_executable &&
(perm_obj->read_access(fullname.Value()) != 1) ) {
upload_success = false;
error_desc.sprintf("error reading from %s: permission denied",fullname.Value());
do_upload_ack = true; // tell receiver that we failed
do_download_ack = true;
try_again = false; // put job on hold
hold_code = CONDOR_HOLD_CODE_UploadFileError;
hold_subcode = EPERM;
return ExitDoUpload(total_bytes,s,saved_priv,socket_default_crypto,
upload_success,do_upload_ack,do_download_ack,
try_again,hold_code,hold_subcode,
error_desc.Value(),__LINE__);
}
#endif
if (is_the_executable) {} // Done to get rid of the compiler set-but-not-used warnings.
int file_command = 1;
int file_subcommand = 0;
if ( DontEncryptFiles->file_contains_withwildcard(filename) ) {
file_command = 3;
}
if ( EncryptFiles->file_contains_withwildcard(filename) ) {
file_command = 2;
}
if ( X509UserProxy && file_strcmp( filename, X509UserProxy ) == 0 &&
DelegateX509Credentials ) {
file_command = 4;
}
if ( is_url ) {
file_command = 5;
}
if ( m_final_transfer_flag && OutputDestination ) {
dprintf(D_FULLDEBUG, "FILETRANSFER: Using command 999:7 for OutputDestionation: %s\n",
OutputDestination);
file_command = 999;
file_subcommand = 7;
}
bool fail_because_mkdir_not_supported = false;
bool fail_because_symlink_not_supported = false;
if( filelist_it->is_directory ) {
if( filelist_it->is_symlink ) {
fail_because_symlink_not_supported = true;
dprintf(D_ALWAYS,"DoUpload: attempting to transfer symlink %s which points to a directory. This is not supported.\n",filename);
}
else if( PeerUnderstandsMkdir ) {
file_command = 6;
}
else {
fail_because_mkdir_not_supported = true;
dprintf(D_ALWAYS,"DoUpload: attempting to transfer directory %s, but the version of Condor we are talking to is too old to support that!\n",
filename);
}
}
dprintf ( D_FULLDEBUG, "FILETRANSFER: outgoing file_command is %i for %s\n",
file_command, filename );
if( !s->snd_int(file_command,FALSE) ) {
dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
if( !s->end_of_message() ) {
dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
if (file_command == 2) {
s->set_crypto_mode(true);
} else if (file_command == 3) {
s->set_crypto_mode(false);
}
else {
s->set_crypto_mode(socket_default_crypto);
}
MyString dest_filename;
if ( ExecFile && !simple_init && (file_strcmp(ExecFile,filename)==0 )) {
is_the_executable = true;
dest_filename = CONDOR_EXEC;
} else {
is_the_executable = false;
if( dest_dir && *dest_dir ) {
dest_filename.sprintf("%s%c",dest_dir,DIR_DELIM_CHAR);
}
dest_filename.sprintf_cat( "%s", condor_basename(filename) );
}
if( !s->put(dest_filename.Value()) ) {
dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
if( PeerDoesGoAhead ) {
if( !s->end_of_message() ) {
dprintf(D_FULLDEBUG, "DoUpload: failed on eom before GoAhead; exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
if( !peer_goes_ahead_always ) {
if( !ReceiveTransferGoAhead(s,fullname.Value(),false,peer_goes_ahead_always) ) {
dprintf(D_FULLDEBUG, "DoUpload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
}
if( !I_go_ahead_always ) {
if( !ObtainAndSendTransferGoAhead(xfer_queue,false,s,fullname.Value(),I_go_ahead_always) ) {
dprintf(D_FULLDEBUG, "DoUpload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
}
s->encode();
}
if ( file_command == 999) {
ClassAd file_info;
file_info.Assign("ProtocolVersion", 1);
file_info.Assign("Command", file_command);
file_info.Assign("SubCommand", file_subcommand);
if(file_subcommand == 7) {
MyString source_filename;
source_filename = Iwd;
source_filename += DIR_DELIM_CHAR;
source_filename += filename;
MyString URL;
URL = OutputDestination;
URL += DIR_DELIM_CHAR;
URL += filename;
dprintf (D_FULLDEBUG, "DoUpload: calling IFTP(fn,U): fn\"%s\", U\"%s\"\n", source_filename.Value(), URL.Value());
dprintf (D_FULLDEBUG, "LocalProxyName: %s\n", LocalProxyName.Value());
rc = InvokeFileTransferPlugin(errstack, source_filename.Value(), URL.Value(), LocalProxyName.Value());
dprintf (D_FULLDEBUG, "DoUpload: IFTP(fn,U): fn\"%s\", U\"%s\" returns %i\n", source_filename.Value(), URL.Value(), rc);
file_info.Assign("Filename", source_filename);
file_info.Assign("OutputDestination", URL);
file_info.Assign("Result", rc);
if (rc) {
file_info.Assign("ErrorString", errstack.getFullText());
}
if(!file_info.put(*s)) {
dprintf(D_FULLDEBUG,"DoDownload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
MyString junkbuf;
file_info.sPrint(junkbuf);
bytes = junkbuf.Length();
} else {
dprintf( D_ALWAYS, "DoUpload: invalid subcommand %i, skipping %s.",
file_subcommand, filename);
bytes = 0;
rc = 0;
}
} else if ( file_command == 4 ) {
if ( (PeerDoesGoAhead || s->end_of_message()) ) {
time_t expiration_time = GetDesiredDelegatedJobCredentialExpiration(&jobAd);
rc = s->put_x509_delegation( &bytes, fullname.Value(), expiration_time, NULL );
dprintf( D_FULLDEBUG,
"DoUpload: put_x509_delegation() returned %d\n",
rc );
} else {
rc = -1;
}
} else if (file_command == 5) {
if(!s->code(fullname)) {
dprintf( D_FULLDEBUG, "DoUpload: failed to send fullname: %s\n", fullname.Value());
rc = -1;
} else {
dprintf( D_FULLDEBUG, "DoUpload: sent fullname and NO eom: %s\n", fullname.Value());
rc = 0;
}
bytes = fullname.Length();
} else if( file_command == 6 ) { // mkdir
bytes = sizeof( filelist_it->file_mode );
if( !s->put( filelist_it->file_mode ) ) {
rc = -1;
dprintf(D_ALWAYS,"DoUpload: failed to send mkdir mode\n");
}
else {
rc = 0;
}
} else if( fail_because_mkdir_not_supported || fail_because_symlink_not_supported ) {
if( TransferFilePermissions ) {
rc = s->put_file_with_permissions( &bytes, NULL_FILE );
}
else {
rc = s->put_file( &bytes, NULL_FILE );
}
if( rc == 0 ) {
rc = PUT_FILE_OPEN_FAILED;
errno = EISDIR;
}
} else if ( TransferFilePermissions ) {
rc = s->put_file_with_permissions( &bytes, fullname.Value() );
} else {
rc = s->put_file( &bytes, fullname.Value() );
}
if( rc < 0 ) {
int the_error = errno;
upload_success = false;
error_desc.sprintf("error sending %s",fullname.Value());
if((rc == PUT_FILE_OPEN_FAILED) || (rc == PUT_FILE_PLUGIN_FAILED)) {
if (rc == PUT_FILE_OPEN_FAILED) {
error_desc.replaceString("sending","reading from");
error_desc.sprintf_cat(": (errno %d) %s",the_error,strerror(the_error));
if( fail_because_mkdir_not_supported ) {
error_desc.sprintf_cat("; Remote condor version is too old to transfer directories.");
}
if( fail_because_symlink_not_supported ) {
error_desc.sprintf_cat("; Transfer of symlinks to directories is not supported.");
}
} else {
error_desc.sprintf_cat(": %s", errstack.getFullText());
}
try_again = false; // put job on hold
hold_code = CONDOR_HOLD_CODE_UploadFileError;
hold_subcode = the_error;
if (first_failed_file_transfer_happened == false) {
first_failed_file_transfer_happened = true;
first_failed_upload_success = false;
first_failed_try_again = false;
first_failed_hold_code = hold_code;
first_failed_hold_subcode = the_error;
first_failed_error_desc = error_desc;
first_failed_line_number = __LINE__;
}
}
else {
do_download_ack = true;
do_upload_ack = false;
try_again = true;
return ExitDoUpload(total_bytes,s,saved_priv,
socket_default_crypto,upload_success,
do_upload_ack,do_download_ack,
try_again,hold_code,hold_subcode,
error_desc.Value(),__LINE__);
}
}
if( !s->end_of_message() ) {
dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__);
return_and_resetpriv( -1 );
}
*total_bytes += bytes;
if( dest_filename.FindChar(DIR_DELIM_CHAR) < 0 &&
dest_filename != condor_basename(JobStdoutFile.Value()) &&
dest_filename != condor_basename(JobStderrFile.Value()) )
{
Info.addSpooledFile( dest_filename.Value() );
}
}
do_download_ack = true;
do_upload_ack = true;
if (first_failed_file_transfer_happened == true) {
return ExitDoUpload(total_bytes,s,saved_priv,socket_default_crypto,
first_failed_upload_success,do_upload_ack,do_download_ack,
first_failed_try_again,first_failed_hold_code,
first_failed_hold_subcode,first_failed_error_desc.Value(),
first_failed_line_number);
}
upload_success = true;
return ExitDoUpload(total_bytes,s,saved_priv,socket_default_crypto,
upload_success,do_upload_ack,do_download_ack,
try_again,hold_code,hold_subcode,NULL,__LINE__);
}
| 165,386 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void RunRoundTripErrorCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
int max_error = 0;
int total_error = 0;
const int count_test_block = 100000;
DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, 64);
DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, 64);
DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, 64);
DECLARE_ALIGNED_ARRAY(16, uint8_t, src, 64);
for (int i = 0; i < count_test_block; ++i) {
for (int j = 0; j < 64; ++j) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
test_input_block[j] = src[j] - dst[j];
}
REGISTER_STATE_CHECK(
RunFwdTxfm(test_input_block, test_temp_block, pitch_));
for (int j = 0; j < 64; ++j) {
if (test_temp_block[j] > 0) {
test_temp_block[j] += 2;
test_temp_block[j] /= 4;
test_temp_block[j] *= 4;
} else {
test_temp_block[j] -= 2;
test_temp_block[j] /= 4;
test_temp_block[j] *= 4;
}
}
REGISTER_STATE_CHECK(
RunInvTxfm(test_temp_block, dst, pitch_));
for (int j = 0; j < 64; ++j) {
const int diff = dst[j] - src[j];
const int error = diff * diff;
if (max_error < error)
max_error = error;
total_error += error;
}
}
EXPECT_GE(1, max_error)
<< "Error: 8x8 FDCT/IDCT or FHT/IHT has an individual"
<< " roundtrip error > 1";
EXPECT_GE(count_test_block/5, total_error)
<< "Error: 8x8 FDCT/IDCT or FHT/IHT has average roundtrip "
<< "error > 1/5 per block";
}
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 RunRoundTripErrorCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
int max_error = 0;
int total_error = 0;
const int count_test_block = 100000;
DECLARE_ALIGNED(16, int16_t, test_input_block[64]);
DECLARE_ALIGNED(16, tran_low_t, test_temp_block[64]);
DECLARE_ALIGNED(16, uint8_t, dst[64]);
DECLARE_ALIGNED(16, uint8_t, src[64]);
#if CONFIG_VP9_HIGHBITDEPTH
DECLARE_ALIGNED(16, uint16_t, dst16[64]);
DECLARE_ALIGNED(16, uint16_t, src16[64]);
#endif
for (int i = 0; i < count_test_block; ++i) {
// Initialize a test block with input range [-mask_, mask_].
for (int j = 0; j < 64; ++j) {
if (bit_depth_ == VPX_BITS_8) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
test_input_block[j] = src[j] - dst[j];
#if CONFIG_VP9_HIGHBITDEPTH
} else {
src16[j] = rnd.Rand16() & mask_;
dst16[j] = rnd.Rand16() & mask_;
test_input_block[j] = src16[j] - dst16[j];
#endif
}
}
ASM_REGISTER_STATE_CHECK(
RunFwdTxfm(test_input_block, test_temp_block, pitch_));
for (int j = 0; j < 64; ++j) {
if (test_temp_block[j] > 0) {
test_temp_block[j] += 2;
test_temp_block[j] /= 4;
test_temp_block[j] *= 4;
} else {
test_temp_block[j] -= 2;
test_temp_block[j] /= 4;
test_temp_block[j] *= 4;
}
}
if (bit_depth_ == VPX_BITS_8) {
ASM_REGISTER_STATE_CHECK(
RunInvTxfm(test_temp_block, dst, pitch_));
#if CONFIG_VP9_HIGHBITDEPTH
} else {
ASM_REGISTER_STATE_CHECK(
RunInvTxfm(test_temp_block, CONVERT_TO_BYTEPTR(dst16), pitch_));
#endif
}
for (int j = 0; j < 64; ++j) {
#if CONFIG_VP9_HIGHBITDEPTH
const int diff =
bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j];
#else
const int diff = dst[j] - src[j];
#endif
const int error = diff * diff;
if (max_error < error)
max_error = error;
total_error += error;
}
}
EXPECT_GE(1 << 2 * (bit_depth_ - 8), max_error)
<< "Error: 8x8 FDCT/IDCT or FHT/IHT has an individual"
<< " roundtrip error > 1";
EXPECT_GE((count_test_block << 2 * (bit_depth_ - 8))/5, total_error)
<< "Error: 8x8 FDCT/IDCT or FHT/IHT has average roundtrip "
<< "error > 1/5 per block";
}
| 174,560 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static struct mount *clone_mnt(struct mount *old, struct dentry *root,
int flag)
{
struct super_block *sb = old->mnt.mnt_sb;
struct mount *mnt;
int err;
mnt = alloc_vfsmnt(old->mnt_devname);
if (!mnt)
return ERR_PTR(-ENOMEM);
if (flag & (CL_SLAVE | CL_PRIVATE | CL_SHARED_TO_SLAVE))
mnt->mnt_group_id = 0; /* not a peer of original */
else
mnt->mnt_group_id = old->mnt_group_id;
if ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) {
err = mnt_alloc_group_id(mnt);
if (err)
goto out_free;
}
mnt->mnt.mnt_flags = old->mnt.mnt_flags & ~(MNT_WRITE_HOLD|MNT_MARKED);
/* Don't allow unprivileged users to change mount flags */
if ((flag & CL_UNPRIVILEGED) && (mnt->mnt.mnt_flags & MNT_READONLY))
mnt->mnt.mnt_flags |= MNT_LOCK_READONLY;
/* Don't allow unprivileged users to reveal what is under a mount */
if ((flag & CL_UNPRIVILEGED) && list_empty(&old->mnt_expire))
mnt->mnt.mnt_flags |= MNT_LOCKED;
atomic_inc(&sb->s_active);
mnt->mnt.mnt_sb = sb;
mnt->mnt.mnt_root = dget(root);
mnt->mnt_mountpoint = mnt->mnt.mnt_root;
mnt->mnt_parent = mnt;
lock_mount_hash();
list_add_tail(&mnt->mnt_instance, &sb->s_mounts);
unlock_mount_hash();
if ((flag & CL_SLAVE) ||
((flag & CL_SHARED_TO_SLAVE) && IS_MNT_SHARED(old))) {
list_add(&mnt->mnt_slave, &old->mnt_slave_list);
mnt->mnt_master = old;
CLEAR_MNT_SHARED(mnt);
} else if (!(flag & CL_PRIVATE)) {
if ((flag & CL_MAKE_SHARED) || IS_MNT_SHARED(old))
list_add(&mnt->mnt_share, &old->mnt_share);
if (IS_MNT_SLAVE(old))
list_add(&mnt->mnt_slave, &old->mnt_slave);
mnt->mnt_master = old->mnt_master;
}
if (flag & CL_MAKE_SHARED)
set_mnt_shared(mnt);
/* stick the duplicate mount on the same expiry list
* as the original if that was on one */
if (flag & CL_EXPIRE) {
if (!list_empty(&old->mnt_expire))
list_add(&mnt->mnt_expire, &old->mnt_expire);
}
return mnt;
out_free:
mnt_free_id(mnt);
free_vfsmnt(mnt);
return ERR_PTR(err);
}
Commit Message: mnt: Correct permission checks in do_remount
While invesgiating the issue where in "mount --bind -oremount,ro ..."
would result in later "mount --bind -oremount,rw" succeeding even if
the mount started off locked I realized that there are several
additional mount flags that should be locked and are not.
In particular MNT_NOSUID, MNT_NODEV, MNT_NOEXEC, and the atime
flags in addition to MNT_READONLY should all be locked. These
flags are all per superblock, can all be changed with MS_BIND,
and should not be changable if set by a more privileged user.
The following additions to the current logic are added in this patch.
- nosuid may not be clearable by a less privileged user.
- nodev may not be clearable by a less privielged user.
- noexec may not be clearable by a less privileged user.
- atime flags may not be changeable by a less privileged user.
The logic with atime is that always setting atime on access is a
global policy and backup software and auditing software could break if
atime bits are not updated (when they are configured to be updated),
and serious performance degradation could result (DOS attack) if atime
updates happen when they have been explicitly disabled. Therefore an
unprivileged user should not be able to mess with the atime bits set
by a more privileged user.
The additional restrictions are implemented with the addition of
MNT_LOCK_NOSUID, MNT_LOCK_NODEV, MNT_LOCK_NOEXEC, and MNT_LOCK_ATIME
mnt flags.
Taken together these changes and the fixes for MNT_LOCK_READONLY
should make it safe for an unprivileged user to create a user
namespace and to call "mount --bind -o remount,... ..." without
the danger of mount flags being changed maliciously.
Cc: [email protected]
Acked-by: Serge E. Hallyn <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-264
|
static struct mount *clone_mnt(struct mount *old, struct dentry *root,
int flag)
{
struct super_block *sb = old->mnt.mnt_sb;
struct mount *mnt;
int err;
mnt = alloc_vfsmnt(old->mnt_devname);
if (!mnt)
return ERR_PTR(-ENOMEM);
if (flag & (CL_SLAVE | CL_PRIVATE | CL_SHARED_TO_SLAVE))
mnt->mnt_group_id = 0; /* not a peer of original */
else
mnt->mnt_group_id = old->mnt_group_id;
if ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) {
err = mnt_alloc_group_id(mnt);
if (err)
goto out_free;
}
mnt->mnt.mnt_flags = old->mnt.mnt_flags & ~(MNT_WRITE_HOLD|MNT_MARKED);
/* Don't allow unprivileged users to change mount flags */
if (flag & CL_UNPRIVILEGED) {
mnt->mnt.mnt_flags |= MNT_LOCK_ATIME;
if (mnt->mnt.mnt_flags & MNT_READONLY)
mnt->mnt.mnt_flags |= MNT_LOCK_READONLY;
if (mnt->mnt.mnt_flags & MNT_NODEV)
mnt->mnt.mnt_flags |= MNT_LOCK_NODEV;
if (mnt->mnt.mnt_flags & MNT_NOSUID)
mnt->mnt.mnt_flags |= MNT_LOCK_NOSUID;
if (mnt->mnt.mnt_flags & MNT_NOEXEC)
mnt->mnt.mnt_flags |= MNT_LOCK_NOEXEC;
}
/* Don't allow unprivileged users to reveal what is under a mount */
if ((flag & CL_UNPRIVILEGED) && list_empty(&old->mnt_expire))
mnt->mnt.mnt_flags |= MNT_LOCKED;
atomic_inc(&sb->s_active);
mnt->mnt.mnt_sb = sb;
mnt->mnt.mnt_root = dget(root);
mnt->mnt_mountpoint = mnt->mnt.mnt_root;
mnt->mnt_parent = mnt;
lock_mount_hash();
list_add_tail(&mnt->mnt_instance, &sb->s_mounts);
unlock_mount_hash();
if ((flag & CL_SLAVE) ||
((flag & CL_SHARED_TO_SLAVE) && IS_MNT_SHARED(old))) {
list_add(&mnt->mnt_slave, &old->mnt_slave_list);
mnt->mnt_master = old;
CLEAR_MNT_SHARED(mnt);
} else if (!(flag & CL_PRIVATE)) {
if ((flag & CL_MAKE_SHARED) || IS_MNT_SHARED(old))
list_add(&mnt->mnt_share, &old->mnt_share);
if (IS_MNT_SLAVE(old))
list_add(&mnt->mnt_slave, &old->mnt_slave);
mnt->mnt_master = old->mnt_master;
}
if (flag & CL_MAKE_SHARED)
set_mnt_shared(mnt);
/* stick the duplicate mount on the same expiry list
* as the original if that was on one */
if (flag & CL_EXPIRE) {
if (!list_empty(&old->mnt_expire))
list_add(&mnt->mnt_expire, &old->mnt_expire);
}
return mnt;
out_free:
mnt_free_id(mnt);
free_vfsmnt(mnt);
return ERR_PTR(err);
}
| 166,280 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int sctp_getsockopt_assoc_stats(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_stats sas;
struct sctp_association *asoc = NULL;
/* User must provide at least the assoc id */
if (len < sizeof(sctp_assoc_t))
return -EINVAL;
if (copy_from_user(&sas, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, sas.sas_assoc_id);
if (!asoc)
return -EINVAL;
sas.sas_rtxchunks = asoc->stats.rtxchunks;
sas.sas_gapcnt = asoc->stats.gapcnt;
sas.sas_outofseqtsns = asoc->stats.outofseqtsns;
sas.sas_osacks = asoc->stats.osacks;
sas.sas_isacks = asoc->stats.isacks;
sas.sas_octrlchunks = asoc->stats.octrlchunks;
sas.sas_ictrlchunks = asoc->stats.ictrlchunks;
sas.sas_oodchunks = asoc->stats.oodchunks;
sas.sas_iodchunks = asoc->stats.iodchunks;
sas.sas_ouodchunks = asoc->stats.ouodchunks;
sas.sas_iuodchunks = asoc->stats.iuodchunks;
sas.sas_idupchunks = asoc->stats.idupchunks;
sas.sas_opackets = asoc->stats.opackets;
sas.sas_ipackets = asoc->stats.ipackets;
/* New high max rto observed, will return 0 if not a single
* RTO update took place. obs_rto_ipaddr will be bogus
* in such a case
*/
sas.sas_maxrto = asoc->stats.max_obs_rto;
memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr,
sizeof(struct sockaddr_storage));
/* Mark beginning of a new observation period */
asoc->stats.max_obs_rto = asoc->rto_min;
/* Allow the struct to grow and fill in as much as possible */
len = min_t(size_t, len, sizeof(sas));
if (put_user(len, optlen))
return -EFAULT;
SCTP_DEBUG_PRINTK("sctp_getsockopt_assoc_stat(%d): %d\n",
len, sas.sas_assoc_id);
if (copy_to_user(optval, &sas, len))
return -EFAULT;
return 0;
}
Commit Message: net/sctp: Validate parameter size for SCTP_GET_ASSOC_STATS
Building sctp may fail with:
In function ‘copy_from_user’,
inlined from ‘sctp_getsockopt_assoc_stats’ at
net/sctp/socket.c:5656:20:
arch/x86/include/asm/uaccess_32.h:211:26: error: call to
‘copy_from_user_overflow’ declared with attribute error: copy_from_user()
buffer size is not provably correct
if built with W=1 due to a missing parameter size validation
before the call to copy_from_user.
Signed-off-by: Guenter Roeck <[email protected]>
Acked-by: Vlad Yasevich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
|
static int sctp_getsockopt_assoc_stats(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_stats sas;
struct sctp_association *asoc = NULL;
/* User must provide at least the assoc id */
if (len < sizeof(sctp_assoc_t))
return -EINVAL;
/* Allow the struct to grow and fill in as much as possible */
len = min_t(size_t, len, sizeof(sas));
if (copy_from_user(&sas, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, sas.sas_assoc_id);
if (!asoc)
return -EINVAL;
sas.sas_rtxchunks = asoc->stats.rtxchunks;
sas.sas_gapcnt = asoc->stats.gapcnt;
sas.sas_outofseqtsns = asoc->stats.outofseqtsns;
sas.sas_osacks = asoc->stats.osacks;
sas.sas_isacks = asoc->stats.isacks;
sas.sas_octrlchunks = asoc->stats.octrlchunks;
sas.sas_ictrlchunks = asoc->stats.ictrlchunks;
sas.sas_oodchunks = asoc->stats.oodchunks;
sas.sas_iodchunks = asoc->stats.iodchunks;
sas.sas_ouodchunks = asoc->stats.ouodchunks;
sas.sas_iuodchunks = asoc->stats.iuodchunks;
sas.sas_idupchunks = asoc->stats.idupchunks;
sas.sas_opackets = asoc->stats.opackets;
sas.sas_ipackets = asoc->stats.ipackets;
/* New high max rto observed, will return 0 if not a single
* RTO update took place. obs_rto_ipaddr will be bogus
* in such a case
*/
sas.sas_maxrto = asoc->stats.max_obs_rto;
memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr,
sizeof(struct sockaddr_storage));
/* Mark beginning of a new observation period */
asoc->stats.max_obs_rto = asoc->rto_min;
if (put_user(len, optlen))
return -EFAULT;
SCTP_DEBUG_PRINTK("sctp_getsockopt_assoc_stat(%d): %d\n",
len, sas.sas_assoc_id);
if (copy_to_user(optval, &sas, len))
return -EFAULT;
return 0;
}
| 166,111 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void CCLayerTreeHostTest::doBeginTest()
{
ASSERT(isMainThread());
ASSERT(!m_running);
m_running = true;
m_client = MockLayerTreeHostClient::create(this);
RefPtr<LayerChromium> rootLayer = LayerChromium::create(0);
m_layerTreeHost = MockLayerTreeHost::create(this, m_client.get(), rootLayer, m_settings);
ASSERT(m_layerTreeHost);
m_beginning = true;
beginTest();
m_beginning = false;
if (m_endWhenBeginReturns)
onEndTest(static_cast<void*>(this));
}
Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests
https://bugs.webkit.org/show_bug.cgi?id=70161
Reviewed by David Levin.
Source/WebCore:
Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor
thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was
destroyed.
This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit
task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the
CCThreadProxy have been drained.
Covered by the now-enabled CCLayerTreeHostTest* unit tests.
* WebCore.gypi:
* platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added.
(WebCore::CCScopedMainThreadProxy::create):
(WebCore::CCScopedMainThreadProxy::postTask):
(WebCore::CCScopedMainThreadProxy::shutdown):
(WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy):
(WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown):
* platform/graphics/chromium/cc/CCThreadProxy.cpp:
(WebCore::CCThreadProxy::CCThreadProxy):
(WebCore::CCThreadProxy::~CCThreadProxy):
(WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread):
* platform/graphics/chromium/cc/CCThreadProxy.h:
Source/WebKit/chromium:
Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple
thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor
thread scheduling draws by itself.
* tests/CCLayerTreeHostTest.cpp:
(::CCLayerTreeHostTest::timeout):
(::CCLayerTreeHostTest::clearTimeout):
(::CCLayerTreeHostTest::CCLayerTreeHostTest):
(::CCLayerTreeHostTest::onEndTest):
(::CCLayerTreeHostTest::TimeoutTask::TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::clearTest):
(::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::Run):
(::CCLayerTreeHostTest::runTest):
(::CCLayerTreeHostTest::doBeginTest):
(::CCLayerTreeHostTestThreadOnly::runTest):
(::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread):
git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
void CCLayerTreeHostTest::doBeginTest()
{
ASSERT(isMainThread());
m_client = MockLayerTreeHostClient::create(this);
RefPtr<LayerChromium> rootLayer = LayerChromium::create(0);
m_layerTreeHost = MockLayerTreeHost::create(this, m_client.get(), rootLayer, m_settings);
ASSERT(m_layerTreeHost);
m_beginning = true;
beginTest();
m_beginning = false;
if (m_endWhenBeginReturns)
onEndTest(static_cast<void*>(this));
}
| 170,292 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static int needs_empty_write(sector_t block, struct inode *inode)
{
int error;
struct buffer_head bh_map = { .b_state = 0, .b_blocknr = 0 };
bh_map.b_size = 1 << inode->i_blkbits;
error = gfs2_block_map(inode, block, &bh_map, 0);
if (unlikely(error))
return error;
return !buffer_mapped(&bh_map);
}
Commit Message: GFS2: rewrite fallocate code to write blocks directly
GFS2's fallocate code currently goes through the page cache. Since it's only
writing to the end of the file or to holes in it, it doesn't need to, and it
was causing issues on low memory environments. This patch pulls in some of
Steve's block allocation work, and uses it to simply allocate the blocks for
the file, and zero them out at allocation time. It provides a slight
performance increase, and it dramatically simplifies the code.
Signed-off-by: Benjamin Marzinski <[email protected]>
Signed-off-by: Steven Whitehouse <[email protected]>
CWE ID: CWE-119
|
static int needs_empty_write(sector_t block, struct inode *inode)
| 166,214 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void SetConstantInput(int value) {
memset(input_, value, kInputBufferSize);
}
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 SetConstantInput(int value) {
memset(input_, value, kInputBufferSize);
#if CONFIG_VP9_HIGHBITDEPTH
vpx_memset16(input16_, value, kInputBufferSize);
#endif
}
void CopyOutputToRef() {
memcpy(output_ref_, output_, kOutputBufferSize);
#if CONFIG_VP9_HIGHBITDEPTH
memcpy(output16_ref_, output16_, kOutputBufferSize);
#endif
}
| 174,504 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ih264d_init_decoder(void * ps_dec_params)
{
dec_struct_t * ps_dec = (dec_struct_t *)ps_dec_params;
dec_slice_params_t *ps_cur_slice;
pocstruct_t *ps_prev_poc, *ps_cur_poc;
WORD32 size;
size = sizeof(pred_info_t) * 2 * 32;
memset(ps_dec->ps_pred, 0 , size);
size = sizeof(disp_mgr_t);
memset(ps_dec->pv_disp_buf_mgr, 0 , size);
size = sizeof(buf_mgr_t) + ithread_get_mutex_lock_size();
memset(ps_dec->pv_pic_buf_mgr, 0, size);
size = sizeof(dec_err_status_t);
memset(ps_dec->ps_dec_err_status, 0, size);
size = sizeof(sei);
memset(ps_dec->ps_sei, 0, size);
size = sizeof(dpb_commands_t);
memset(ps_dec->ps_dpb_cmds, 0, size);
size = sizeof(dec_bit_stream_t);
memset(ps_dec->ps_bitstrm, 0, size);
size = sizeof(dec_slice_params_t);
memset(ps_dec->ps_cur_slice, 0, size);
size = MAX(sizeof(dec_seq_params_t), sizeof(dec_pic_params_t));
memset(ps_dec->pv_scratch_sps_pps, 0, size);
size = sizeof(ctxt_inc_mb_info_t);
memset(ps_dec->ps_left_mb_ctxt_info, 0, size);
size = (sizeof(neighbouradd_t) << 2);
memset(ps_dec->ps_left_mvpred_addr, 0 ,size);
size = sizeof(buf_mgr_t) + ithread_get_mutex_lock_size();
memset(ps_dec->pv_mv_buf_mgr, 0, size);
/* Free any dynamic buffers that are allocated */
ih264d_free_dynamic_bufs(ps_dec);
ps_cur_slice = ps_dec->ps_cur_slice;
ps_dec->init_done = 0;
ps_dec->u4_num_cores = 1;
ps_dec->u2_pic_ht = ps_dec->u2_pic_wd = 0;
ps_dec->u1_separate_parse = DEFAULT_SEPARATE_PARSE;
ps_dec->u4_app_disable_deblk_frm = 0;
ps_dec->i4_degrade_type = 0;
ps_dec->i4_degrade_pics = 0;
ps_dec->i4_app_skip_mode = IVD_SKIP_NONE;
ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE;
memset(ps_dec->ps_pps, 0,
((sizeof(dec_pic_params_t)) * MAX_NUM_PIC_PARAMS));
memset(ps_dec->ps_sps, 0,
((sizeof(dec_seq_params_t)) * MAX_NUM_SEQ_PARAMS));
/* Initialization of function pointers ih264d_deblock_picture function*/
ps_dec->p_DeblockPicture[0] = ih264d_deblock_picture_non_mbaff;
ps_dec->p_DeblockPicture[1] = ih264d_deblock_picture_mbaff;
ps_dec->s_cab_dec_env.pv_codec_handle = ps_dec;
ps_dec->u4_num_fld_in_frm = 0;
ps_dec->ps_dpb_mgr->pv_codec_handle = ps_dec;
/* Initialize the sei validity u4_flag with zero indiacting sei is not valid*/
ps_dec->ps_sei->u1_is_valid = 0;
/* decParams Initializations */
ps_dec->ps_cur_pps = NULL;
ps_dec->ps_cur_sps = NULL;
ps_dec->u1_init_dec_flag = 0;
ps_dec->u1_first_slice_in_stream = 1;
ps_dec->u1_first_pb_nal_in_pic = 1;
ps_dec->u1_last_pic_not_decoded = 0;
ps_dec->u4_app_disp_width = 0;
ps_dec->i4_header_decoded = 0;
ps_dec->u4_total_frames_decoded = 0;
ps_dec->i4_error_code = 0;
ps_dec->i4_content_type = -1;
ps_dec->ps_cur_slice->u1_mbaff_frame_flag = 0;
ps_dec->ps_dec_err_status->u1_err_flag = ACCEPT_ALL_PICS; //REJECT_PB_PICS;
ps_dec->ps_dec_err_status->u1_cur_pic_type = PIC_TYPE_UNKNOWN;
ps_dec->ps_dec_err_status->u4_frm_sei_sync = SYNC_FRM_DEFAULT;
ps_dec->ps_dec_err_status->u4_cur_frm = INIT_FRAME;
ps_dec->ps_dec_err_status->u1_pic_aud_i = PIC_TYPE_UNKNOWN;
ps_dec->u1_pr_sl_type = 0xFF;
ps_dec->u2_mbx = 0xffff;
ps_dec->u2_mby = 0;
ps_dec->u2_total_mbs_coded = 0;
/* POC initializations */
ps_prev_poc = &ps_dec->s_prev_pic_poc;
ps_cur_poc = &ps_dec->s_cur_pic_poc;
ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb = 0;
ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb = 0;
ps_prev_poc->i4_delta_pic_order_cnt_bottom =
ps_cur_poc->i4_delta_pic_order_cnt_bottom = 0;
ps_prev_poc->i4_delta_pic_order_cnt[0] =
ps_cur_poc->i4_delta_pic_order_cnt[0] = 0;
ps_prev_poc->i4_delta_pic_order_cnt[1] =
ps_cur_poc->i4_delta_pic_order_cnt[1] = 0;
ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0;
ps_prev_poc->i4_top_field_order_count = ps_cur_poc->i4_top_field_order_count =
0;
ps_prev_poc->i4_bottom_field_order_count =
ps_cur_poc->i4_bottom_field_order_count = 0;
ps_prev_poc->u1_bot_field = ps_cur_poc->u1_bot_field = 0;
ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0;
ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst = 0;
ps_cur_slice->u1_mmco_equalto5 = 0;
ps_cur_slice->u2_frame_num = 0;
ps_dec->i4_max_poc = 0;
ps_dec->i4_prev_max_display_seq = 0;
ps_dec->u1_recon_mb_grp = 4;
/* Field PIC initializations */
ps_dec->u1_second_field = 0;
ps_dec->s_prev_seq_params.u1_eoseq_pending = 0;
/* Set the cropping parameters as zero */
ps_dec->u2_crop_offset_y = 0;
ps_dec->u2_crop_offset_uv = 0;
/* The Initial Frame Rate Info is not Present */
ps_dec->i4_vui_frame_rate = -1;
ps_dec->i4_pic_type = -1;
ps_dec->i4_frametype = -1;
ps_dec->i4_content_type = -1;
ps_dec->u1_res_changed = 0;
ps_dec->u1_frame_decoded_flag = 0;
/* Set the default frame seek mask mode */
ps_dec->u4_skip_frm_mask = SKIP_NONE;
/********************************************************/
/* Initialize CAVLC residual decoding function pointers */
/********************************************************/
ps_dec->pf_cavlc_4x4res_block[0] = ih264d_cavlc_4x4res_block_totalcoeff_1;
ps_dec->pf_cavlc_4x4res_block[1] =
ih264d_cavlc_4x4res_block_totalcoeff_2to10;
ps_dec->pf_cavlc_4x4res_block[2] =
ih264d_cavlc_4x4res_block_totalcoeff_11to16;
ps_dec->pf_cavlc_parse4x4coeff[0] = ih264d_cavlc_parse4x4coeff_n0to7;
ps_dec->pf_cavlc_parse4x4coeff[1] = ih264d_cavlc_parse4x4coeff_n8;
ps_dec->pf_cavlc_parse_8x8block[0] =
ih264d_cavlc_parse_8x8block_none_available;
ps_dec->pf_cavlc_parse_8x8block[1] =
ih264d_cavlc_parse_8x8block_left_available;
ps_dec->pf_cavlc_parse_8x8block[2] =
ih264d_cavlc_parse_8x8block_top_available;
ps_dec->pf_cavlc_parse_8x8block[3] =
ih264d_cavlc_parse_8x8block_both_available;
/***************************************************************************/
/* Initialize Bs calculation function pointers for P and B, 16x16/non16x16 */
/***************************************************************************/
ps_dec->pf_fill_bs1[0][0] = ih264d_fill_bs1_16x16mb_pslice;
ps_dec->pf_fill_bs1[0][1] = ih264d_fill_bs1_non16x16mb_pslice;
ps_dec->pf_fill_bs1[1][0] = ih264d_fill_bs1_16x16mb_bslice;
ps_dec->pf_fill_bs1[1][1] = ih264d_fill_bs1_non16x16mb_bslice;
ps_dec->pf_fill_bs_xtra_left_edge[0] =
ih264d_fill_bs_xtra_left_edge_cur_frm;
ps_dec->pf_fill_bs_xtra_left_edge[1] =
ih264d_fill_bs_xtra_left_edge_cur_fld;
/* Initialize Reference Pic Buffers */
ih264d_init_ref_bufs(ps_dec->ps_dpb_mgr);
ps_dec->u2_prv_frame_num = 0;
ps_dec->u1_top_bottom_decoded = 0;
ps_dec->u1_dangling_field = 0;
ps_dec->s_cab_dec_env.cabac_table = gau4_ih264d_cabac_table;
ps_dec->pu1_left_mv_ctxt_inc = ps_dec->u1_left_mv_ctxt_inc_arr[0];
ps_dec->pi1_left_ref_idx_ctxt_inc =
&ps_dec->i1_left_ref_idx_ctx_inc_arr[0][0];
ps_dec->pu1_left_yuv_dc_csbp = &ps_dec->u1_yuv_dc_csbp_topmb;
/* ! */
/* Initializing flush frame u4_flag */
ps_dec->u1_flushfrm = 0;
{
ps_dec->s_cab_dec_env.pv_codec_handle = (void*)ps_dec;
ps_dec->ps_bitstrm->pv_codec_handle = (void*)ps_dec;
ps_dec->ps_cur_slice->pv_codec_handle = (void*)ps_dec;
ps_dec->ps_dpb_mgr->pv_codec_handle = (void*)ps_dec;
}
memset(ps_dec->disp_bufs, 0, (MAX_DISP_BUFS_NEW) * sizeof(disp_buf_t));
memset(ps_dec->u4_disp_buf_mapping, 0,
(MAX_DISP_BUFS_NEW) * sizeof(UWORD32));
memset(ps_dec->u4_disp_buf_to_be_freed, 0,
(MAX_DISP_BUFS_NEW) * sizeof(UWORD32));
ih264d_init_arch(ps_dec);
ih264d_init_function_ptr(ps_dec);
ps_dec->e_frm_out_mode = IVD_DISPLAY_FRAME_OUT;
ps_dec->init_done = 1;
}
Commit Message: Fix slice params for interlaced video
Bug: 28165661
Change-Id: I912a86bd78ebf0617fd2bc6eb2b5a61afc17bf53
CWE ID: CWE-20
|
void ih264d_init_decoder(void * ps_dec_params)
{
dec_struct_t * ps_dec = (dec_struct_t *)ps_dec_params;
dec_slice_params_t *ps_cur_slice;
pocstruct_t *ps_prev_poc, *ps_cur_poc;
WORD32 size;
size = sizeof(pred_info_t) * 2 * 32;
memset(ps_dec->ps_pred, 0 , size);
size = sizeof(disp_mgr_t);
memset(ps_dec->pv_disp_buf_mgr, 0 , size);
size = sizeof(buf_mgr_t) + ithread_get_mutex_lock_size();
memset(ps_dec->pv_pic_buf_mgr, 0, size);
size = sizeof(dec_err_status_t);
memset(ps_dec->ps_dec_err_status, 0, size);
size = sizeof(sei);
memset(ps_dec->ps_sei, 0, size);
size = sizeof(dpb_commands_t);
memset(ps_dec->ps_dpb_cmds, 0, size);
size = sizeof(dec_bit_stream_t);
memset(ps_dec->ps_bitstrm, 0, size);
size = sizeof(dec_slice_params_t);
memset(ps_dec->ps_cur_slice, 0, size);
size = MAX(sizeof(dec_seq_params_t), sizeof(dec_pic_params_t));
memset(ps_dec->pv_scratch_sps_pps, 0, size);
size = sizeof(ctxt_inc_mb_info_t);
memset(ps_dec->ps_left_mb_ctxt_info, 0, size);
size = (sizeof(neighbouradd_t) << 2);
memset(ps_dec->ps_left_mvpred_addr, 0 ,size);
size = sizeof(buf_mgr_t) + ithread_get_mutex_lock_size();
memset(ps_dec->pv_mv_buf_mgr, 0, size);
/* Free any dynamic buffers that are allocated */
ih264d_free_dynamic_bufs(ps_dec);
ps_cur_slice = ps_dec->ps_cur_slice;
ps_dec->init_done = 0;
ps_dec->u4_num_cores = 1;
ps_dec->u2_pic_ht = ps_dec->u2_pic_wd = 0;
ps_dec->u1_separate_parse = DEFAULT_SEPARATE_PARSE;
ps_dec->u4_app_disable_deblk_frm = 0;
ps_dec->i4_degrade_type = 0;
ps_dec->i4_degrade_pics = 0;
ps_dec->i4_app_skip_mode = IVD_SKIP_NONE;
ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE;
memset(ps_dec->ps_pps, 0,
((sizeof(dec_pic_params_t)) * MAX_NUM_PIC_PARAMS));
memset(ps_dec->ps_sps, 0,
((sizeof(dec_seq_params_t)) * MAX_NUM_SEQ_PARAMS));
/* Initialization of function pointers ih264d_deblock_picture function*/
ps_dec->p_DeblockPicture[0] = ih264d_deblock_picture_non_mbaff;
ps_dec->p_DeblockPicture[1] = ih264d_deblock_picture_mbaff;
ps_dec->s_cab_dec_env.pv_codec_handle = ps_dec;
ps_dec->u4_num_fld_in_frm = 0;
ps_dec->ps_dpb_mgr->pv_codec_handle = ps_dec;
/* Initialize the sei validity u4_flag with zero indiacting sei is not valid*/
ps_dec->ps_sei->u1_is_valid = 0;
/* decParams Initializations */
ps_dec->ps_cur_pps = NULL;
ps_dec->ps_cur_sps = NULL;
ps_dec->u1_init_dec_flag = 0;
ps_dec->u1_first_slice_in_stream = 1;
ps_dec->u1_first_pb_nal_in_pic = 1;
ps_dec->u1_last_pic_not_decoded = 0;
ps_dec->u4_app_disp_width = 0;
ps_dec->i4_header_decoded = 0;
ps_dec->u4_total_frames_decoded = 0;
ps_dec->i4_error_code = 0;
ps_dec->i4_content_type = -1;
ps_dec->ps_cur_slice->u1_mbaff_frame_flag = 0;
ps_dec->ps_dec_err_status->u1_err_flag = ACCEPT_ALL_PICS; //REJECT_PB_PICS;
ps_dec->ps_dec_err_status->u1_cur_pic_type = PIC_TYPE_UNKNOWN;
ps_dec->ps_dec_err_status->u4_frm_sei_sync = SYNC_FRM_DEFAULT;
ps_dec->ps_dec_err_status->u4_cur_frm = INIT_FRAME;
ps_dec->ps_dec_err_status->u1_pic_aud_i = PIC_TYPE_UNKNOWN;
ps_dec->u1_pr_sl_type = 0xFF;
ps_dec->u2_mbx = 0xffff;
ps_dec->u2_mby = 0;
ps_dec->u2_total_mbs_coded = 0;
/* POC initializations */
ps_prev_poc = &ps_dec->s_prev_pic_poc;
ps_cur_poc = &ps_dec->s_cur_pic_poc;
ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb = 0;
ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb = 0;
ps_prev_poc->i4_delta_pic_order_cnt_bottom =
ps_cur_poc->i4_delta_pic_order_cnt_bottom = 0;
ps_prev_poc->i4_delta_pic_order_cnt[0] =
ps_cur_poc->i4_delta_pic_order_cnt[0] = 0;
ps_prev_poc->i4_delta_pic_order_cnt[1] =
ps_cur_poc->i4_delta_pic_order_cnt[1] = 0;
ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0;
ps_prev_poc->i4_top_field_order_count = ps_cur_poc->i4_top_field_order_count =
0;
ps_prev_poc->i4_bottom_field_order_count =
ps_cur_poc->i4_bottom_field_order_count = 0;
ps_prev_poc->u1_bot_field = ps_cur_poc->u1_bot_field = 0;
ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0;
ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst = 0;
ps_cur_slice->u1_mmco_equalto5 = 0;
ps_cur_slice->u2_frame_num = 0;
ps_dec->i4_max_poc = 0;
ps_dec->i4_prev_max_display_seq = 0;
ps_dec->u1_recon_mb_grp = 4;
/* Field PIC initializations */
ps_dec->u1_second_field = 0;
ps_dec->s_prev_seq_params.u1_eoseq_pending = 0;
/* Set the cropping parameters as zero */
ps_dec->u2_crop_offset_y = 0;
ps_dec->u2_crop_offset_uv = 0;
/* The Initial Frame Rate Info is not Present */
ps_dec->i4_vui_frame_rate = -1;
ps_dec->i4_pic_type = -1;
ps_dec->i4_frametype = -1;
ps_dec->i4_content_type = -1;
ps_dec->u1_res_changed = 0;
ps_dec->u1_frame_decoded_flag = 0;
/* Set the default frame seek mask mode */
ps_dec->u4_skip_frm_mask = SKIP_NONE;
/********************************************************/
/* Initialize CAVLC residual decoding function pointers */
/********************************************************/
ps_dec->pf_cavlc_4x4res_block[0] = ih264d_cavlc_4x4res_block_totalcoeff_1;
ps_dec->pf_cavlc_4x4res_block[1] =
ih264d_cavlc_4x4res_block_totalcoeff_2to10;
ps_dec->pf_cavlc_4x4res_block[2] =
ih264d_cavlc_4x4res_block_totalcoeff_11to16;
ps_dec->pf_cavlc_parse4x4coeff[0] = ih264d_cavlc_parse4x4coeff_n0to7;
ps_dec->pf_cavlc_parse4x4coeff[1] = ih264d_cavlc_parse4x4coeff_n8;
ps_dec->pf_cavlc_parse_8x8block[0] =
ih264d_cavlc_parse_8x8block_none_available;
ps_dec->pf_cavlc_parse_8x8block[1] =
ih264d_cavlc_parse_8x8block_left_available;
ps_dec->pf_cavlc_parse_8x8block[2] =
ih264d_cavlc_parse_8x8block_top_available;
ps_dec->pf_cavlc_parse_8x8block[3] =
ih264d_cavlc_parse_8x8block_both_available;
/***************************************************************************/
/* Initialize Bs calculation function pointers for P and B, 16x16/non16x16 */
/***************************************************************************/
ps_dec->pf_fill_bs1[0][0] = ih264d_fill_bs1_16x16mb_pslice;
ps_dec->pf_fill_bs1[0][1] = ih264d_fill_bs1_non16x16mb_pslice;
ps_dec->pf_fill_bs1[1][0] = ih264d_fill_bs1_16x16mb_bslice;
ps_dec->pf_fill_bs1[1][1] = ih264d_fill_bs1_non16x16mb_bslice;
ps_dec->pf_fill_bs_xtra_left_edge[0] =
ih264d_fill_bs_xtra_left_edge_cur_frm;
ps_dec->pf_fill_bs_xtra_left_edge[1] =
ih264d_fill_bs_xtra_left_edge_cur_fld;
/* Initialize Reference Pic Buffers */
ih264d_init_ref_bufs(ps_dec->ps_dpb_mgr);
ps_dec->u2_prv_frame_num = 0;
ps_dec->u1_top_bottom_decoded = 0;
ps_dec->u1_dangling_field = 0;
ps_dec->s_cab_dec_env.cabac_table = gau4_ih264d_cabac_table;
ps_dec->pu1_left_mv_ctxt_inc = ps_dec->u1_left_mv_ctxt_inc_arr[0];
ps_dec->pi1_left_ref_idx_ctxt_inc =
&ps_dec->i1_left_ref_idx_ctx_inc_arr[0][0];
ps_dec->pu1_left_yuv_dc_csbp = &ps_dec->u1_yuv_dc_csbp_topmb;
/* ! */
/* Initializing flush frame u4_flag */
ps_dec->u1_flushfrm = 0;
{
ps_dec->s_cab_dec_env.pv_codec_handle = (void*)ps_dec;
ps_dec->ps_bitstrm->pv_codec_handle = (void*)ps_dec;
ps_dec->ps_cur_slice->pv_codec_handle = (void*)ps_dec;
ps_dec->ps_dpb_mgr->pv_codec_handle = (void*)ps_dec;
}
memset(ps_dec->disp_bufs, 0, (MAX_DISP_BUFS_NEW) * sizeof(disp_buf_t));
memset(ps_dec->u4_disp_buf_mapping, 0,
(MAX_DISP_BUFS_NEW) * sizeof(UWORD32));
memset(ps_dec->u4_disp_buf_to_be_freed, 0,
(MAX_DISP_BUFS_NEW) * sizeof(UWORD32));
memset(ps_dec->ps_cur_slice, 0, sizeof(dec_slice_params_t));
ih264d_init_arch(ps_dec);
ih264d_init_function_ptr(ps_dec);
ps_dec->e_frm_out_mode = IVD_DISPLAY_FRAME_OUT;
ps_dec->init_done = 1;
}
| 173,760 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void ShadowRoot::setInnerHTML(const String& markup, ExceptionCode& ec)
{
RefPtr<DocumentFragment> fragment = createFragmentFromSource(markup, host(), ec);
if (fragment)
replaceChildrenWithFragment(this, fragment.release(), ec);
}
Commit Message: There are too many poorly named functions to create a fragment from markup
https://bugs.webkit.org/show_bug.cgi?id=87339
Reviewed by Eric Seidel.
Source/WebCore:
Moved all functions that create a fragment from markup to markup.h/cpp.
There should be no behavioral change.
* dom/Range.cpp:
(WebCore::Range::createContextualFragment):
* dom/Range.h: Removed createDocumentFragmentForElement.
* dom/ShadowRoot.cpp:
(WebCore::ShadowRoot::setInnerHTML):
* editing/markup.cpp:
(WebCore::createFragmentFromMarkup):
(WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource.
(WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor.
(WebCore::removeElementPreservingChildren): Moved from Range.
(WebCore::createContextualFragment): Ditto.
* editing/markup.h:
* html/HTMLElement.cpp:
(WebCore::HTMLElement::setInnerHTML):
(WebCore::HTMLElement::setOuterHTML):
(WebCore::HTMLElement::insertAdjacentHTML):
* inspector/DOMPatchSupport.cpp:
(WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using
one of the functions listed in markup.h
* xml/XSLTProcessor.cpp:
(WebCore::XSLTProcessor::transformToFragment):
Source/WebKit/qt:
Replace calls to Range::createDocumentFragmentForElement by calls to
createContextualDocumentFragment.
* Api/qwebelement.cpp:
(QWebElement::appendInside):
(QWebElement::prependInside):
(QWebElement::prependOutside):
(QWebElement::appendOutside):
(QWebElement::encloseContentsWith):
(QWebElement::encloseWith):
git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264
|
void ShadowRoot::setInnerHTML(const String& markup, ExceptionCode& ec)
{
if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, host(), ec))
replaceChildrenWithFragment(this, fragment.release(), ec);
}
| 170,437 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void sas_discover_domain(struct work_struct *work)
{
struct domain_device *dev;
int error = 0;
struct sas_discovery_event *ev = to_sas_discovery_event(work);
struct asd_sas_port *port = ev->port;
clear_bit(DISCE_DISCOVER_DOMAIN, &port->disc.pending);
if (port->port_dev)
return;
error = sas_get_port_device(port);
if (error)
return;
dev = port->port_dev;
SAS_DPRINTK("DOING DISCOVERY on port %d, pid:%d\n", port->id,
task_pid_nr(current));
switch (dev->dev_type) {
case SAS_END_DEVICE:
error = sas_discover_end_dev(dev);
break;
case SAS_EDGE_EXPANDER_DEVICE:
case SAS_FANOUT_EXPANDER_DEVICE:
error = sas_discover_root_expander(dev);
break;
case SAS_SATA_DEV:
case SAS_SATA_PM:
#ifdef CONFIG_SCSI_SAS_ATA
error = sas_discover_sata(dev);
break;
#else
SAS_DPRINTK("ATA device seen but CONFIG_SCSI_SAS_ATA=N so cannot attach\n");
/* Fall through */
#endif
default:
error = -ENXIO;
SAS_DPRINTK("unhandled device %d\n", dev->dev_type);
break;
}
if (error) {
sas_rphy_free(dev->rphy);
list_del_init(&dev->disco_list_node);
spin_lock_irq(&port->dev_list_lock);
list_del_init(&dev->dev_list_node);
spin_unlock_irq(&port->dev_list_lock);
sas_put_device(dev);
port->port_dev = NULL;
}
SAS_DPRINTK("DONE DISCOVERY on port %d, pid:%d, result:%d\n", port->id,
task_pid_nr(current), error);
}
Commit Message: scsi: libsas: direct call probe and destruct
In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery
competing with ata error handling") introduced disco mutex to prevent
rediscovery competing with ata error handling and put the whole
revalidation in the mutex. But the rphy add/remove needs to wait for the
error handling which also grabs the disco mutex. This may leads to dead
lock.So the probe and destruct event were introduce to do the rphy
add/remove asynchronously and out of the lock.
The asynchronously processed workers makes the whole discovery process
not atomic, the other events may interrupt the process. For example,
if a loss of signal event inserted before the probe event, the
sas_deform_port() is called and the port will be deleted.
And sas_port_delete() may run before the destruct event, but the
port-x:x is the top parent of end device or expander. This leads to
a kernel WARNING such as:
[ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22'
[ 82.042983] ------------[ cut here ]------------
[ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237
sysfs_remove_group+0x94/0xa0
[ 82.043059] Call trace:
[ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0
[ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70
[ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308
[ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60
[ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80
[ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0
[ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50
[ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0
[ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0
[ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490
[ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128
[ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50
Make probe and destruct a direct call in the disco and revalidate function,
but put them outside the lock. The whole discovery or revalidate won't
be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT
event are deleted as a result of the direct call.
Introduce a new list to destruct the sas_port and put the port delete after
the destruct. This makes sure the right order of destroying the sysfs
kobject and fix the warning above.
In sas_ex_revalidate_domain() have a loop to find all broadcasted
device, and sometimes we have a chance to find the same expander twice.
Because the sas_port will be deleted at the end of the whole revalidate
process, sas_port with the same name cannot be added before this.
Otherwise the sysfs will complain of creating duplicate filename. Since
the LLDD will send broadcast for every device change, we can only
process one expander's revalidation.
[mkp: kbuild test robot warning]
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: Johannes Thumshirn <[email protected]>
CC: Ewan Milne <[email protected]>
CC: Christoph Hellwig <[email protected]>
CC: Tomas Henzl <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Hannes Reinecke <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID:
|
static void sas_discover_domain(struct work_struct *work)
{
struct domain_device *dev;
int error = 0;
struct sas_discovery_event *ev = to_sas_discovery_event(work);
struct asd_sas_port *port = ev->port;
clear_bit(DISCE_DISCOVER_DOMAIN, &port->disc.pending);
if (port->port_dev)
return;
error = sas_get_port_device(port);
if (error)
return;
dev = port->port_dev;
SAS_DPRINTK("DOING DISCOVERY on port %d, pid:%d\n", port->id,
task_pid_nr(current));
switch (dev->dev_type) {
case SAS_END_DEVICE:
error = sas_discover_end_dev(dev);
break;
case SAS_EDGE_EXPANDER_DEVICE:
case SAS_FANOUT_EXPANDER_DEVICE:
error = sas_discover_root_expander(dev);
break;
case SAS_SATA_DEV:
case SAS_SATA_PM:
#ifdef CONFIG_SCSI_SAS_ATA
error = sas_discover_sata(dev);
break;
#else
SAS_DPRINTK("ATA device seen but CONFIG_SCSI_SAS_ATA=N so cannot attach\n");
/* Fall through */
#endif
default:
error = -ENXIO;
SAS_DPRINTK("unhandled device %d\n", dev->dev_type);
break;
}
if (error) {
sas_rphy_free(dev->rphy);
list_del_init(&dev->disco_list_node);
spin_lock_irq(&port->dev_list_lock);
list_del_init(&dev->dev_list_node);
spin_unlock_irq(&port->dev_list_lock);
sas_put_device(dev);
port->port_dev = NULL;
}
sas_probe_devices(port);
SAS_DPRINTK("DONE DISCOVERY on port %d, pid:%d, result:%d\n", port->id,
task_pid_nr(current), error);
}
| 169,385 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: unset_and_free_gvalue (gpointer val)
{
g_value_unset (val);
g_free (val);
}
Commit Message:
CWE ID: CWE-264
|
unset_and_free_gvalue (gpointer val)
| 165,127 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: NetworkChangeNotifierMac::NetworkChangeNotifierMac()
: NetworkChangeNotifier(NetworkChangeCalculatorParamsMac()),
connection_type_(CONNECTION_UNKNOWN),
connection_type_initialized_(false),
initial_connection_type_cv_(&connection_type_lock_),
forwarder_(this),
dns_config_service_thread_(base::MakeUnique<DnsConfigServiceThread>()) {
config_watcher_ = base::MakeUnique<NetworkConfigWatcherMac>(&forwarder_);
dns_config_service_thread_->StartWithOptions(
base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
}
Commit Message: Replace base::MakeUnique with std::make_unique in net/.
base/memory/ptr_util.h includes will be cleaned up later.
Bug: 755727
Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434
Reviewed-on: https://chromium-review.googlesource.com/627300
Commit-Queue: Jeremy Roman <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Bence Béky <[email protected]>
Cr-Commit-Position: refs/heads/master@{#498123}
CWE ID: CWE-311
|
NetworkChangeNotifierMac::NetworkChangeNotifierMac()
: NetworkChangeNotifier(NetworkChangeCalculatorParamsMac()),
connection_type_(CONNECTION_UNKNOWN),
connection_type_initialized_(false),
initial_connection_type_cv_(&connection_type_lock_),
forwarder_(this),
dns_config_service_thread_(std::make_unique<DnsConfigServiceThread>()) {
config_watcher_ = std::make_unique<NetworkConfigWatcherMac>(&forwarder_);
dns_config_service_thread_->StartWithOptions(
base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
}
| 173,264 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: void *jas_malloc(size_t size)
{
void *result;
JAS_DBGLOG(101, ("jas_malloc called with %zu\n", size));
result = malloc(size);
JAS_DBGLOG(100, ("jas_malloc(%zu) -> %p\n", size, result));
return result;
}
Commit Message: Fixed an integer overflow problem.
CWE ID: CWE-190
|
void *jas_malloc(size_t size)
{
void *result;
JAS_DBGLOG(101, ("jas_malloc(%zu)\n", size));
result = malloc(size);
JAS_DBGLOG(100, ("jas_malloc(%zu) -> %p\n", size, result));
return result;
}
| 168,474 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static av_cold int xpm_decode_close(AVCodecContext *avctx)
{
XPMDecContext *x = avctx->priv_data;
av_freep(&x->pixels);
return 0;
}
Commit Message: avcodec/xpmdec: Fix multiple pointer/memory issues
Most of these were found through code review in response to
fixing 1466/clusterfuzz-testcase-minimized-5961584419536896
There is thus no testcase for most of this.
The initial issue was Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119
|
static av_cold int xpm_decode_close(AVCodecContext *avctx)
{
XPMDecContext *x = avctx->priv_data;
av_freep(&x->pixels);
av_freep(&x->buf);
x->buf_size = 0;
return 0;
}
| 168,077 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 2)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
int nonCallback(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
if (exec->argumentCount() <= 1 || !exec->argument(1).isFunction()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return JSValue::encode(jsUndefined());
}
RefPtr<TestCallback> callback = JSTestCallback::create(asObject(exec->argument(1)), castedThis->globalObject());
impl->methodWithNonCallbackArgAndCallbackArg(nonCallback, callback);
return JSValue::encode(jsUndefined());
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
|
EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 2)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
int nonCallback(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
if (exec->argumentCount() <= 1 || !exec->argument(1).isFunction()) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return JSValue::encode(jsUndefined());
}
RefPtr<TestCallback> callback = JSTestCallback::create(asObject(exec->argument(1)), castedThis->globalObject());
impl->methodWithNonCallbackArgAndCallbackArg(nonCallback, callback);
return JSValue::encode(jsUndefined());
}
| 170,593 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: check_symlinks(struct archive_write_disk *a)
{
#if !defined(HAVE_LSTAT)
/* Platform doesn't have lstat, so we can't look for symlinks. */
(void)a; /* UNUSED */
return (ARCHIVE_OK);
#else
char *pn;
char c;
int r;
struct stat st;
/*
* Guard against symlink tricks. Reject any archive entry whose
* destination would be altered by a symlink.
*/
/* Whatever we checked last time doesn't need to be re-checked. */
pn = a->name;
if (archive_strlen(&(a->path_safe)) > 0) {
char *p = a->path_safe.s;
while ((*pn != '\0') && (*p == *pn))
++p, ++pn;
}
/* Skip the root directory if the path is absolute. */
if(pn == a->name && pn[0] == '/')
++pn;
c = pn[0];
/* Keep going until we've checked the entire name. */
while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) {
/* Skip the next path element. */
while (*pn != '\0' && *pn != '/')
++pn;
c = pn[0];
pn[0] = '\0';
/* Check that we haven't hit a symlink. */
r = lstat(a->name, &st);
if (r != 0) {
/* We've hit a dir that doesn't exist; stop now. */
if (errno == ENOENT) {
break;
} else {
/* Note: This effectively disables deep directory
* support when security checks are enabled.
* Otherwise, very long pathnames that trigger
* an error here could evade the sandbox.
* TODO: We could do better, but it would probably
* require merging the symlink checks with the
* deep-directory editing. */
return (ARCHIVE_FAILED);
}
} else if (S_ISLNK(st.st_mode)) {
if (c == '\0') {
/*
* Last element is symlink; remove it
* so we can overwrite it with the
* item being extracted.
*/
if (unlink(a->name)) {
archive_set_error(&a->archive, errno,
"Could not remove symlink %s",
a->name);
pn[0] = c;
return (ARCHIVE_FAILED);
}
a->pst = NULL;
/*
* Even if we did remove it, a warning
* is in order. The warning is silly,
* though, if we're just replacing one
* symlink with another symlink.
*/
if (!S_ISLNK(a->mode)) {
archive_set_error(&a->archive, 0,
"Removing symlink %s",
a->name);
}
/* Symlink gone. No more problem! */
pn[0] = c;
return (0);
} else if (a->flags & ARCHIVE_EXTRACT_UNLINK) {
/* User asked us to remove problems. */
if (unlink(a->name) != 0) {
archive_set_error(&a->archive, 0,
"Cannot remove intervening symlink %s",
a->name);
pn[0] = c;
return (ARCHIVE_FAILED);
}
a->pst = NULL;
} else {
archive_set_error(&a->archive, 0,
"Cannot extract through symlink %s",
a->name);
pn[0] = c;
return (ARCHIVE_FAILED);
}
}
pn[0] = c;
if (pn[0] != '\0')
pn++; /* Advance to the next segment. */
}
pn[0] = c;
/* We've checked and/or cleaned the whole path, so remember it. */
archive_strcpy(&a->path_safe, a->name);
return (ARCHIVE_OK);
#endif
}
Commit Message: Fixes for Issue #745 and Issue #746 from Doran Moppert.
CWE ID: CWE-20
|
check_symlinks(struct archive_write_disk *a)
check_symlinks_fsobj(char *path, int *error_number, struct archive_string *error_string, int flags)
{
#if !defined(HAVE_LSTAT)
/* Platform doesn't have lstat, so we can't look for symlinks. */
(void)a; /* UNUSED */
(void)path; /* UNUSED */
(void)error_number; /* UNUSED */
(void)error_string; /* UNUSED */
(void)flags; /* UNUSED */
return (ARCHIVE_OK);
#else
int res = ARCHIVE_OK;
char *tail;
char *head;
int last;
char c;
int r;
struct stat st;
int restore_pwd;
/* Nothing to do here if name is empty */
if(path[0] == '\0')
return (ARCHIVE_OK);
/*
* Guard against symlink tricks. Reject any archive entry whose
* destination would be altered by a symlink.
*
* Walk the filename in chunks separated by '/'. For each segment:
* - if it doesn't exist, continue
* - if it's symlink, abort or remove it
* - if it's a directory and it's not the last chunk, cd into it
* As we go:
* head points to the current (relative) path
* tail points to the temporary \0 terminating the segment we're currently examining
* c holds what used to be in *tail
* last is 1 if this is the last tail
*/
restore_pwd = open(".", O_RDONLY | O_BINARY | O_CLOEXEC);
__archive_ensure_cloexec_flag(restore_pwd);
if (restore_pwd < 0)
return (ARCHIVE_FATAL);
head = path;
tail = path;
last = 0;
/* TODO: reintroduce a safe cache here? */
/* Skip the root directory if the path is absolute. */
if(tail == path && tail[0] == '/')
++tail;
/* Keep going until we've checked the entire name.
* head, tail, path all alias the same string, which is
* temporarily zeroed at tail, so be careful restoring the
* stashed (c=tail[0]) for error messages.
* Exiting the loop with break is okay; continue is not.
*/
while (!last) {
/* Skip the separator we just consumed, plus any adjacent ones */
while (*tail == '/')
++tail;
/* Skip the next path element. */
while (*tail != '\0' && *tail != '/')
++tail;
/* is this the last path component? */
last = (tail[0] == '\0') || (tail[0] == '/' && tail[1] == '\0');
/* temporarily truncate the string here */
c = tail[0];
tail[0] = '\0';
/* Check that we haven't hit a symlink. */
r = lstat(head, &st);
if (r != 0) {
tail[0] = c;
/* We've hit a dir that doesn't exist; stop now. */
if (errno == ENOENT) {
break;
} else {
/* Treat any other error as fatal - best to be paranoid here
* Note: This effectively disables deep directory
* support when security checks are enabled.
* Otherwise, very long pathnames that trigger
* an error here could evade the sandbox.
* TODO: We could do better, but it would probably
* require merging the symlink checks with the
* deep-directory editing. */
if (error_number) *error_number = errno;
if (error_string)
archive_string_sprintf(error_string,
"Could not stat %s",
path);
res = ARCHIVE_FAILED;
break;
}
} else if (S_ISDIR(st.st_mode)) {
if (!last) {
if (chdir(head) != 0) {
tail[0] = c;
if (error_number) *error_number = errno;
if (error_string)
archive_string_sprintf(error_string,
"Could not chdir %s",
path);
res = (ARCHIVE_FATAL);
break;
}
/* Our view is now from inside this dir: */
head = tail + 1;
}
} else if (S_ISLNK(st.st_mode)) {
if (last) {
/*
* Last element is symlink; remove it
* so we can overwrite it with the
* item being extracted.
*/
if (unlink(head)) {
tail[0] = c;
if (error_number) *error_number = errno;
if (error_string)
archive_string_sprintf(error_string,
"Could not remove symlink %s",
path);
res = ARCHIVE_FAILED;
break;
}
/*
* Even if we did remove it, a warning
* is in order. The warning is silly,
* though, if we're just replacing one
* symlink with another symlink.
*/
tail[0] = c;
/* FIXME: not sure how important this is to restore
if (!S_ISLNK(path)) {
if (error_number) *error_number = 0;
if (error_string)
archive_string_sprintf(error_string,
"Removing symlink %s",
path);
}
*/
/* Symlink gone. No more problem! */
res = ARCHIVE_OK;
break;
} else if (flags & ARCHIVE_EXTRACT_UNLINK) {
/* User asked us to remove problems. */
if (unlink(head) != 0) {
tail[0] = c;
if (error_number) *error_number = 0;
if (error_string)
archive_string_sprintf(error_string,
"Cannot remove intervening symlink %s",
path);
res = ARCHIVE_FAILED;
break;
}
tail[0] = c;
} else {
tail[0] = c;
if (error_number) *error_number = 0;
if (error_string)
archive_string_sprintf(error_string,
"Cannot extract through symlink %s",
path);
res = ARCHIVE_FAILED;
break;
}
}
/* be sure to always maintain this */
tail[0] = c;
if (tail[0] != '\0')
tail++; /* Advance to the next segment. */
}
/* Catches loop exits via break */
tail[0] = c;
#ifdef HAVE_FCHDIR
/* If we changed directory above, restore it here. */
if (restore_pwd >= 0) {
r = fchdir(restore_pwd);
if (r != 0) {
if(error_number) *error_number = errno;
if(error_string)
archive_string_sprintf(error_string,
"chdir() failure");
}
close(restore_pwd);
restore_pwd = -1;
if (r != 0) {
res = (ARCHIVE_FATAL);
}
}
#endif
/* TODO: reintroduce a safe cache here? */
return res;
#endif
}
| 167,135 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
|
Code: static void unix_detach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
scm->fp = UNIXCB(skb).fp;
UNIXCB(skb).fp = NULL;
for (i = scm->fp->count-1; i >= 0; i--)
unix_notinflight(scm->fp->fp[i]);
}
Commit Message: unix: correctly track in-flight fds in sending process user_struct
The commit referenced in the Fixes tag incorrectly accounted the number
of in-flight fds over a unix domain socket to the original opener
of the file-descriptor. This allows another process to arbitrary
deplete the original file-openers resource limit for the maximum of
open files. Instead the sending processes and its struct cred should
be credited.
To do so, we add a reference counted struct user_struct pointer to the
scm_fp_list and use it to account for the number of inflight unix fds.
Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets")
Reported-by: David Herrmann <[email protected]>
Cc: David Herrmann <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: Linus Torvalds <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
|
static void unix_detach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
scm->fp = UNIXCB(skb).fp;
UNIXCB(skb).fp = NULL;
for (i = scm->fp->count-1; i >= 0; i--)
unix_notinflight(scm->fp->user, scm->fp->fp[i]);
}
| 167,395 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.