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: long SegmentInfo::Parse()
{
assert(m_pMuxingAppAsUTF8 == NULL);
assert(m_pWritingAppAsUTF8 == NULL);
assert(m_pTitleAsUTF8 == NULL);
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start;
const long long stop = m_start + m_size;
m_timecodeScale = 1000000;
m_duration = -1;
while (pos < stop)
{
long long id, size;
const long status = ParseElementHeader(
pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x0AD7B1) //Timecode Scale
{
m_timecodeScale = UnserializeUInt(pReader, pos, size);
if (m_timecodeScale <= 0)
return E_FILE_FORMAT_INVALID;
}
else if (id == 0x0489) //Segment duration
{
const long status = UnserializeFloat(
pReader,
pos,
size,
m_duration);
if (status < 0)
return status;
if (m_duration < 0)
return E_FILE_FORMAT_INVALID;
}
else if (id == 0x0D80) //MuxingApp
{
const long status = UnserializeString(
pReader,
pos,
size,
m_pMuxingAppAsUTF8);
if (status)
return status;
}
else if (id == 0x1741) //WritingApp
{
const long status = UnserializeString(
pReader,
pos,
size,
m_pWritingAppAsUTF8);
if (status)
return status;
}
else if (id == 0x3BA9) //Title
{
const long status = UnserializeString(
pReader,
pos,
size,
m_pTitleAsUTF8);
if (status)
return status;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long SegmentInfo::Parse()
| 174,404 |
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: MagickExport void CatchException(ExceptionInfo *exception)
{
register const ExceptionInfo
*p;
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if (exception->exceptions == (void *) NULL)
return;
LockSemaphoreInfo(exception->semaphore);
ResetLinkedListIterator((LinkedListInfo *) exception->exceptions);
p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *)
exception->exceptions);
while (p != (const ExceptionInfo *) NULL)
{
if ((p->severity >= WarningException) && (p->severity < ErrorException))
MagickWarning(p->severity,p->reason,p->description);
if ((p->severity >= ErrorException) && (p->severity < FatalErrorException))
MagickError(p->severity,p->reason,p->description);
if (p->severity >= FatalErrorException)
MagickFatalError(p->severity,p->reason,p->description);
p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *)
exception->exceptions);
}
UnlockSemaphoreInfo(exception->semaphore);
ClearMagickException(exception);
}
Commit Message: Suspend exception processing if there are too many exceptions
CWE ID: CWE-119 | MagickExport void CatchException(ExceptionInfo *exception)
{
register const ExceptionInfo
*p;
ssize_t
i;
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if (exception->exceptions == (void *) NULL)
return;
LockSemaphoreInfo(exception->semaphore);
ResetLinkedListIterator((LinkedListInfo *) exception->exceptions);
p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *)
exception->exceptions);
for (i=0; p != (const ExceptionInfo *) NULL; i++)
{
if (p->severity >= FatalErrorException)
MagickFatalError(p->severity,p->reason,p->description);
if (i < MaxExceptions)
{
if ((p->severity >= ErrorException) &&
(p->severity < FatalErrorException))
MagickError(p->severity,p->reason,p->description);
if ((p->severity >= WarningException) && (p->severity < ErrorException))
MagickWarning(p->severity,p->reason,p->description);
}
else
if (i == MaxExceptions)
MagickError(ResourceLimitError,"too many exceptions",
"exception processing suspended");
p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *)
exception->exceptions);
}
UnlockSemaphoreInfo(exception->semaphore);
ClearMagickException(exception);
}
| 168,541 |
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: __be32 ipv6_proxy_select_ident(struct net *net, struct sk_buff *skb)
{
static u32 ip6_proxy_idents_hashrnd __read_mostly;
struct in6_addr buf[2];
struct in6_addr *addrs;
u32 id;
addrs = skb_header_pointer(skb,
skb_network_offset(skb) +
offsetof(struct ipv6hdr, saddr),
sizeof(buf), buf);
if (!addrs)
return 0;
net_get_random_once(&ip6_proxy_idents_hashrnd,
sizeof(ip6_proxy_idents_hashrnd));
id = __ipv6_select_ident(net, ip6_proxy_idents_hashrnd,
&addrs[1], &addrs[0]);
return htonl(id);
}
Commit Message: inet: switch IP ID generator to siphash
According to Amit Klein and Benny Pinkas, IP ID generation is too weak
and might be used by attackers.
Even with recent net_hash_mix() fix (netns: provide pure entropy for net_hash_mix())
having 64bit key and Jenkins hash is risky.
It is time to switch to siphash and its 128bit keys.
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Amit Klein <[email protected]>
Reported-by: Benny Pinkas <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | __be32 ipv6_proxy_select_ident(struct net *net, struct sk_buff *skb)
{
struct in6_addr buf[2];
struct in6_addr *addrs;
u32 id;
addrs = skb_header_pointer(skb,
skb_network_offset(skb) +
offsetof(struct ipv6hdr, saddr),
sizeof(buf), buf);
if (!addrs)
return 0;
id = __ipv6_select_ident(net, &addrs[1], &addrs[0]);
return htonl(id);
}
| 169,718 |
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: http_splitheader(struct http *hp, int req)
{
char *p, *q, **hh;
int n;
char buf[20];
CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC);
if (req) {
memset(hp->req, 0, sizeof hp->req);
hh = hp->req;
} else {
memset(hp->resp, 0, sizeof hp->resp);
hh = hp->resp;
}
n = 0;
p = hp->rxbuf;
/* REQ/PROTO */
while (vct_islws(*p))
p++;
hh[n++] = p;
while (!vct_islws(*p))
p++;
assert(!vct_iscrlf(*p));
*p++ = '\0';
/* URL/STATUS */
while (vct_issp(*p)) /* XXX: H space only */
p++;
assert(!vct_iscrlf(*p));
hh[n++] = p;
while (!vct_islws(*p))
p++;
if (vct_iscrlf(*p)) {
hh[n++] = NULL;
q = p;
p += vct_skipcrlf(p);
*q = '\0';
} else {
*p++ = '\0';
/* PROTO/MSG */
while (vct_issp(*p)) /* XXX: H space only */
p++;
hh[n++] = p;
while (!vct_iscrlf(*p))
p++;
q = p;
p += vct_skipcrlf(p);
*q = '\0';
}
assert(n == 3);
while (*p != '\0') {
assert(n < MAX_HDR);
if (vct_iscrlf(*p))
break;
hh[n++] = p++;
while (*p != '\0' && !vct_iscrlf(*p))
p++;
q = p;
p += vct_skipcrlf(p);
*q = '\0';
}
p += vct_skipcrlf(p);
assert(*p == '\0');
for (n = 0; n < 3 || hh[n] != NULL; n++) {
sprintf(buf, "http[%2d] ", n);
vtc_dump(hp->vl, 4, buf, hh[n], -1);
}
}
Commit Message: Do not consider a CR by itself as a valid line terminator
Varnish (prior to version 4.0) was not following the standard with
regard to line separator.
Spotted and analyzed by: Régis Leroy [regilero] [email protected]
CWE ID: | http_splitheader(struct http *hp, int req)
{
char *p, *q, **hh;
int n;
char buf[20];
CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC);
if (req) {
memset(hp->req, 0, sizeof hp->req);
hh = hp->req;
} else {
memset(hp->resp, 0, sizeof hp->resp);
hh = hp->resp;
}
n = 0;
p = hp->rxbuf;
/* REQ/PROTO */
while (vct_islws(*p))
p++;
hh[n++] = p;
while (!vct_islws(*p))
p++;
assert(!vct_iscrlf(p));
*p++ = '\0';
/* URL/STATUS */
while (vct_issp(*p)) /* XXX: H space only */
p++;
assert(!vct_iscrlf(p));
hh[n++] = p;
while (!vct_islws(*p))
p++;
if (vct_iscrlf(p)) {
hh[n++] = NULL;
q = p;
p += vct_skipcrlf(p);
*q = '\0';
} else {
*p++ = '\0';
/* PROTO/MSG */
while (vct_issp(*p)) /* XXX: H space only */
p++;
hh[n++] = p;
while (!vct_iscrlf(p))
p++;
q = p;
p += vct_skipcrlf(p);
*q = '\0';
}
assert(n == 3);
while (*p != '\0') {
assert(n < MAX_HDR);
if (vct_iscrlf(p))
break;
hh[n++] = p++;
while (*p != '\0' && !vct_iscrlf(p))
p++;
q = p;
p += vct_skipcrlf(p);
*q = '\0';
}
p += vct_skipcrlf(p);
assert(*p == '\0');
for (n = 0; n < 3 || hh[n] != NULL; n++) {
sprintf(buf, "http[%2d] ", n);
vtc_dump(hp->vl, 4, buf, hh[n], -1);
}
}
| 170,000 |
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_str_hash_len (MyObject *obj, GHashTable *table, guint *len, GError **error)
{
*len = 0;
g_hash_table_foreach (table, hash_foreach, len);
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_str_hash_len (MyObject *obj, GHashTable *table, guint *len, GError **error)
| 165,121 |
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 main( int /*argc*/, char ** argv)
{
InitializeMagick(*argv);
int failures=0;
try {
string srcdir("");
if(getenv("SRCDIR") != 0)
srcdir = getenv("SRCDIR");
list<Image> imageList;
readImages( &imageList, srcdir + "test_image_anim.miff" );
Image appended;
appendImages( &appended, imageList.begin(), imageList.end() );
if (( appended.signature() != "3a90bb0bb8f69f6788ab99e9e25598a0d6c5cdbbb797f77ad68011e0a8b1689d" ) &&
( appended.signature() != "c15fcd1e739b73638dc4e36837bdb53f7087359544664caf7b1763928129f3c7" ) &&
( appended.signature() != "229ff72f812e5f536245dc3b4502a0bc2ab2363f67c545863a85ab91ebfbfb83" ) &&
( appended.signature() != "b98c42c55fc4e661cb3684154256809c03c0c6b53da2738b6ce8066e1b6ddef0" ))
{
++failures;
cout << "Line: " << __LINE__
<< " Horizontal append failed, signature = "
<< appended.signature() << endl;
appended.write("appendImages_horizontal_out.miff");
}
appendImages( &appended, imageList.begin(), imageList.end(), true );
if (( appended.signature() != "d73d25ccd6011936d08b6d0d89183b7a61790544c2195269aff4db2f782ffc08" ) &&
( appended.signature() != "0909f7ffa7c6ea410fb2ebfdbcb19d61b19c4bd271851ce3bd51662519dc2b58" ) &&
( appended.signature() != "11b97ba6ac1664aa1c2faed4c86195472ae9cce2ed75402d975bb4ffcf1de751" ) &&
( appended.signature() != "cae4815eeb3cb689e73b94d897a9957d3414d1d4f513e8b5e52579b05d164bfe" ))
{
++failures;
cout << "Line: " << __LINE__
<< " Vertical append failed, signature = "
<< appended.signature() << endl;
appended.write("appendImages_vertical_out.miff");
}
}
catch( Exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
catch( exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
if ( failures )
{
cout << failures << " failures" << endl;
return 1;
}
return 0;
}
Commit Message: Fix signature mismatch
CWE ID: CWE-369 | int main( int /*argc*/, char ** argv)
{
InitializeMagick(*argv);
int failures=0;
try {
string srcdir("");
if(getenv("SRCDIR") != 0)
srcdir = getenv("SRCDIR");
list<Image> imageList;
readImages( &imageList, srcdir + "test_image_anim.miff" );
Image appended;
appendImages( &appended, imageList.begin(), imageList.end() );
if (( appended.signature() != "3a90bb0bb8f69f6788ab99e9e25598a0d6c5cdbbb797f77ad68011e0a8b1689d" ) &&
( appended.signature() != "c15fcd1e739b73638dc4e36837bdb53f7087359544664caf7b1763928129f3c7" ) &&
( appended.signature() != "229ff72f812e5f536245dc3b4502a0bc2ab2363f67c545863a85ab91ebfbfb83" ) &&
( appended.signature() != "b98c42c55fc4e661cb3684154256809c03c0c6b53da2738b6ce8066e1b6ddef0" ))
{
++failures;
cout << "Line: " << __LINE__
<< " Horizontal append failed, signature = "
<< appended.signature() << endl;
appended.write("appendImages_horizontal_out.miff");
}
appendImages( &appended, imageList.begin(), imageList.end(), true );
if (( appended.signature() != "d73d25ccd6011936d08b6d0d89183b7a61790544c2195269aff4db2f782ffc08" ) &&
( appended.signature() != "f3590c183018757da798613a23505ab9600b35935988eee12f096cb6219f2bc3" ) &&
( appended.signature() != "11b97ba6ac1664aa1c2faed4c86195472ae9cce2ed75402d975bb4ffcf1de751" ) &&
( appended.signature() != "cae4815eeb3cb689e73b94d897a9957d3414d1d4f513e8b5e52579b05d164bfe" ))
{
++failures;
cout << "Line: " << __LINE__
<< " Vertical append failed, signature = "
<< appended.signature() << endl;
appended.write("appendImages_vertical_out.miff");
}
}
catch( Exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
catch( exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
if ( failures )
{
cout << failures << " failures" << endl;
return 1;
}
return 0;
}
| 170,112 |
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 *ReadOneJNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
Image
*alpha_image,
*color_image,
*image,
*jng_image;
ImageInfo
*alpha_image_info,
*color_image_info;
MagickBooleanType
logging;
int
unique_filenames;
ssize_t
y;
MagickBooleanType
status;
png_uint_32
jng_height,
jng_width;
png_byte
jng_color_type,
jng_image_sample_depth,
jng_image_compression_method,
jng_image_interlace_method,
jng_alpha_sample_depth,
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method;
register const PixelPacket
*s;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*p;
unsigned int
read_JSEP,
reading_idat;
size_t
length;
jng_alpha_compression_method=0;
jng_alpha_sample_depth=8;
jng_color_type=0;
jng_height=0;
jng_width=0;
alpha_image=(Image *) NULL;
color_image=(Image *) NULL;
alpha_image_info=(ImageInfo *) NULL;
color_image_info=(ImageInfo *) NULL;
unique_filenames=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneJNGImage()");
image=mng_info->image;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireNextImage()");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
/*
Signature bytes have already been read.
*/
read_JSEP=MagickFalse;
reading_idat=MagickFalse;
for (;;)
{
char
type[MaxTextExtent];
unsigned char
*chunk;
unsigned int
count;
/*
Read a new JNG chunk.
*/
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
break;
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(unsigned int) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading JNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX || count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
if (length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
if (memcmp(type,mng_JHDR,4) == 0)
{
if (length == 16)
{
jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if ((jng_width == 0) || (jng_height == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
jng_color_type=p[8];
jng_image_sample_depth=p[9];
jng_image_compression_method=p[10];
jng_image_interlace_method=p[11];
image->interlace=jng_image_interlace_method != 0 ? PNGInterlace :
NoInterlace;
jng_alpha_sample_depth=p[12];
jng_alpha_compression_method=p[13];
jng_alpha_filter_method=p[14];
jng_alpha_interlace_method=p[15];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_width: %16lu, jng_height: %16lu\n"
" jng_color_type: %16d, jng_image_sample_depth: %3d\n"
" jng_image_compression_method:%3d",
(unsigned long) jng_width, (unsigned long) jng_height,
jng_color_type, jng_image_sample_depth,
jng_image_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_image_interlace_method: %3d"
" jng_alpha_sample_depth: %3d",
jng_image_interlace_method,
jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_alpha_compression_method:%3d\n"
" jng_alpha_filter_method: %3d\n"
" jng_alpha_interlace_method: %3d",
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) &&
((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) ||
(memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0)))
{
/*
o create color_image
o open color_blob, attached to color_image
o if (color type has alpha)
open alpha_blob, attached to alpha_image
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating color_blob.");
color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo));
if (color_image_info == (ImageInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
GetImageInfo(color_image_info);
color_image=AcquireImage(color_image_info);
if (color_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) AcquireUniqueFilename(color_image->filename);
unique_filenames++;
status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))
{
alpha_image_info=(ImageInfo *)
AcquireMagickMemory(sizeof(ImageInfo));
if (alpha_image_info == (ImageInfo *) NULL)
{
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
GetImageInfo(alpha_image_info);
alpha_image=AcquireImage(alpha_image_info);
if (alpha_image == (Image *) NULL)
{
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating alpha_blob.");
(void) AcquireUniqueFilename(alpha_image->filename);
unique_filenames++;
status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if (jng_alpha_compression_method == 0)
{
unsigned char
data[18];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing IHDR chunk to alpha_blob.");
(void) WriteBlob(alpha_image,8,(const unsigned char *)
"\211PNG\r\n\032\n");
(void) WriteBlobMSBULong(alpha_image,13L);
PNGType(data,mng_IHDR);
LogPNGChunk(logging,mng_IHDR,13L);
PNGLong(data+4,jng_width);
PNGLong(data+8,jng_height);
data[12]=jng_alpha_sample_depth;
data[13]=0; /* color_type gray */
data[14]=0; /* compression method 0 */
data[15]=0; /* filter_method 0 */
data[16]=0; /* interlace_method 0 */
(void) WriteBlob(alpha_image,17,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,17));
}
}
reading_idat=MagickTrue;
}
if (memcmp(type,mng_JDAT,4) == 0)
{
/* Copy chunk to color_image->blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAT chunk data to color_blob.");
if (length != 0)
{
(void) WriteBlob(color_image,length,chunk);
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
}
continue;
}
if (memcmp(type,mng_IDAT,4) == 0)
{
png_byte
data[5];
/* Copy IDAT header and chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying IDAT chunk data to alpha_blob.");
(void) WriteBlobMSBULong(alpha_image,(size_t) length);
PNGType(data,mng_IDAT);
LogPNGChunk(logging,mng_IDAT,length);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlob(alpha_image,length,chunk);
(void) WriteBlobMSBULong(alpha_image,
crc32(crc32(0,data,4),chunk,(uInt) length));
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0))
{
/* Copy chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAA chunk data to alpha_blob.");
(void) WriteBlob(alpha_image,length,chunk);
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_JSEP,4) == 0)
{
read_JSEP=MagickTrue;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
if (length == 2)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=image->background_color.red;
image->background_color.blue=image->background_color.red;
}
if (length == 6)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=ScaleCharToQuantum(p[3]);
image->background_color.blue=ScaleCharToQuantum(p[5]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
image->gamma=((float) mng_get_long(p))*0.00001;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
if (length == 32)
{
image->chromaticity.white_point.x=0.00001*mng_get_long(p);
image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]);
image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]);
image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]);
image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]);
image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]);
image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]);
image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
if (length == 1)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_oFFs,4) == 0)
{
if (length > 8)
{
image->page.x=(ssize_t) mng_get_long(p);
image->page.y=(ssize_t) mng_get_long(&p[4]);
if ((int) p[8] != 0)
{
image->page.x/=10000;
image->page.y/=10000;
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
image->x_resolution=(double) mng_get_long(p);
image->y_resolution=(double) mng_get_long(&p[4]);
if ((int) p[8] == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=image->x_resolution/100.0f;
image->y_resolution=image->y_resolution/100.0f;
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if 0
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#endif
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (memcmp(type,mng_IEND,4))
continue;
break;
}
/* IEND found */
/*
Finish up reading image data:
o read main image from color_blob.
o close color_blob.
o if (color_type has alpha)
if alpha_encoding is PNG
read secondary image from alpha_blob via ReadPNG
if alpha_encoding is JPEG
read secondary image from alpha_blob via ReadJPEG
o close alpha_blob.
o copy intensity of secondary image into
opacity samples of main image.
o destroy the secondary image.
*/
if (color_image_info == (ImageInfo *) NULL)
{
assert(color_image == (Image *) NULL);
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
if (color_image == (Image *) NULL)
{
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
(void) SeekBlob(color_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading jng_image from color_blob.");
assert(color_image_info != (ImageInfo *) NULL);
(void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s",
color_image->filename);
color_image_info->ping=MagickFalse; /* To do: avoid this */
jng_image=ReadImage(color_image_info,exception);
(void) RelinquishUniqueFileResource(color_image->filename);
unique_filenames--;
color_image=DestroyImage(color_image);
color_image_info=DestroyImageInfo(color_image_info);
if (jng_image == (Image *) NULL)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying jng_image pixels to main image.");
image->columns=jng_width;
image->rows=jng_height;
length=image->columns*sizeof(PixelPacket);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
(void) CopyMagickMemory(q,s,length);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
jng_image=DestroyImage(jng_image);
if (image_info->ping == MagickFalse)
{
if (jng_color_type >= 12)
{
if (jng_alpha_compression_method == 0)
{
png_byte
data[5];
(void) WriteBlobMSBULong(alpha_image,0x00000000L);
PNGType(data,mng_IEND);
LogPNGChunk(logging,mng_IEND,0L);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,4));
}
(void) SeekBlob(alpha_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading opacity from alpha_blob.");
(void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent,
"%s",alpha_image->filename);
jng_image=ReadImage(alpha_image_info,exception);
if (jng_image != (Image *) NULL)
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,
&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (image->matte != MagickFalse)
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
SetPixelOpacity(q,QuantumRange-
GetPixelRed(s));
else
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
{
SetPixelAlpha(q,GetPixelRed(s));
if (GetPixelOpacity(q) != OpaqueOpacity)
image->matte=MagickTrue;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
(void) RelinquishUniqueFileResource(alpha_image->filename);
unique_filenames--;
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
if (jng_image != (Image *) NULL)
jng_image=DestroyImage(jng_image);
}
}
/* Read the JNG image. */
if (mng_info->mng_type == 0)
{
mng_info->mng_width=jng_width;
mng_info->mng_height=jng_height;
}
if (image->page.width == 0 && image->page.height == 0)
{
image->page.width=jng_width;
image->page.height=jng_height;
}
if (image->page.x == 0 && image->page.y == 0)
{
image->page.x=mng_info->x_off[mng_info->object_id];
image->page.y=mng_info->y_off[mng_info->object_id];
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
mng_info->image_found++;
status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames);
return(image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/550
CWE ID: CWE-772 | static Image *ReadOneJNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
Image
*alpha_image,
*color_image,
*image,
*jng_image;
ImageInfo
*alpha_image_info,
*color_image_info;
MagickBooleanType
logging;
int
unique_filenames;
ssize_t
y;
MagickBooleanType
status;
png_uint_32
jng_height,
jng_width;
png_byte
jng_color_type,
jng_image_sample_depth,
jng_image_compression_method,
jng_image_interlace_method,
jng_alpha_sample_depth,
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method;
register const PixelPacket
*s;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*p;
unsigned int
read_JSEP,
reading_idat;
size_t
length;
jng_alpha_compression_method=0;
jng_alpha_sample_depth=8;
jng_color_type=0;
jng_height=0;
jng_width=0;
alpha_image=(Image *) NULL;
color_image=(Image *) NULL;
alpha_image_info=(ImageInfo *) NULL;
color_image_info=(ImageInfo *) NULL;
unique_filenames=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneJNGImage()");
image=mng_info->image;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireNextImage()");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
/*
Signature bytes have already been read.
*/
read_JSEP=MagickFalse;
reading_idat=MagickFalse;
for (;;)
{
char
type[MaxTextExtent];
unsigned char
*chunk;
unsigned int
count;
/*
Read a new JNG chunk.
*/
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
break;
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(unsigned int) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading JNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX || count == 0)
{
if (color_image != (Image *) NULL)
color_image=DestroyImage(color_image);
if (color_image_info != (Image *) NULL)
color_image_info=DestroyImageInfo(color_image_info);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
if (length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
if (memcmp(type,mng_JHDR,4) == 0)
{
if (length == 16)
{
jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if ((jng_width == 0) || (jng_height == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
jng_color_type=p[8];
jng_image_sample_depth=p[9];
jng_image_compression_method=p[10];
jng_image_interlace_method=p[11];
image->interlace=jng_image_interlace_method != 0 ? PNGInterlace :
NoInterlace;
jng_alpha_sample_depth=p[12];
jng_alpha_compression_method=p[13];
jng_alpha_filter_method=p[14];
jng_alpha_interlace_method=p[15];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_width: %16lu, jng_height: %16lu\n"
" jng_color_type: %16d, jng_image_sample_depth: %3d\n"
" jng_image_compression_method:%3d",
(unsigned long) jng_width, (unsigned long) jng_height,
jng_color_type, jng_image_sample_depth,
jng_image_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_image_interlace_method: %3d"
" jng_alpha_sample_depth: %3d",
jng_image_interlace_method,
jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_alpha_compression_method:%3d\n"
" jng_alpha_filter_method: %3d\n"
" jng_alpha_interlace_method: %3d",
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) &&
((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) ||
(memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0)))
{
/*
o create color_image
o open color_blob, attached to color_image
o if (color type has alpha)
open alpha_blob, attached to alpha_image
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating color_blob.");
color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo));
if (color_image_info == (ImageInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
GetImageInfo(color_image_info);
color_image=AcquireImage(color_image_info);
if (color_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) AcquireUniqueFilename(color_image->filename);
unique_filenames++;
status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))
{
alpha_image_info=(ImageInfo *)
AcquireMagickMemory(sizeof(ImageInfo));
if (alpha_image_info == (ImageInfo *) NULL)
{
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
GetImageInfo(alpha_image_info);
alpha_image=AcquireImage(alpha_image_info);
if (alpha_image == (Image *) NULL)
{
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating alpha_blob.");
(void) AcquireUniqueFilename(alpha_image->filename);
unique_filenames++;
status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if (jng_alpha_compression_method == 0)
{
unsigned char
data[18];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing IHDR chunk to alpha_blob.");
(void) WriteBlob(alpha_image,8,(const unsigned char *)
"\211PNG\r\n\032\n");
(void) WriteBlobMSBULong(alpha_image,13L);
PNGType(data,mng_IHDR);
LogPNGChunk(logging,mng_IHDR,13L);
PNGLong(data+4,jng_width);
PNGLong(data+8,jng_height);
data[12]=jng_alpha_sample_depth;
data[13]=0; /* color_type gray */
data[14]=0; /* compression method 0 */
data[15]=0; /* filter_method 0 */
data[16]=0; /* interlace_method 0 */
(void) WriteBlob(alpha_image,17,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,17));
}
}
reading_idat=MagickTrue;
}
if (memcmp(type,mng_JDAT,4) == 0)
{
/* Copy chunk to color_image->blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAT chunk data to color_blob.");
if (length != 0)
{
(void) WriteBlob(color_image,length,chunk);
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
}
continue;
}
if (memcmp(type,mng_IDAT,4) == 0)
{
png_byte
data[5];
/* Copy IDAT header and chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying IDAT chunk data to alpha_blob.");
(void) WriteBlobMSBULong(alpha_image,(size_t) length);
PNGType(data,mng_IDAT);
LogPNGChunk(logging,mng_IDAT,length);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlob(alpha_image,length,chunk);
(void) WriteBlobMSBULong(alpha_image,
crc32(crc32(0,data,4),chunk,(uInt) length));
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0))
{
/* Copy chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAA chunk data to alpha_blob.");
(void) WriteBlob(alpha_image,length,chunk);
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_JSEP,4) == 0)
{
read_JSEP=MagickTrue;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
if (length == 2)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=image->background_color.red;
image->background_color.blue=image->background_color.red;
}
if (length == 6)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=ScaleCharToQuantum(p[3]);
image->background_color.blue=ScaleCharToQuantum(p[5]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
image->gamma=((float) mng_get_long(p))*0.00001;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
if (length == 32)
{
image->chromaticity.white_point.x=0.00001*mng_get_long(p);
image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]);
image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]);
image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]);
image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]);
image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]);
image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]);
image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
if (length == 1)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_oFFs,4) == 0)
{
if (length > 8)
{
image->page.x=(ssize_t) mng_get_long(p);
image->page.y=(ssize_t) mng_get_long(&p[4]);
if ((int) p[8] != 0)
{
image->page.x/=10000;
image->page.y/=10000;
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
image->x_resolution=(double) mng_get_long(p);
image->y_resolution=(double) mng_get_long(&p[4]);
if ((int) p[8] == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=image->x_resolution/100.0f;
image->y_resolution=image->y_resolution/100.0f;
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if 0
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#endif
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (memcmp(type,mng_IEND,4))
continue;
break;
}
/* IEND found */
/*
Finish up reading image data:
o read main image from color_blob.
o close color_blob.
o if (color_type has alpha)
if alpha_encoding is PNG
read secondary image from alpha_blob via ReadPNG
if alpha_encoding is JPEG
read secondary image from alpha_blob via ReadJPEG
o close alpha_blob.
o copy intensity of secondary image into
opacity samples of main image.
o destroy the secondary image.
*/
if (color_image_info == (ImageInfo *) NULL)
{
assert(color_image == (Image *) NULL);
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
if (color_image == (Image *) NULL)
{
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
(void) SeekBlob(color_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading jng_image from color_blob.");
assert(color_image_info != (ImageInfo *) NULL);
(void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s",
color_image->filename);
color_image_info->ping=MagickFalse; /* To do: avoid this */
jng_image=ReadImage(color_image_info,exception);
(void) RelinquishUniqueFileResource(color_image->filename);
unique_filenames--;
color_image=DestroyImage(color_image);
color_image_info=DestroyImageInfo(color_image_info);
if (jng_image == (Image *) NULL)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying jng_image pixels to main image.");
image->columns=jng_width;
image->rows=jng_height;
length=image->columns*sizeof(PixelPacket);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
(void) CopyMagickMemory(q,s,length);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
jng_image=DestroyImage(jng_image);
if (image_info->ping == MagickFalse)
{
if (jng_color_type >= 12)
{
if (jng_alpha_compression_method == 0)
{
png_byte
data[5];
(void) WriteBlobMSBULong(alpha_image,0x00000000L);
PNGType(data,mng_IEND);
LogPNGChunk(logging,mng_IEND,0L);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,4));
}
(void) SeekBlob(alpha_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading opacity from alpha_blob.");
(void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent,
"%s",alpha_image->filename);
jng_image=ReadImage(alpha_image_info,exception);
if (jng_image != (Image *) NULL)
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,
&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (image->matte != MagickFalse)
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
SetPixelOpacity(q,QuantumRange-
GetPixelRed(s));
else
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
{
SetPixelAlpha(q,GetPixelRed(s));
if (GetPixelOpacity(q) != OpaqueOpacity)
image->matte=MagickTrue;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
(void) RelinquishUniqueFileResource(alpha_image->filename);
unique_filenames--;
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
if (jng_image != (Image *) NULL)
jng_image=DestroyImage(jng_image);
}
}
/* Read the JNG image. */
if (mng_info->mng_type == 0)
{
mng_info->mng_width=jng_width;
mng_info->mng_height=jng_height;
}
if (image->page.width == 0 && image->page.height == 0)
{
image->page.width=jng_width;
image->page.height=jng_height;
}
if (image->page.x == 0 && image->page.y == 0)
{
image->page.x=mng_info->x_off[mng_info->object_id];
image->page.y=mng_info->y_off[mng_info->object_id];
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
mng_info->image_found++;
status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames);
return(image);
}
| 167,981 |
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 rfcomm_get_dev_list(void __user *arg)
{
struct rfcomm_dev *dev;
struct rfcomm_dev_list_req *dl;
struct rfcomm_dev_info *di;
int n = 0, size, err;
u16 dev_num;
BT_DBG("");
if (get_user(dev_num, (u16 __user *) arg))
return -EFAULT;
if (!dev_num || dev_num > (PAGE_SIZE * 4) / sizeof(*di))
return -EINVAL;
size = sizeof(*dl) + dev_num * sizeof(*di);
dl = kmalloc(size, GFP_KERNEL);
if (!dl)
return -ENOMEM;
di = dl->dev_info;
spin_lock(&rfcomm_dev_lock);
list_for_each_entry(dev, &rfcomm_dev_list, list) {
if (test_bit(RFCOMM_TTY_RELEASED, &dev->flags))
continue;
(di + n)->id = dev->id;
(di + n)->flags = dev->flags;
(di + n)->state = dev->dlc->state;
(di + n)->channel = dev->channel;
bacpy(&(di + n)->src, &dev->src);
bacpy(&(di + n)->dst, &dev->dst);
if (++n >= dev_num)
break;
}
spin_unlock(&rfcomm_dev_lock);
dl->dev_num = n;
size = sizeof(*dl) + n * sizeof(*di);
err = copy_to_user(arg, dl, size);
kfree(dl);
return err ? -EFAULT : 0;
}
Commit Message: Bluetooth: RFCOMM - Fix info leak in ioctl(RFCOMMGETDEVLIST)
The RFCOMM code fails to initialize the two padding bytes of struct
rfcomm_dev_list_req inserted for alignment before copying it to
userland. Additionally there are two padding bytes in each instance of
struct rfcomm_dev_info. The ioctl() that for disclosures two bytes plus
dev_num times two bytes uninitialized kernel heap memory.
Allocate the memory using kzalloc() to fix this issue.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Marcel Holtmann <[email protected]>
Cc: Gustavo Padovan <[email protected]>
Cc: Johan Hedberg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int rfcomm_get_dev_list(void __user *arg)
{
struct rfcomm_dev *dev;
struct rfcomm_dev_list_req *dl;
struct rfcomm_dev_info *di;
int n = 0, size, err;
u16 dev_num;
BT_DBG("");
if (get_user(dev_num, (u16 __user *) arg))
return -EFAULT;
if (!dev_num || dev_num > (PAGE_SIZE * 4) / sizeof(*di))
return -EINVAL;
size = sizeof(*dl) + dev_num * sizeof(*di);
dl = kzalloc(size, GFP_KERNEL);
if (!dl)
return -ENOMEM;
di = dl->dev_info;
spin_lock(&rfcomm_dev_lock);
list_for_each_entry(dev, &rfcomm_dev_list, list) {
if (test_bit(RFCOMM_TTY_RELEASED, &dev->flags))
continue;
(di + n)->id = dev->id;
(di + n)->flags = dev->flags;
(di + n)->state = dev->dlc->state;
(di + n)->channel = dev->channel;
bacpy(&(di + n)->src, &dev->src);
bacpy(&(di + n)->dst, &dev->dst);
if (++n >= dev_num)
break;
}
spin_unlock(&rfcomm_dev_lock);
dl->dev_num = n;
size = sizeof(*dl) + n * sizeof(*di);
err = copy_to_user(arg, dl, size);
kfree(dl);
return err ? -EFAULT : 0;
}
| 169,898 |
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 JSValueRef addTouchPointCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 2)
return JSValueMakeUndefined(context);
int x = static_cast<int>(JSValueToNumber(context, arguments[0], exception));
ASSERT(!exception || !*exception);
int y = static_cast<int>(JSValueToNumber(context, arguments[1], exception));
ASSERT(!exception || !*exception);
BlackBerry::Platform::TouchPoint touch;
touch.m_id = touches.isEmpty() ? 0 : touches.last().m_id + 1;
IntPoint pos(x, y);
touch.m_pos = pos;
touch.m_screenPos = pos;
touch.m_state = BlackBerry::Platform::TouchPoint::TouchPressed;
touches.append(touch);
return JSValueMakeUndefined(context);
}
Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API
https://bugs.webkit.org/show_bug.cgi?id=105143
RIM PR 171941
Reviewed by Rob Buis.
Internally reviewed by George Staikos.
Source/WebCore:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit.
Also adapt to new method names and encapsulation of TouchPoint data
members.
No change in behavior, no new tests.
* platform/blackberry/PlatformTouchPointBlackBerry.cpp:
(WebCore::PlatformTouchPoint::PlatformTouchPoint):
Source/WebKit/blackberry:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit. One exception
is when passing events to a full screen plugin.
Also adapt to new method names and encapsulation of TouchPoint data
members.
* Api/WebPage.cpp:
(BlackBerry::WebKit::WebPage::touchEvent):
(BlackBerry::WebKit::WebPage::touchPointAsMouseEvent):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin):
* WebKitSupport/InputHandler.cpp:
(BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint):
* WebKitSupport/InputHandler.h:
(InputHandler):
* WebKitSupport/TouchEventHandler.cpp:
(BlackBerry::WebKit::TouchEventHandler::doFatFingers):
(BlackBerry::WebKit::TouchEventHandler::handleTouchPoint):
* WebKitSupport/TouchEventHandler.h:
(TouchEventHandler):
Tools:
Adapt to new method names and encapsulation of TouchPoint data members.
* DumpRenderTree/blackberry/EventSender.cpp:
(addTouchPointCallback):
(updateTouchPointCallback):
(touchEndCallback):
(releaseTouchPointCallback):
(sendTouchEvent):
git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static JSValueRef addTouchPointCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 2)
return JSValueMakeUndefined(context);
int x = static_cast<int>(JSValueToNumber(context, arguments[0], exception));
ASSERT(!exception || !*exception);
int y = static_cast<int>(JSValueToNumber(context, arguments[1], exception));
ASSERT(!exception || !*exception);
int id = touches.isEmpty() ? 0 : touches.last().id() + 1;
// pixelViewportPosition is unused in the WebKit layer, so use this for screen position
IntPoint pos(x, y);
BlackBerry::Platform::TouchPoint touch(id, BlackBerry::Platform::TouchPoint::TouchPressed, pos, pos, 0);
// Unfortunately we don't know the scroll position at this point, so use pos for the content position too.
// This assumes scroll position is 0,0
touch.populateDocumentPosition(pos, pos);
touches.append(touch);
return JSValueMakeUndefined(context);
}
| 170,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 int crypto_report_comp(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_comp rcomp;
strlcpy(rcomp.type, "compression", sizeof(rcomp.type));
if (nla_put(skb, CRYPTOCFGA_REPORT_COMPRESS,
sizeof(struct crypto_report_comp), &rcomp))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Commit Message: crypto: user - fix leaking uninitialized memory to userspace
All bytes of the NETLINK_CRYPTO report structures must be initialized,
since they are copied to userspace. The change from strncpy() to
strlcpy() broke this. As a minimal fix, change it back.
Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion")
Cc: <[email protected]> # v4.12+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: | static int crypto_report_comp(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_comp rcomp;
strncpy(rcomp.type, "compression", sizeof(rcomp.type));
if (nla_put(skb, CRYPTOCFGA_REPORT_COMPRESS,
sizeof(struct crypto_report_comp), &rcomp))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
| 168,966 |
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 parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c,
int class_index, int *methods, int *sym_count) {
struct r_bin_t *rbin = binfile->rbin;
char *class_name;
int z;
const ut8 *p, *p_end;
if (!c) {
return;
}
class_name = dex_class_name (bin, c);
class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func
if (!class_name || !*class_name) {
return;
}
RBinClass *cls = R_NEW0 (RBinClass);
if (!cls) {
return;
}
cls->name = class_name;
cls->index = class_index;
cls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE;
cls->methods = r_list_new ();
if (!cls->methods) {
free (cls);
return;
}
cls->fields = r_list_new ();
if (!cls->fields) {
r_list_free (cls->methods);
free (cls);
return;
}
r_list_append (bin->classes_list, cls);
if (dexdump) {
rbin->cb_printf (" Class descriptor : '%s;'\n", class_name);
rbin->cb_printf (
" Access flags : 0x%04x (%s)\n", c->access_flags,
createAccessFlagStr (c->access_flags, kAccessForClass));
rbin->cb_printf (" Superclass : '%s'\n",
dex_class_super_name (bin, c));
rbin->cb_printf (" Interfaces -\n");
}
if (c->interfaces_offset > 0 &&
bin->header.data_offset < c->interfaces_offset &&
c->interfaces_offset <
bin->header.data_offset + bin->header.data_size) {
p = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL);
int types_list_size = r_read_le32(p);
if (types_list_size < 0 || types_list_size >= bin->header.types_size ) {
return;
}
for (z = 0; z < types_list_size; z++) {
int t = r_read_le16 (p + 4 + z * 2);
if (t > 0 && t < bin->header.types_size ) {
int tid = bin->types[t].descriptor_id;
if (dexdump) {
rbin->cb_printf (
" #%d : '%s'\n",
z, getstr (bin, tid));
}
}
}
}
if (!c || !c->class_data_offset) {
if (dexdump) {
rbin->cb_printf (
" Static fields -\n Instance fields "
"-\n Direct methods -\n Virtual methods "
"-\n");
}
} else {
if (bin->header.class_offset > c->class_data_offset ||
c->class_data_offset <
bin->header.class_offset +
bin->header.class_size * DEX_CLASS_SIZE) {
return;
}
p = r_buf_get_at (binfile->buf, c->class_data_offset, NULL);
p_end = p + binfile->buf->length - c->class_data_offset;
c->class_data = (struct dex_class_data_item_t *)malloc (
sizeof (struct dex_class_data_item_t));
p = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size);
p = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size);
p = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size);
p = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size);
if (dexdump) {
rbin->cb_printf (" Static fields -\n");
}
p = parse_dex_class_fields (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->static_fields_size, true);
if (dexdump) {
rbin->cb_printf (" Instance fields -\n");
}
p = parse_dex_class_fields (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->instance_fields_size, false);
if (dexdump) {
rbin->cb_printf (" Direct methods -\n");
}
p = parse_dex_class_method (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->direct_methods_size, methods, true);
if (dexdump) {
rbin->cb_printf (" Virtual methods -\n");
}
p = parse_dex_class_method (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->virtual_methods_size, methods, false);
}
if (dexdump) {
char *source_file = getstr (bin, c->source_file);
if (!source_file) {
rbin->cb_printf (
" source_file_idx : %d (unknown)\n\n",
c->source_file);
} else {
rbin->cb_printf (" source_file_idx : %d (%s)\n\n",
c->source_file, source_file);
}
}
}
Commit Message: Fix #6816 - null deref in r_read_*
CWE ID: CWE-476 | static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c,
int class_index, int *methods, int *sym_count) {
struct r_bin_t *rbin = binfile->rbin;
char *class_name;
int z;
const ut8 *p, *p_end;
if (!c) {
return;
}
class_name = dex_class_name (bin, c);
class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func
if (!class_name || !*class_name) {
return;
}
RBinClass *cls = R_NEW0 (RBinClass);
if (!cls) {
return;
}
cls->name = class_name;
cls->index = class_index;
cls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE;
cls->methods = r_list_new ();
if (!cls->methods) {
free (cls);
return;
}
cls->fields = r_list_new ();
if (!cls->fields) {
r_list_free (cls->methods);
free (cls);
return;
}
r_list_append (bin->classes_list, cls);
if (dexdump) {
rbin->cb_printf (" Class descriptor : '%s;'\n", class_name);
rbin->cb_printf (
" Access flags : 0x%04x (%s)\n", c->access_flags,
createAccessFlagStr (c->access_flags, kAccessForClass));
rbin->cb_printf (" Superclass : '%s'\n",
dex_class_super_name (bin, c));
rbin->cb_printf (" Interfaces -\n");
}
if (c->interfaces_offset > 0 &&
bin->header.data_offset < c->interfaces_offset &&
c->interfaces_offset <
bin->header.data_offset + bin->header.data_size) {
p = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL);
int types_list_size = r_read_le32 (p);
if (types_list_size < 0 || types_list_size >= bin->header.types_size ) {
return;
}
for (z = 0; z < types_list_size; z++) {
int t = r_read_le16 (p + 4 + z * 2);
if (t > 0 && t < bin->header.types_size ) {
int tid = bin->types[t].descriptor_id;
if (dexdump) {
rbin->cb_printf (
" #%d : '%s'\n",
z, getstr (bin, tid));
}
}
}
}
if (!c || !c->class_data_offset) {
if (dexdump) {
rbin->cb_printf (
" Static fields -\n Instance fields "
"-\n Direct methods -\n Virtual methods "
"-\n");
}
} else {
if (bin->header.class_offset > c->class_data_offset ||
c->class_data_offset <
bin->header.class_offset +
bin->header.class_size * DEX_CLASS_SIZE) {
return;
}
p = r_buf_get_at (binfile->buf, c->class_data_offset, NULL);
p_end = p + binfile->buf->length - c->class_data_offset;
c->class_data = (struct dex_class_data_item_t *)malloc (
sizeof (struct dex_class_data_item_t));
p = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size);
p = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size);
p = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size);
p = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size);
if (dexdump) {
rbin->cb_printf (" Static fields -\n");
}
p = parse_dex_class_fields (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->static_fields_size, true);
if (dexdump) {
rbin->cb_printf (" Instance fields -\n");
}
p = parse_dex_class_fields (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->instance_fields_size, false);
if (dexdump) {
rbin->cb_printf (" Direct methods -\n");
}
p = parse_dex_class_method (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->direct_methods_size, methods, true);
if (dexdump) {
rbin->cb_printf (" Virtual methods -\n");
}
p = parse_dex_class_method (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->virtual_methods_size, methods, false);
}
if (dexdump) {
char *source_file = getstr (bin, c->source_file);
if (!source_file) {
rbin->cb_printf (
" source_file_idx : %d (unknown)\n\n",
c->source_file);
} else {
rbin->cb_printf (" source_file_idx : %d (%s)\n\n",
c->source_file, source_file);
}
}
}
| 168,362 |
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 red_channel_pipes_add_empty_msg(RedChannel *channel, int msg_type)
{
RingItem *link;
RING_FOREACH(link, &channel->clients) {
red_channel_client_pipe_add_empty_msg(
SPICE_CONTAINEROF(link, RedChannelClient, channel_link),
msg_type);
}
}
Commit Message:
CWE ID: CWE-399 | void red_channel_pipes_add_empty_msg(RedChannel *channel, int msg_type)
{
RingItem *link, *next;
RING_FOREACH_SAFE(link, next, &channel->clients) {
red_channel_client_pipe_add_empty_msg(
SPICE_CONTAINEROF(link, RedChannelClient, channel_link),
msg_type);
}
}
| 164,663 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: resp_get_length(netdissect_options *ndo, register const u_char *bp, int len, const u_char **endp)
{
int result;
u_char c;
int saw_digit;
int neg;
int too_large;
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
too_large = 0;
neg = 0;
if (*bp == '-') {
neg = 1;
bp++;
len--;
}
result = 0;
saw_digit = 0;
for (;;) {
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
c = *bp;
if (!(c >= '0' && c <= '9')) {
if (!saw_digit)
goto invalid;
break;
}
c -= '0';
if (result > (INT_MAX / 10)) {
/* This will overflow an int when we multiply it by 10. */
too_large = 1;
} else {
result *= 10;
if (result == INT_MAX && c > (INT_MAX % 10)) {
/* This will overflow an int when we add c */
too_large = 1;
} else
result += c;
}
bp++;
len--;
saw_digit = 1;
}
if (!saw_digit)
goto invalid;
/*
* OK, the next thing should be \r\n.
*/
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
if (*bp != '\r')
goto invalid;
bp++;
len--;
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
if (*bp != '\n')
goto invalid;
bp++;
len--;
*endp = bp;
if (neg) {
/* -1 means "null", anything else is invalid */
if (too_large || result != 1)
return (-4);
result = -1;
}
return (too_large ? -3 : result);
trunc:
return (-2);
invalid:
return (-5);
}
Commit Message: CVE-2017-12989/RESP: Make sure resp_get_length() advances the pointer for invalid lengths.
Make sure that it always sends *endp before returning and that, for
invalid lengths where we don't like a character in the length string,
what it sets *endp to is past the character in question, so we don't
run the risk of infinitely looping (or doing something else random) if a
character in the length is invalid.
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 | resp_get_length(netdissect_options *ndo, register const u_char *bp, int len, const u_char **endp)
{
int result;
u_char c;
int saw_digit;
int neg;
int too_large;
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
too_large = 0;
neg = 0;
if (*bp == '-') {
neg = 1;
bp++;
len--;
}
result = 0;
saw_digit = 0;
for (;;) {
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
c = *bp;
if (!(c >= '0' && c <= '9')) {
if (!saw_digit) {
bp++;
goto invalid;
}
break;
}
c -= '0';
if (result > (INT_MAX / 10)) {
/* This will overflow an int when we multiply it by 10. */
too_large = 1;
} else {
result *= 10;
if (result == INT_MAX && c > (INT_MAX % 10)) {
/* This will overflow an int when we add c */
too_large = 1;
} else
result += c;
}
bp++;
len--;
saw_digit = 1;
}
if (!saw_digit)
goto invalid;
/*
* OK, the next thing should be \r\n.
*/
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
if (*bp != '\r') {
bp++;
goto invalid;
}
bp++;
len--;
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
if (*bp != '\n') {
bp++;
goto invalid;
}
bp++;
len--;
*endp = bp;
if (neg) {
/* -1 means "null", anything else is invalid */
if (too_large || result != 1)
return (-4);
result = -1;
}
return (too_large ? -3 : result);
trunc:
*endp = bp;
return (-2);
invalid:
*endp = bp;
return (-5);
}
| 167,928 |
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 dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len)
{
int rlen, remain;
dpIOCtxPtr dctx;
dynamicPtr *dp;
dctx = (dpIOCtxPtr) ctx;
dp = dctx->dp;
remain = dp->logicalSize - dp->pos;
if(remain >= len) {
rlen = len;
} else {
if(remain <= 0) {
/* 2.0.34: EOF is incorrect. We use 0 for
* errors and EOF, just like fileGetbuf,
* which is a simple fread() wrapper.
* TBB. Original bug report: Daniel Cowgill. */
return 0; /* NOT EOF */
}
rlen = remain;
}
memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen);
dp->pos += rlen;
return rlen;
}
Commit Message: Fix invalid read in gdImageCreateFromTiffPtr()
tiff_invalid_read.tiff is corrupt, and causes an invalid read in
gdImageCreateFromTiffPtr(), but not in gdImageCreateFromTiff(). The culprit
is dynamicGetbuf(), which doesn't check for out-of-bound reads. In this case,
dynamicGetbuf() is called with a negative dp->pos, but also positive buffer
overflows have to be handled, in which case 0 has to be returned (cf. commit
75e29a9).
Fixing dynamicGetbuf() exhibits that the corrupt TIFF would still create
the image, because the return value of TIFFReadRGBAImage() is not checked.
We do that, and let createFromTiffRgba() fail if TIFFReadRGBAImage() fails.
This issue had been reported by Ibrahim El-Sayed to [email protected].
CVE-2016-6911
CWE ID: CWE-125 | static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len)
{
int rlen, remain;
dpIOCtxPtr dctx;
dynamicPtr *dp;
dctx = (dpIOCtxPtr) ctx;
dp = dctx->dp;
if (dp->pos < 0 || dp->pos >= dp->realSize) {
return 0;
}
remain = dp->logicalSize - dp->pos;
if(remain >= len) {
rlen = len;
} else {
if(remain <= 0) {
return 0;
}
rlen = remain;
}
if (dp->pos + rlen > dp->realSize) {
rlen = dp->realSize - dp->pos;
}
memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen);
dp->pos += rlen;
return rlen;
}
| 168,821 |
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: IV_API_CALL_STATUS_T impeg2d_api_entity(iv_obj_t *ps_dechdl,
void *pv_api_ip,
void *pv_api_op)
{
iv_obj_t *ps_dec_handle;
dec_state_t *ps_dec_state;
dec_state_multi_core_t *ps_dec_state_multi_core;
impeg2d_video_decode_ip_t *ps_dec_ip;
impeg2d_video_decode_op_t *ps_dec_op;
WORD32 bytes_remaining;
pic_buf_t *ps_disp_pic;
ps_dec_ip = (impeg2d_video_decode_ip_t *)pv_api_ip;
ps_dec_op = (impeg2d_video_decode_op_t *)pv_api_op;
memset(ps_dec_op,0,sizeof(impeg2d_video_decode_op_t));
ps_dec_op->s_ivd_video_decode_op_t.u4_size = sizeof(impeg2d_video_decode_op_t);
ps_dec_op->s_ivd_video_decode_op_t.u4_output_present = 0;
bytes_remaining = ps_dec_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
ps_dec_handle = (iv_obj_t *)ps_dechdl;
if(ps_dechdl == NULL)
{
return(IV_FAIL);
}
ps_dec_state_multi_core = ps_dec_handle->pv_codec_handle;
ps_dec_state = ps_dec_state_multi_core->ps_dec_state[0];
ps_dec_state->ps_disp_frm_buf = &(ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf);
if(0 == ps_dec_state->u4_share_disp_buf)
{
ps_dec_state->ps_disp_frm_buf->pv_y_buf = ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[0];
ps_dec_state->ps_disp_frm_buf->pv_u_buf = ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[1];
ps_dec_state->ps_disp_frm_buf->pv_v_buf = ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[2];
}
ps_dec_state->ps_disp_pic = NULL;
ps_dec_state->i4_frame_decoded = 0;
/*rest bytes consumed */
ps_dec_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = 0;
ps_dec_op->s_ivd_video_decode_op_t.u4_error_code = IV_SUCCESS;
if((ps_dec_ip->s_ivd_video_decode_ip_t.pv_stream_buffer == NULL)&&(ps_dec_state->u1_flushfrm==0))
{
ps_dec_op->s_ivd_video_decode_op_t.u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->s_ivd_video_decode_op_t.u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL;
return IV_FAIL;
}
if (ps_dec_state->u4_num_frames_decoded > NUM_FRAMES_LIMIT)
{
ps_dec_op->s_ivd_video_decode_op_t.u4_error_code = IMPEG2D_SAMPLE_VERSION_LIMIT_ERR;
return(IV_FAIL);
}
if(((0 == ps_dec_state->u2_header_done) || (ps_dec_state->u2_decode_header == 1)) && (ps_dec_state->u1_flushfrm == 0))
{
impeg2d_dec_hdr(ps_dec_state,ps_dec_ip ,ps_dec_op);
bytes_remaining -= ps_dec_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed;
}
if((1 != ps_dec_state->u2_decode_header) && ((bytes_remaining > 0) || ps_dec_state->u1_flushfrm))
{
if(ps_dec_state->u1_flushfrm)
{
if(ps_dec_state->aps_ref_pics[1] != NULL)
{
impeg2_disp_mgr_add(&ps_dec_state->s_disp_mgr, ps_dec_state->aps_ref_pics[1], ps_dec_state->aps_ref_pics[1]->i4_buf_id);
impeg2_buf_mgr_release(ps_dec_state->pv_pic_buf_mg, ps_dec_state->aps_ref_pics[1]->i4_buf_id, BUF_MGR_REF);
impeg2_buf_mgr_release(ps_dec_state->pv_pic_buf_mg, ps_dec_state->aps_ref_pics[0]->i4_buf_id, BUF_MGR_REF);
ps_dec_state->aps_ref_pics[1] = NULL;
ps_dec_state->aps_ref_pics[0] = NULL;
}
else if(ps_dec_state->aps_ref_pics[0] != NULL)
{
impeg2_disp_mgr_add(&ps_dec_state->s_disp_mgr, ps_dec_state->aps_ref_pics[0], ps_dec_state->aps_ref_pics[0]->i4_buf_id);
impeg2_buf_mgr_release(ps_dec_state->pv_pic_buf_mg, ps_dec_state->aps_ref_pics[0]->i4_buf_id, BUF_MGR_REF);
ps_dec_state->aps_ref_pics[0] = NULL;
}
ps_dec_ip->s_ivd_video_decode_ip_t.u4_size = sizeof(impeg2d_video_decode_ip_t);
ps_dec_op->s_ivd_video_decode_op_t.u4_size = sizeof(impeg2d_video_decode_op_t);
ps_disp_pic = impeg2_disp_mgr_get(&ps_dec_state->s_disp_mgr, &ps_dec_state->i4_disp_buf_id);
ps_dec_state->ps_disp_pic = ps_disp_pic;
if(ps_disp_pic == NULL)
{
ps_dec_op->s_ivd_video_decode_op_t.u4_output_present = 0;
}
else
{
WORD32 fmt_conv;
if(0 == ps_dec_state->u4_share_disp_buf)
{
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.pv_y_buf = ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[0];
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.pv_u_buf = ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[1];
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.pv_v_buf = ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[2];
fmt_conv = 1;
}
else
{
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.pv_y_buf = ps_disp_pic->pu1_y;
if(IV_YUV_420P == ps_dec_state->i4_chromaFormat)
{
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.pv_u_buf = ps_disp_pic->pu1_u;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.pv_v_buf = ps_disp_pic->pu1_v;
fmt_conv = 0;
}
else
{
UWORD8 *pu1_buf;
pu1_buf = ps_dec_state->as_disp_buffers[ps_disp_pic->i4_buf_id].pu1_bufs[1];
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.pv_u_buf = pu1_buf;
pu1_buf = ps_dec_state->as_disp_buffers[ps_disp_pic->i4_buf_id].pu1_bufs[2];
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.pv_v_buf = pu1_buf;
fmt_conv = 1;
}
}
if(fmt_conv == 1)
{
iv_yuv_buf_t *ps_dst;
ps_dst = &(ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf);
if(ps_dec_state->u4_deinterlace && (0 == ps_dec_state->u2_progressive_frame))
{
impeg2d_deinterlace(ps_dec_state,
ps_disp_pic,
ps_dst,
0,
ps_dec_state->u2_vertical_size);
}
else
{
impeg2d_format_convert(ps_dec_state,
ps_disp_pic,
ps_dst,
0,
ps_dec_state->u2_vertical_size);
}
}
if(ps_dec_state->u4_deinterlace)
{
if(ps_dec_state->ps_deint_pic)
{
impeg2_buf_mgr_release(ps_dec_state->pv_pic_buf_mg,
ps_dec_state->ps_deint_pic->i4_buf_id,
MPEG2_BUF_MGR_DEINT);
}
ps_dec_state->ps_deint_pic = ps_disp_pic;
}
if(0 == ps_dec_state->u4_share_disp_buf)
impeg2_buf_mgr_release(ps_dec_state->pv_pic_buf_mg, ps_disp_pic->i4_buf_id, BUF_MGR_DISP);
ps_dec_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec_state->u2_vertical_size;
ps_dec_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec_state->u2_horizontal_size;
ps_dec_op->s_ivd_video_decode_op_t.u4_output_present = 1;
ps_dec_op->s_ivd_video_decode_op_t.u4_disp_buf_id = ps_disp_pic->i4_buf_id;
ps_dec_op->s_ivd_video_decode_op_t.u4_ts = ps_disp_pic->u4_ts;
ps_dec_op->s_ivd_video_decode_op_t.e_output_format = (IV_COLOR_FORMAT_T)ps_dec_state->i4_chromaFormat;
ps_dec_op->s_ivd_video_decode_op_t.u4_is_ref_flag = (B_PIC != ps_dec_state->e_pic_type);
ps_dec_op->s_ivd_video_decode_op_t.u4_progressive_frame_flag = IV_PROGRESSIVE;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_y_wd = ps_dec_state->u2_horizontal_size;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_y_strd = ps_dec_state->u4_frm_buf_stride;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_y_ht = ps_dec_state->u2_vertical_size;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_wd = ps_dec_state->u2_horizontal_size >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_strd = ps_dec_state->u4_frm_buf_stride >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_ht = ps_dec_state->u2_vertical_size >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_wd = ps_dec_state->u2_horizontal_size >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_strd = ps_dec_state->u4_frm_buf_stride >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_ht = ps_dec_state->u2_vertical_size >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_size = sizeof(ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf);
switch(ps_dec_state->i4_chromaFormat)
{
case IV_YUV_420SP_UV:
case IV_YUV_420SP_VU:
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_wd = ps_dec_state->u2_horizontal_size;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_strd = ps_dec_state->u4_frm_buf_stride;
break;
case IV_YUV_422ILE:
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_wd = 0;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_ht = 0;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_wd = 0;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_ht = 0;
break;
default:
break;
}
}
if(ps_dec_op->s_ivd_video_decode_op_t.u4_output_present)
{
if(1 == ps_dec_op->s_ivd_video_decode_op_t.u4_output_present)
{
INSERT_LOGO(ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[0],
ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[1],
ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[2],
ps_dec_state->u4_frm_buf_stride,
ps_dec_state->u2_horizontal_size,
ps_dec_state->u2_vertical_size,
ps_dec_state->i4_chromaFormat,
ps_dec_state->u2_horizontal_size,
ps_dec_state->u2_vertical_size);
}
return(IV_SUCCESS);
}
else
{
ps_dec_state->u1_flushfrm = 0;
return(IV_FAIL);
}
}
else if(ps_dec_state->u1_flushfrm==0)
{
ps_dec_ip->s_ivd_video_decode_ip_t.u4_size = sizeof(impeg2d_video_decode_ip_t);
ps_dec_op->s_ivd_video_decode_op_t.u4_size = sizeof(impeg2d_video_decode_op_t);
if(ps_dec_ip->s_ivd_video_decode_ip_t.u4_num_Bytes < 4)
{
ps_dec_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_dec_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
return(IV_FAIL);
}
if(1 == ps_dec_state->u4_share_disp_buf)
{
if(0 == impeg2_buf_mgr_check_free(ps_dec_state->pv_pic_buf_mg))
{
ps_dec_op->s_ivd_video_decode_op_t.u4_error_code =
(IMPEG2D_ERROR_CODES_T)IVD_DEC_REF_BUF_NULL;
return IV_FAIL;
}
}
ps_dec_op->s_ivd_video_decode_op_t.e_output_format = (IV_COLOR_FORMAT_T)ps_dec_state->i4_chromaFormat;
ps_dec_op->s_ivd_video_decode_op_t.u4_is_ref_flag = (B_PIC != ps_dec_state->e_pic_type);
ps_dec_op->s_ivd_video_decode_op_t.u4_progressive_frame_flag = IV_PROGRESSIVE;
if (0 == ps_dec_state->u4_frm_buf_stride)
{
ps_dec_state->u4_frm_buf_stride = (ps_dec_state->u2_horizontal_size);
}
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_y_wd = ps_dec_state->u2_horizontal_size;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_y_strd = ps_dec_state->u4_frm_buf_stride;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_y_ht = ps_dec_state->u2_vertical_size;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_wd = ps_dec_state->u2_horizontal_size >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_strd = ps_dec_state->u4_frm_buf_stride >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_ht = ps_dec_state->u2_vertical_size >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_wd = ps_dec_state->u2_horizontal_size >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_strd = ps_dec_state->u4_frm_buf_stride >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_ht = ps_dec_state->u2_vertical_size >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_size = sizeof(ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf);
switch(ps_dec_state->i4_chromaFormat)
{
case IV_YUV_420SP_UV:
case IV_YUV_420SP_VU:
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_wd = ps_dec_state->u2_horizontal_size;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_strd = ps_dec_state->u4_frm_buf_stride;
break;
case IV_YUV_422ILE:
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_wd = 0;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_ht = 0;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_wd = 0;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_ht = 0;
break;
default:
break;
}
if( ps_dec_state->u1_flushfrm == 0)
{
ps_dec_state->u1_flushcnt = 0;
/*************************************************************************/
/* Frame Decode */
/*************************************************************************/
impeg2d_dec_frm(ps_dec_state,ps_dec_ip,ps_dec_op);
if (IVD_ERROR_NONE ==
ps_dec_op->s_ivd_video_decode_op_t.u4_error_code)
{
if(ps_dec_state->u1_first_frame_done == 0)
{
ps_dec_state->u1_first_frame_done = 1;
}
if(ps_dec_state->ps_disp_pic)
{
ps_dec_op->s_ivd_video_decode_op_t.u4_output_present = 1;
switch(ps_dec_state->ps_disp_pic->e_pic_type)
{
case I_PIC :
ps_dec_op->s_ivd_video_decode_op_t.e_pic_type = IV_I_FRAME;
break;
case P_PIC:
ps_dec_op->s_ivd_video_decode_op_t.e_pic_type = IV_P_FRAME;
break;
case B_PIC:
ps_dec_op->s_ivd_video_decode_op_t.e_pic_type = IV_B_FRAME;
break;
case D_PIC:
ps_dec_op->s_ivd_video_decode_op_t.e_pic_type = IV_I_FRAME;
break;
default :
ps_dec_op->s_ivd_video_decode_op_t.e_pic_type = IV_FRAMETYPE_DEFAULT;
break;
}
}
else
{
ps_dec_op->s_ivd_video_decode_op_t.u4_output_present = 0;
ps_dec_op->s_ivd_video_decode_op_t.e_pic_type = IV_NA_FRAME;
}
ps_dec_state->u4_num_frames_decoded++;
}
}
else
{
ps_dec_state->u1_flushcnt++;
}
}
if(ps_dec_state->ps_disp_pic)
{
ps_dec_op->s_ivd_video_decode_op_t.u4_disp_buf_id = ps_dec_state->ps_disp_pic->i4_buf_id;
ps_dec_op->s_ivd_video_decode_op_t.u4_ts = ps_dec_state->ps_disp_pic->u4_ts;
if(0 == ps_dec_state->u4_share_disp_buf)
{
impeg2_buf_mgr_release(ps_dec_state->pv_pic_buf_mg, ps_dec_state->ps_disp_pic->i4_buf_id, BUF_MGR_DISP);
}
}
if(ps_dec_state->u4_deinterlace)
{
if(ps_dec_state->ps_deint_pic)
{
impeg2_buf_mgr_release(ps_dec_state->pv_pic_buf_mg,
ps_dec_state->ps_deint_pic->i4_buf_id,
MPEG2_BUF_MGR_DEINT);
}
ps_dec_state->ps_deint_pic = ps_dec_state->ps_disp_pic;
}
if(1 == ps_dec_op->s_ivd_video_decode_op_t.u4_output_present)
{
INSERT_LOGO(ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[0],
ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[1],
ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[2],
ps_dec_state->u4_frm_buf_stride,
ps_dec_state->u2_horizontal_size,
ps_dec_state->u2_vertical_size,
ps_dec_state->i4_chromaFormat,
ps_dec_state->u2_horizontal_size,
ps_dec_state->u2_vertical_size);
}
}
ps_dec_op->s_ivd_video_decode_op_t.u4_progressive_frame_flag = 1;
ps_dec_op->s_ivd_video_decode_op_t.e4_fld_type = ps_dec_state->s_disp_op.e4_fld_type;
if(ps_dec_op->s_ivd_video_decode_op_t.u4_error_code)
return IV_FAIL;
else
return IV_SUCCESS;
}
Commit Message: Fix in handling header decode errors
If header decode was unsuccessful, do not try decoding a frame
Also, initialize pic_wd, pic_ht for reinitialization when
decoder is created with smaller dimensions
Bug: 28886651
Bug: 35219737
Change-Id: I8c06d9052910e47fce2e6fe25ad318d4c83d2c50
(cherry picked from commit 2b9fa9ace2dbedfbac026fc9b6ab6cdac7f68c27)
(cherry picked from commit c2395cd7cc0c286a66de674032dd2ed26500aef4)
CWE ID: CWE-119 | IV_API_CALL_STATUS_T impeg2d_api_entity(iv_obj_t *ps_dechdl,
void *pv_api_ip,
void *pv_api_op)
{
iv_obj_t *ps_dec_handle;
dec_state_t *ps_dec_state;
dec_state_multi_core_t *ps_dec_state_multi_core;
impeg2d_video_decode_ip_t *ps_dec_ip;
impeg2d_video_decode_op_t *ps_dec_op;
WORD32 bytes_remaining;
pic_buf_t *ps_disp_pic;
ps_dec_ip = (impeg2d_video_decode_ip_t *)pv_api_ip;
ps_dec_op = (impeg2d_video_decode_op_t *)pv_api_op;
memset(ps_dec_op,0,sizeof(impeg2d_video_decode_op_t));
ps_dec_op->s_ivd_video_decode_op_t.u4_size = sizeof(impeg2d_video_decode_op_t);
ps_dec_op->s_ivd_video_decode_op_t.u4_output_present = 0;
bytes_remaining = ps_dec_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
ps_dec_handle = (iv_obj_t *)ps_dechdl;
if(ps_dechdl == NULL)
{
return(IV_FAIL);
}
ps_dec_state_multi_core = ps_dec_handle->pv_codec_handle;
ps_dec_state = ps_dec_state_multi_core->ps_dec_state[0];
ps_dec_state->ps_disp_frm_buf = &(ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf);
if(0 == ps_dec_state->u4_share_disp_buf)
{
ps_dec_state->ps_disp_frm_buf->pv_y_buf = ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[0];
ps_dec_state->ps_disp_frm_buf->pv_u_buf = ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[1];
ps_dec_state->ps_disp_frm_buf->pv_v_buf = ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[2];
}
ps_dec_state->ps_disp_pic = NULL;
ps_dec_state->i4_frame_decoded = 0;
/*rest bytes consumed */
ps_dec_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = 0;
ps_dec_op->s_ivd_video_decode_op_t.u4_error_code = IV_SUCCESS;
if((ps_dec_ip->s_ivd_video_decode_ip_t.pv_stream_buffer == NULL)&&(ps_dec_state->u1_flushfrm==0))
{
ps_dec_op->s_ivd_video_decode_op_t.u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM;
ps_dec_op->s_ivd_video_decode_op_t.u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL;
return IV_FAIL;
}
if (ps_dec_state->u4_num_frames_decoded > NUM_FRAMES_LIMIT)
{
ps_dec_op->s_ivd_video_decode_op_t.u4_error_code = IMPEG2D_SAMPLE_VERSION_LIMIT_ERR;
return(IV_FAIL);
}
if(((0 == ps_dec_state->u2_header_done) || (ps_dec_state->u2_decode_header == 1)) && (ps_dec_state->u1_flushfrm == 0))
{
impeg2d_dec_hdr(ps_dec_state,ps_dec_ip ,ps_dec_op);
bytes_remaining -= ps_dec_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed;
}
if((1 != ps_dec_state->u2_decode_header) &&
(((bytes_remaining > 0) && (1 == ps_dec_state->u2_header_done)) || ps_dec_state->u1_flushfrm))
{
if(ps_dec_state->u1_flushfrm)
{
if(ps_dec_state->aps_ref_pics[1] != NULL)
{
impeg2_disp_mgr_add(&ps_dec_state->s_disp_mgr, ps_dec_state->aps_ref_pics[1], ps_dec_state->aps_ref_pics[1]->i4_buf_id);
impeg2_buf_mgr_release(ps_dec_state->pv_pic_buf_mg, ps_dec_state->aps_ref_pics[1]->i4_buf_id, BUF_MGR_REF);
impeg2_buf_mgr_release(ps_dec_state->pv_pic_buf_mg, ps_dec_state->aps_ref_pics[0]->i4_buf_id, BUF_MGR_REF);
ps_dec_state->aps_ref_pics[1] = NULL;
ps_dec_state->aps_ref_pics[0] = NULL;
}
else if(ps_dec_state->aps_ref_pics[0] != NULL)
{
impeg2_disp_mgr_add(&ps_dec_state->s_disp_mgr, ps_dec_state->aps_ref_pics[0], ps_dec_state->aps_ref_pics[0]->i4_buf_id);
impeg2_buf_mgr_release(ps_dec_state->pv_pic_buf_mg, ps_dec_state->aps_ref_pics[0]->i4_buf_id, BUF_MGR_REF);
ps_dec_state->aps_ref_pics[0] = NULL;
}
ps_dec_ip->s_ivd_video_decode_ip_t.u4_size = sizeof(impeg2d_video_decode_ip_t);
ps_dec_op->s_ivd_video_decode_op_t.u4_size = sizeof(impeg2d_video_decode_op_t);
ps_disp_pic = impeg2_disp_mgr_get(&ps_dec_state->s_disp_mgr, &ps_dec_state->i4_disp_buf_id);
ps_dec_state->ps_disp_pic = ps_disp_pic;
if(ps_disp_pic == NULL)
{
ps_dec_op->s_ivd_video_decode_op_t.u4_output_present = 0;
}
else
{
WORD32 fmt_conv;
if(0 == ps_dec_state->u4_share_disp_buf)
{
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.pv_y_buf = ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[0];
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.pv_u_buf = ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[1];
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.pv_v_buf = ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[2];
fmt_conv = 1;
}
else
{
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.pv_y_buf = ps_disp_pic->pu1_y;
if(IV_YUV_420P == ps_dec_state->i4_chromaFormat)
{
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.pv_u_buf = ps_disp_pic->pu1_u;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.pv_v_buf = ps_disp_pic->pu1_v;
fmt_conv = 0;
}
else
{
UWORD8 *pu1_buf;
pu1_buf = ps_dec_state->as_disp_buffers[ps_disp_pic->i4_buf_id].pu1_bufs[1];
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.pv_u_buf = pu1_buf;
pu1_buf = ps_dec_state->as_disp_buffers[ps_disp_pic->i4_buf_id].pu1_bufs[2];
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.pv_v_buf = pu1_buf;
fmt_conv = 1;
}
}
if(fmt_conv == 1)
{
iv_yuv_buf_t *ps_dst;
ps_dst = &(ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf);
if(ps_dec_state->u4_deinterlace && (0 == ps_dec_state->u2_progressive_frame))
{
impeg2d_deinterlace(ps_dec_state,
ps_disp_pic,
ps_dst,
0,
ps_dec_state->u2_vertical_size);
}
else
{
impeg2d_format_convert(ps_dec_state,
ps_disp_pic,
ps_dst,
0,
ps_dec_state->u2_vertical_size);
}
}
if(ps_dec_state->u4_deinterlace)
{
if(ps_dec_state->ps_deint_pic)
{
impeg2_buf_mgr_release(ps_dec_state->pv_pic_buf_mg,
ps_dec_state->ps_deint_pic->i4_buf_id,
MPEG2_BUF_MGR_DEINT);
}
ps_dec_state->ps_deint_pic = ps_disp_pic;
}
if(0 == ps_dec_state->u4_share_disp_buf)
impeg2_buf_mgr_release(ps_dec_state->pv_pic_buf_mg, ps_disp_pic->i4_buf_id, BUF_MGR_DISP);
ps_dec_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec_state->u2_vertical_size;
ps_dec_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec_state->u2_horizontal_size;
ps_dec_op->s_ivd_video_decode_op_t.u4_output_present = 1;
ps_dec_op->s_ivd_video_decode_op_t.u4_disp_buf_id = ps_disp_pic->i4_buf_id;
ps_dec_op->s_ivd_video_decode_op_t.u4_ts = ps_disp_pic->u4_ts;
ps_dec_op->s_ivd_video_decode_op_t.e_output_format = (IV_COLOR_FORMAT_T)ps_dec_state->i4_chromaFormat;
ps_dec_op->s_ivd_video_decode_op_t.u4_is_ref_flag = (B_PIC != ps_dec_state->e_pic_type);
ps_dec_op->s_ivd_video_decode_op_t.u4_progressive_frame_flag = IV_PROGRESSIVE;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_y_wd = ps_dec_state->u2_horizontal_size;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_y_strd = ps_dec_state->u4_frm_buf_stride;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_y_ht = ps_dec_state->u2_vertical_size;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_wd = ps_dec_state->u2_horizontal_size >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_strd = ps_dec_state->u4_frm_buf_stride >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_ht = ps_dec_state->u2_vertical_size >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_wd = ps_dec_state->u2_horizontal_size >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_strd = ps_dec_state->u4_frm_buf_stride >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_ht = ps_dec_state->u2_vertical_size >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_size = sizeof(ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf);
switch(ps_dec_state->i4_chromaFormat)
{
case IV_YUV_420SP_UV:
case IV_YUV_420SP_VU:
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_wd = ps_dec_state->u2_horizontal_size;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_strd = ps_dec_state->u4_frm_buf_stride;
break;
case IV_YUV_422ILE:
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_wd = 0;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_ht = 0;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_wd = 0;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_ht = 0;
break;
default:
break;
}
}
if(ps_dec_op->s_ivd_video_decode_op_t.u4_output_present)
{
if(1 == ps_dec_op->s_ivd_video_decode_op_t.u4_output_present)
{
INSERT_LOGO(ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[0],
ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[1],
ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[2],
ps_dec_state->u4_frm_buf_stride,
ps_dec_state->u2_horizontal_size,
ps_dec_state->u2_vertical_size,
ps_dec_state->i4_chromaFormat,
ps_dec_state->u2_horizontal_size,
ps_dec_state->u2_vertical_size);
}
return(IV_SUCCESS);
}
else
{
ps_dec_state->u1_flushfrm = 0;
return(IV_FAIL);
}
}
else if(ps_dec_state->u1_flushfrm==0)
{
ps_dec_ip->s_ivd_video_decode_ip_t.u4_size = sizeof(impeg2d_video_decode_ip_t);
ps_dec_op->s_ivd_video_decode_op_t.u4_size = sizeof(impeg2d_video_decode_op_t);
if(ps_dec_ip->s_ivd_video_decode_ip_t.u4_num_Bytes < 4)
{
ps_dec_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_dec_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
return(IV_FAIL);
}
if(1 == ps_dec_state->u4_share_disp_buf)
{
if(0 == impeg2_buf_mgr_check_free(ps_dec_state->pv_pic_buf_mg))
{
ps_dec_op->s_ivd_video_decode_op_t.u4_error_code =
(IMPEG2D_ERROR_CODES_T)IVD_DEC_REF_BUF_NULL;
return IV_FAIL;
}
}
ps_dec_op->s_ivd_video_decode_op_t.e_output_format = (IV_COLOR_FORMAT_T)ps_dec_state->i4_chromaFormat;
ps_dec_op->s_ivd_video_decode_op_t.u4_is_ref_flag = (B_PIC != ps_dec_state->e_pic_type);
ps_dec_op->s_ivd_video_decode_op_t.u4_progressive_frame_flag = IV_PROGRESSIVE;
if (0 == ps_dec_state->u4_frm_buf_stride)
{
ps_dec_state->u4_frm_buf_stride = (ps_dec_state->u2_horizontal_size);
}
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_y_wd = ps_dec_state->u2_horizontal_size;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_y_strd = ps_dec_state->u4_frm_buf_stride;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_y_ht = ps_dec_state->u2_vertical_size;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_wd = ps_dec_state->u2_horizontal_size >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_strd = ps_dec_state->u4_frm_buf_stride >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_ht = ps_dec_state->u2_vertical_size >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_wd = ps_dec_state->u2_horizontal_size >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_strd = ps_dec_state->u4_frm_buf_stride >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_ht = ps_dec_state->u2_vertical_size >> 1;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_size = sizeof(ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf);
switch(ps_dec_state->i4_chromaFormat)
{
case IV_YUV_420SP_UV:
case IV_YUV_420SP_VU:
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_wd = ps_dec_state->u2_horizontal_size;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_strd = ps_dec_state->u4_frm_buf_stride;
break;
case IV_YUV_422ILE:
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_wd = 0;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_u_ht = 0;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_wd = 0;
ps_dec_op->s_ivd_video_decode_op_t.s_disp_frm_buf.u4_v_ht = 0;
break;
default:
break;
}
if( ps_dec_state->u1_flushfrm == 0)
{
ps_dec_state->u1_flushcnt = 0;
/*************************************************************************/
/* Frame Decode */
/*************************************************************************/
impeg2d_dec_frm(ps_dec_state,ps_dec_ip,ps_dec_op);
if (IVD_ERROR_NONE ==
ps_dec_op->s_ivd_video_decode_op_t.u4_error_code)
{
if(ps_dec_state->u1_first_frame_done == 0)
{
ps_dec_state->u1_first_frame_done = 1;
}
if(ps_dec_state->ps_disp_pic)
{
ps_dec_op->s_ivd_video_decode_op_t.u4_output_present = 1;
switch(ps_dec_state->ps_disp_pic->e_pic_type)
{
case I_PIC :
ps_dec_op->s_ivd_video_decode_op_t.e_pic_type = IV_I_FRAME;
break;
case P_PIC:
ps_dec_op->s_ivd_video_decode_op_t.e_pic_type = IV_P_FRAME;
break;
case B_PIC:
ps_dec_op->s_ivd_video_decode_op_t.e_pic_type = IV_B_FRAME;
break;
case D_PIC:
ps_dec_op->s_ivd_video_decode_op_t.e_pic_type = IV_I_FRAME;
break;
default :
ps_dec_op->s_ivd_video_decode_op_t.e_pic_type = IV_FRAMETYPE_DEFAULT;
break;
}
}
else
{
ps_dec_op->s_ivd_video_decode_op_t.u4_output_present = 0;
ps_dec_op->s_ivd_video_decode_op_t.e_pic_type = IV_NA_FRAME;
}
ps_dec_state->u4_num_frames_decoded++;
}
}
else
{
ps_dec_state->u1_flushcnt++;
}
}
if(ps_dec_state->ps_disp_pic)
{
ps_dec_op->s_ivd_video_decode_op_t.u4_disp_buf_id = ps_dec_state->ps_disp_pic->i4_buf_id;
ps_dec_op->s_ivd_video_decode_op_t.u4_ts = ps_dec_state->ps_disp_pic->u4_ts;
if(0 == ps_dec_state->u4_share_disp_buf)
{
impeg2_buf_mgr_release(ps_dec_state->pv_pic_buf_mg, ps_dec_state->ps_disp_pic->i4_buf_id, BUF_MGR_DISP);
}
}
if(ps_dec_state->u4_deinterlace)
{
if(ps_dec_state->ps_deint_pic)
{
impeg2_buf_mgr_release(ps_dec_state->pv_pic_buf_mg,
ps_dec_state->ps_deint_pic->i4_buf_id,
MPEG2_BUF_MGR_DEINT);
}
ps_dec_state->ps_deint_pic = ps_dec_state->ps_disp_pic;
}
if(1 == ps_dec_op->s_ivd_video_decode_op_t.u4_output_present)
{
INSERT_LOGO(ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[0],
ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[1],
ps_dec_ip->s_ivd_video_decode_ip_t.s_out_buffer.pu1_bufs[2],
ps_dec_state->u4_frm_buf_stride,
ps_dec_state->u2_horizontal_size,
ps_dec_state->u2_vertical_size,
ps_dec_state->i4_chromaFormat,
ps_dec_state->u2_horizontal_size,
ps_dec_state->u2_vertical_size);
}
}
ps_dec_op->s_ivd_video_decode_op_t.u4_progressive_frame_flag = 1;
ps_dec_op->s_ivd_video_decode_op_t.e4_fld_type = ps_dec_state->s_disp_op.e4_fld_type;
if(ps_dec_op->s_ivd_video_decode_op_t.u4_error_code)
return IV_FAIL;
else
return IV_SUCCESS;
}
| 174,032 |
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 ipmi_si_mem_setup(struct si_sm_io *io)
{
unsigned long addr = io->addr_data;
int mapsize, idx;
if (!addr)
return -ENODEV;
io->io_cleanup = mem_cleanup;
/*
* Figure out the actual readb/readw/readl/etc routine to use based
* upon the register size.
*/
switch (io->regsize) {
case 1:
io->inputb = intf_mem_inb;
io->outputb = intf_mem_outb;
break;
case 2:
io->inputb = intf_mem_inw;
io->outputb = intf_mem_outw;
break;
case 4:
io->inputb = intf_mem_inl;
io->outputb = intf_mem_outl;
break;
#ifdef readq
case 8:
io->inputb = mem_inq;
io->outputb = mem_outq;
break;
#endif
default:
dev_warn(io->dev, "Invalid register size: %d\n",
io->regsize);
return -EINVAL;
}
/*
* Some BIOSes reserve disjoint memory regions in their ACPI
* tables. This causes problems when trying to request the
* entire region. Therefore we must request each register
* separately.
*/
for (idx = 0; idx < io->io_size; idx++) {
if (request_mem_region(addr + idx * io->regspacing,
io->regsize, DEVICE_NAME) == NULL) {
/* Undo allocations */
mem_region_cleanup(io, idx);
return -EIO;
}
}
/*
* Calculate the total amount of memory to claim. This is an
* unusual looking calculation, but it avoids claiming any
* more memory than it has to. It will claim everything
* between the first address to the end of the last full
* register.
*/
mapsize = ((io->io_size * io->regspacing)
- (io->regspacing - io->regsize));
io->addr = ioremap(addr, mapsize);
if (io->addr == NULL) {
mem_region_cleanup(io, io->io_size);
return -EIO;
}
return 0;
}
Commit Message: ipmi_si: fix use-after-free of resource->name
When we excute the following commands, we got oops
rmmod ipmi_si
cat /proc/ioports
[ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478
[ 1623.482382] Mem abort info:
[ 1623.482383] ESR = 0x96000007
[ 1623.482385] Exception class = DABT (current EL), IL = 32 bits
[ 1623.482386] SET = 0, FnV = 0
[ 1623.482387] EA = 0, S1PTW = 0
[ 1623.482388] Data abort info:
[ 1623.482389] ISV = 0, ISS = 0x00000007
[ 1623.482390] CM = 0, WnR = 0
[ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66
[ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000
[ 1623.482399] Internal error: Oops: 96000007 [#1] SMP
[ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si]
[ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168
[ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017
[ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO)
[ 1623.553684] pc : string+0x28/0x98
[ 1623.557040] lr : vsnprintf+0x368/0x5e8
[ 1623.560837] sp : ffff000013213a80
[ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5
[ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049
[ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5
[ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000
[ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000
[ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff
[ 1623.596505] x17: 0000000000000200 x16: 0000000000000000
[ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000
[ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000
[ 1623.612661] x11: 0000000000000000 x10: 0000000000000000
[ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f
[ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe
[ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478
[ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000
[ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff
[ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10)
[ 1623.651592] Call trace:
[ 1623.654068] string+0x28/0x98
[ 1623.657071] vsnprintf+0x368/0x5e8
[ 1623.660517] seq_vprintf+0x70/0x98
[ 1623.668009] seq_printf+0x7c/0xa0
[ 1623.675530] r_show+0xc8/0xf8
[ 1623.682558] seq_read+0x330/0x440
[ 1623.689877] proc_reg_read+0x78/0xd0
[ 1623.697346] __vfs_read+0x60/0x1a0
[ 1623.704564] vfs_read+0x94/0x150
[ 1623.711339] ksys_read+0x6c/0xd8
[ 1623.717939] __arm64_sys_read+0x24/0x30
[ 1623.725077] el0_svc_common+0x120/0x148
[ 1623.732035] el0_svc_handler+0x30/0x40
[ 1623.738757] el0_svc+0x8/0xc
[ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085)
[ 1623.753441] ---[ end trace f91b6a4937de9835 ]---
[ 1623.760871] Kernel panic - not syncing: Fatal exception
[ 1623.768935] SMP: stopping secondary CPUs
[ 1623.775718] Kernel Offset: disabled
[ 1623.781998] CPU features: 0x002,21006008
[ 1623.788777] Memory Limit: none
[ 1623.798329] Starting crashdump kernel...
[ 1623.805202] Bye!
If io_setup is called successful in try_smi_init() but try_smi_init()
goes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi()
will not be called while removing module. It leads to the resource that
allocated in io_setup() can not be freed, but the name(DEVICE_NAME) of
resource is freed while removing the module. It causes use-after-free
when cat /proc/ioports.
Fix this by calling io_cleanup() while try_smi_init() goes to out_err.
and don't call io_cleanup() until io_setup() returns successful to avoid
warning prints.
Fixes: 93c303d2045b ("ipmi_si: Clean up shutdown a bit")
Cc: [email protected]
Reported-by: NuoHan Qiao <[email protected]>
Suggested-by: Corey Minyard <[email protected]>
Signed-off-by: Yang Yingliang <[email protected]>
Signed-off-by: Corey Minyard <[email protected]>
CWE ID: CWE-416 | int ipmi_si_mem_setup(struct si_sm_io *io)
{
unsigned long addr = io->addr_data;
int mapsize, idx;
if (!addr)
return -ENODEV;
/*
* Figure out the actual readb/readw/readl/etc routine to use based
* upon the register size.
*/
switch (io->regsize) {
case 1:
io->inputb = intf_mem_inb;
io->outputb = intf_mem_outb;
break;
case 2:
io->inputb = intf_mem_inw;
io->outputb = intf_mem_outw;
break;
case 4:
io->inputb = intf_mem_inl;
io->outputb = intf_mem_outl;
break;
#ifdef readq
case 8:
io->inputb = mem_inq;
io->outputb = mem_outq;
break;
#endif
default:
dev_warn(io->dev, "Invalid register size: %d\n",
io->regsize);
return -EINVAL;
}
/*
* Some BIOSes reserve disjoint memory regions in their ACPI
* tables. This causes problems when trying to request the
* entire region. Therefore we must request each register
* separately.
*/
for (idx = 0; idx < io->io_size; idx++) {
if (request_mem_region(addr + idx * io->regspacing,
io->regsize, DEVICE_NAME) == NULL) {
/* Undo allocations */
mem_region_cleanup(io, idx);
return -EIO;
}
}
/*
* Calculate the total amount of memory to claim. This is an
* unusual looking calculation, but it avoids claiming any
* more memory than it has to. It will claim everything
* between the first address to the end of the last full
* register.
*/
mapsize = ((io->io_size * io->regspacing)
- (io->regspacing - io->regsize));
io->addr = ioremap(addr, mapsize);
if (io->addr == NULL) {
mem_region_cleanup(io, io->io_size);
return -EIO;
}
io->io_cleanup = mem_cleanup;
return 0;
}
| 169,681 |
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 v8::Handle<v8::Value> excitingFunctionCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestActiveDOMObject.excitingFunction");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestActiveDOMObject* imp = V8TestActiveDOMObject::toNative(args.Holder());
if (!V8BindingSecurity::canAccessFrame(V8BindingState::Only(), imp->frame(), true))
return v8::Handle<v8::Value>();
EXCEPTION_BLOCK(Node*, nextChild, V8Node::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Node::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
imp->excitingFunction(nextChild);
return v8::Handle<v8::Value>();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static v8::Handle<v8::Value> excitingFunctionCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestActiveDOMObject.excitingFunction");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
TestActiveDOMObject* imp = V8TestActiveDOMObject::toNative(args.Holder());
if (!V8BindingSecurity::canAccessFrame(V8BindingState::Only(), imp->frame(), true))
return v8::Handle<v8::Value>();
EXCEPTION_BLOCK(Node*, nextChild, V8Node::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Node::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
imp->excitingFunction(nextChild);
return v8::Handle<v8::Value>();
}
| 171,066 |
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: cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h,
cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count)
{
size_t i, maxcount;
const cdf_summary_info_header_t *si =
CAST(const cdf_summary_info_header_t *, sst->sst_tab);
const cdf_section_declaration_t *sd =
CAST(const cdf_section_declaration_t *, (const void *)
((const char *)sst->sst_tab + CDF_SECTION_DECLARATION_OFFSET));
if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 ||
cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1)
return -1;
ssi->si_byte_order = CDF_TOLE2(si->si_byte_order);
ssi->si_os_version = CDF_TOLE2(si->si_os_version);
ssi->si_os = CDF_TOLE2(si->si_os);
ssi->si_class = si->si_class;
cdf_swap_class(&ssi->si_class);
ssi->si_count = CDF_TOLE2(si->si_count);
*count = 0;
maxcount = 0;
*info = NULL;
for (i = 0; i < CDF_TOLE4(si->si_count); i++) {
if (i >= CDF_LOOP_LIMIT) {
DPRINTF(("Unpack summary info loop limit"));
errno = EFTYPE;
return -1;
}
if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset),
info, count, &maxcount) == -1) {
return -1;
}
}
return 0;
}
Commit Message: Remove loop that kept reading the same offset (Jan Kaluza)
CWE ID: CWE-399 | cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h,
cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count)
{
size_t maxcount;
const cdf_summary_info_header_t *si =
CAST(const cdf_summary_info_header_t *, sst->sst_tab);
const cdf_section_declaration_t *sd =
CAST(const cdf_section_declaration_t *, (const void *)
((const char *)sst->sst_tab + CDF_SECTION_DECLARATION_OFFSET));
if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 ||
cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1)
return -1;
ssi->si_byte_order = CDF_TOLE2(si->si_byte_order);
ssi->si_os_version = CDF_TOLE2(si->si_os_version);
ssi->si_os = CDF_TOLE2(si->si_os);
ssi->si_class = si->si_class;
cdf_swap_class(&ssi->si_class);
ssi->si_count = CDF_TOLE4(si->si_count);
*count = 0;
maxcount = 0;
*info = NULL;
if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info,
count, &maxcount) == -1)
return -1;
return 0;
}
| 166,443 |
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: InternalPageInfoBubbleView::InternalPageInfoBubbleView(
views::View* anchor_view,
const gfx::Rect& anchor_rect,
gfx::NativeView parent_window,
const GURL& url)
: BubbleDialogDelegateView(anchor_view, views::BubbleBorder::TOP_LEFT) {
g_shown_bubble_type = PageInfoBubbleView::BUBBLE_INTERNAL_PAGE;
g_page_info_bubble = this;
set_parent_window(parent_window);
if (!anchor_view)
SetAnchorRect(anchor_rect);
int text = IDS_PAGE_INFO_INTERNAL_PAGE;
int icon = IDR_PRODUCT_LOGO_16;
if (url.SchemeIs(extensions::kExtensionScheme)) {
text = IDS_PAGE_INFO_EXTENSION_PAGE;
icon = IDR_PLUGINS_FAVICON;
} else if (url.SchemeIs(content::kViewSourceScheme)) {
text = IDS_PAGE_INFO_VIEW_SOURCE_PAGE;
icon = IDR_PRODUCT_LOGO_16;
} else if (!url.SchemeIs(content::kChromeUIScheme) &&
!url.SchemeIs(content::kChromeDevToolsScheme)) {
NOTREACHED();
}
set_anchor_view_insets(gfx::Insets(
GetLayoutConstant(LOCATION_BAR_BUBBLE_ANCHOR_VERTICAL_INSET), 0));
SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal,
gfx::Insets(kSpacing), kSpacing));
set_margins(gfx::Insets());
if (ChromeLayoutProvider::Get()->ShouldShowWindowIcon()) {
views::ImageView* icon_view = new NonAccessibleImageView();
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
icon_view->SetImage(rb.GetImageSkiaNamed(icon));
AddChildView(icon_view);
}
views::Label* label = new views::Label(l10n_util::GetStringUTF16(text));
label->SetMultiLine(true);
label->SetAllowCharacterBreak(true);
label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
AddChildView(label);
views::BubbleDialogDelegateView::CreateBubble(this);
}
Commit Message: Desktop Page Info/Harmony: Show close button for internal pages.
The Harmony version of Page Info for internal Chrome pages (chrome://,
chrome-extension:// and view-source:// pages) show a close button. Update the
code to match this.
This patch also adds TestBrowserDialog tests for the latter two cases described
above (internal extension and view source pages).
See screenshot -
https://drive.google.com/file/d/18RZnMiHCu-rCX9N6DLUpu4mkFWguh1xm/view?usp=sharing
Bug: 535074
Change-Id: I55e5f1aa682fd4ec85f7b65ac88f5a4f5906fe53
Reviewed-on: https://chromium-review.googlesource.com/759624
Commit-Queue: Patti <[email protected]>
Reviewed-by: Trent Apted <[email protected]>
Cr-Commit-Position: refs/heads/master@{#516624}
CWE ID: CWE-704 | InternalPageInfoBubbleView::InternalPageInfoBubbleView(
views::View* anchor_view,
const gfx::Rect& anchor_rect,
gfx::NativeView parent_window,
const GURL& url)
: BubbleDialogDelegateView(anchor_view, views::BubbleBorder::TOP_LEFT) {
g_shown_bubble_type = PageInfoBubbleView::BUBBLE_INTERNAL_PAGE;
g_page_info_bubble = this;
set_parent_window(parent_window);
if (!anchor_view)
SetAnchorRect(anchor_rect);
int text = IDS_PAGE_INFO_INTERNAL_PAGE;
int icon = IDR_PRODUCT_LOGO_16;
if (url.SchemeIs(extensions::kExtensionScheme)) {
text = IDS_PAGE_INFO_EXTENSION_PAGE;
icon = IDR_PLUGINS_FAVICON;
} else if (url.SchemeIs(content::kViewSourceScheme)) {
text = IDS_PAGE_INFO_VIEW_SOURCE_PAGE;
icon = IDR_PRODUCT_LOGO_16;
} else if (!url.SchemeIs(content::kChromeUIScheme) &&
!url.SchemeIs(content::kChromeDevToolsScheme)) {
NOTREACHED();
}
set_anchor_view_insets(gfx::Insets(
GetLayoutConstant(LOCATION_BAR_BUBBLE_ANCHOR_VERTICAL_INSET), 0));
// Title insets assume there is content (and thus have no bottom padding). Use
// dialog insets to get the bottom margin back.
set_title_margins(
ChromeLayoutProvider::Get()->GetInsetsMetric(views::INSETS_DIALOG));
set_margins(gfx::Insets());
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
bubble_icon_ = rb.GetImageSkiaNamed(icon);
title_text_ = l10n_util::GetStringUTF16(text);
views::BubbleDialogDelegateView::CreateBubble(this);
// Use a normal label's style for the title since there is no content.
views::Label* title_label =
static_cast<views::Label*>(GetBubbleFrameView()->title());
title_label->SetFontList(views::Label::GetDefaultFontList());
title_label->SetMultiLine(false);
title_label->SetElideBehavior(gfx::NO_ELIDE);
SizeToContents();
}
| 172,298 |
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: xfs_attr_rmtval_set(
struct xfs_da_args *args)
{
struct xfs_inode *dp = args->dp;
struct xfs_mount *mp = dp->i_mount;
struct xfs_bmbt_irec map;
xfs_dablk_t lblkno;
xfs_fileoff_t lfileoff = 0;
__uint8_t *src = args->value;
int blkcnt;
int valuelen;
int nmap;
int error;
int offset = 0;
trace_xfs_attr_rmtval_set(args);
/*
* Find a "hole" in the attribute address space large enough for
* us to drop the new attribute's value into. Because CRC enable
* attributes have headers, we can't just do a straight byte to FSB
* conversion and have to take the header space into account.
*/
blkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen);
error = xfs_bmap_first_unused(args->trans, args->dp, blkcnt, &lfileoff,
XFS_ATTR_FORK);
if (error)
return error;
args->rmtblkno = lblkno = (xfs_dablk_t)lfileoff;
args->rmtblkcnt = blkcnt;
/*
* Roll through the "value", allocating blocks on disk as required.
*/
while (blkcnt > 0) {
int committed;
/*
* Allocate a single extent, up to the size of the value.
*/
xfs_bmap_init(args->flist, args->firstblock);
nmap = 1;
error = xfs_bmapi_write(args->trans, dp, (xfs_fileoff_t)lblkno,
blkcnt,
XFS_BMAPI_ATTRFORK | XFS_BMAPI_METADATA,
args->firstblock, args->total, &map, &nmap,
args->flist);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
ASSERT(nmap == 1);
ASSERT((map.br_startblock != DELAYSTARTBLOCK) &&
(map.br_startblock != HOLESTARTBLOCK));
lblkno += map.br_blockcount;
blkcnt -= map.br_blockcount;
/*
* Start the next trans in the chain.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
return (error);
}
/*
* Roll through the "value", copying the attribute value to the
* already-allocated blocks. Blocks are written synchronously
* so that we can know they are all on disk before we turn off
* the INCOMPLETE flag.
*/
lblkno = args->rmtblkno;
blkcnt = args->rmtblkcnt;
valuelen = args->valuelen;
while (valuelen > 0) {
struct xfs_buf *bp;
xfs_daddr_t dblkno;
int dblkcnt;
ASSERT(blkcnt > 0);
xfs_bmap_init(args->flist, args->firstblock);
nmap = 1;
error = xfs_bmapi_read(dp, (xfs_fileoff_t)lblkno,
blkcnt, &map, &nmap,
XFS_BMAPI_ATTRFORK);
if (error)
return(error);
ASSERT(nmap == 1);
ASSERT((map.br_startblock != DELAYSTARTBLOCK) &&
(map.br_startblock != HOLESTARTBLOCK));
dblkno = XFS_FSB_TO_DADDR(mp, map.br_startblock),
dblkcnt = XFS_FSB_TO_BB(mp, map.br_blockcount);
bp = xfs_buf_get(mp->m_ddev_targp, dblkno, dblkcnt, 0);
if (!bp)
return ENOMEM;
bp->b_ops = &xfs_attr3_rmt_buf_ops;
xfs_attr_rmtval_copyin(mp, bp, args->dp->i_ino, &offset,
&valuelen, &src);
error = xfs_bwrite(bp); /* GROT: NOTE: synchronous write */
xfs_buf_relse(bp);
if (error)
return error;
/* roll attribute extent map forwards */
lblkno += map.br_blockcount;
blkcnt -= map.br_blockcount;
}
ASSERT(valuelen == 0);
return 0;
}
Commit Message: xfs: remote attribute overwrite causes transaction overrun
Commit e461fcb ("xfs: remote attribute lookups require the value
length") passes the remote attribute length in the xfs_da_args
structure on lookup so that CRC calculations and validity checking
can be performed correctly by related code. This, unfortunately has
the side effect of changing the args->valuelen parameter in cases
where it shouldn't.
That is, when we replace a remote attribute, the incoming
replacement stores the value and length in args->value and
args->valuelen, but then the lookup which finds the existing remote
attribute overwrites args->valuelen with the length of the remote
attribute being replaced. Hence when we go to create the new
attribute, we create it of the size of the existing remote
attribute, not the size it is supposed to be. When the new attribute
is much smaller than the old attribute, this results in a
transaction overrun and an ASSERT() failure on a debug kernel:
XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331
Fix this by keeping the remote attribute value length separate to
the attribute value length in the xfs_da_args structure. The enables
us to pass the length of the remote attribute to be removed without
overwriting the new attribute's length.
Also, ensure that when we save remote block contexts for a later
rename we zero the original state variables so that we don't confuse
the state of the attribute to be removes with the state of the new
attribute that we just added. [Spotted by Brain Foster.]
Signed-off-by: Dave Chinner <[email protected]>
Reviewed-by: Brian Foster <[email protected]>
Signed-off-by: Dave Chinner <[email protected]>
CWE ID: CWE-19 | xfs_attr_rmtval_set(
struct xfs_da_args *args)
{
struct xfs_inode *dp = args->dp;
struct xfs_mount *mp = dp->i_mount;
struct xfs_bmbt_irec map;
xfs_dablk_t lblkno;
xfs_fileoff_t lfileoff = 0;
__uint8_t *src = args->value;
int blkcnt;
int valuelen;
int nmap;
int error;
int offset = 0;
trace_xfs_attr_rmtval_set(args);
/*
* Find a "hole" in the attribute address space large enough for
* us to drop the new attribute's value into. Because CRC enable
* attributes have headers, we can't just do a straight byte to FSB
* conversion and have to take the header space into account.
*/
blkcnt = xfs_attr3_rmt_blocks(mp, args->rmtvaluelen);
error = xfs_bmap_first_unused(args->trans, args->dp, blkcnt, &lfileoff,
XFS_ATTR_FORK);
if (error)
return error;
args->rmtblkno = lblkno = (xfs_dablk_t)lfileoff;
args->rmtblkcnt = blkcnt;
/*
* Roll through the "value", allocating blocks on disk as required.
*/
while (blkcnt > 0) {
int committed;
/*
* Allocate a single extent, up to the size of the value.
*/
xfs_bmap_init(args->flist, args->firstblock);
nmap = 1;
error = xfs_bmapi_write(args->trans, dp, (xfs_fileoff_t)lblkno,
blkcnt,
XFS_BMAPI_ATTRFORK | XFS_BMAPI_METADATA,
args->firstblock, args->total, &map, &nmap,
args->flist);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
ASSERT(nmap == 1);
ASSERT((map.br_startblock != DELAYSTARTBLOCK) &&
(map.br_startblock != HOLESTARTBLOCK));
lblkno += map.br_blockcount;
blkcnt -= map.br_blockcount;
/*
* Start the next trans in the chain.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
return (error);
}
/*
* Roll through the "value", copying the attribute value to the
* already-allocated blocks. Blocks are written synchronously
* so that we can know they are all on disk before we turn off
* the INCOMPLETE flag.
*/
lblkno = args->rmtblkno;
blkcnt = args->rmtblkcnt;
valuelen = args->rmtvaluelen;
while (valuelen > 0) {
struct xfs_buf *bp;
xfs_daddr_t dblkno;
int dblkcnt;
ASSERT(blkcnt > 0);
xfs_bmap_init(args->flist, args->firstblock);
nmap = 1;
error = xfs_bmapi_read(dp, (xfs_fileoff_t)lblkno,
blkcnt, &map, &nmap,
XFS_BMAPI_ATTRFORK);
if (error)
return(error);
ASSERT(nmap == 1);
ASSERT((map.br_startblock != DELAYSTARTBLOCK) &&
(map.br_startblock != HOLESTARTBLOCK));
dblkno = XFS_FSB_TO_DADDR(mp, map.br_startblock),
dblkcnt = XFS_FSB_TO_BB(mp, map.br_blockcount);
bp = xfs_buf_get(mp->m_ddev_targp, dblkno, dblkcnt, 0);
if (!bp)
return ENOMEM;
bp->b_ops = &xfs_attr3_rmt_buf_ops;
xfs_attr_rmtval_copyin(mp, bp, args->dp->i_ino, &offset,
&valuelen, &src);
error = xfs_bwrite(bp); /* GROT: NOTE: synchronous write */
xfs_buf_relse(bp);
if (error)
return error;
/* roll attribute extent map forwards */
lblkno += map.br_blockcount;
blkcnt -= map.br_blockcount;
}
ASSERT(valuelen == 0);
return 0;
}
| 166,740 |
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 ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
{
int ret;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
unsigned char *p = NULL, *end = NULL;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
{
if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* ServerKeyExchange may be skipped with PSK and RSA-PSK when the server
* doesn't use a psk_identity_hint
*/
if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )
{
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
{
/* Current message is probably either
* CertificateRequest or ServerHelloDone */
ssl->keep_current_message = 1;
goto exit;
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key exchange message must "
"not be skipped" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
end = ssl->in_msg + ssl->in_hslen;
MBEDTLS_SSL_DEBUG_BUF( 3, "server key exchange", p, end - p );
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
} /* FALLTROUGH */
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
; /* nothing more to do */
else
#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
{
if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
{
if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
p, end - p );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
{
size_t sig_len, hashlen;
unsigned char hash[64];
mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
size_t params_len = p - params;
/*
* Handle the digitally-signed structure
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
if( ssl_parse_signature_algorithm( ssl, &p, end,
&md_alg, &pk_alg ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
{
pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
/* Default hash for ECDSA is SHA-1 */
if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE )
md_alg = MBEDTLS_MD_SHA1;
}
else
#endif
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
/*
* Read signature
*/
if( p > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
sig_len = ( p[0] << 8 ) | p[1];
p += 2;
if( end != p + sig_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len );
/*
* Compute the hash that has been signed
*/
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( md_alg == MBEDTLS_MD_NONE )
{
hashlen = 36;
ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params,
params_len );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( md_alg != MBEDTLS_MD_NONE )
{
/* Info from md_alg will be used instead */
hashlen = 0;
ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, params,
params_len, md_alg );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen != 0 ? hashlen :
(unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) );
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* Verify signature
*/
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,
md_alg, hash, hashlen, p, sig_len ) ) != 0 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
return( ret );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
exit:
ssl->state++;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) );
return( 0 );
}
Commit Message: Prevent arithmetic overflow on bounds check
CWE ID: CWE-119 | static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
{
int ret;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
unsigned char *p = NULL, *end = NULL;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
{
if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* ServerKeyExchange may be skipped with PSK and RSA-PSK when the server
* doesn't use a psk_identity_hint
*/
if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )
{
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
{
/* Current message is probably either
* CertificateRequest or ServerHelloDone */
ssl->keep_current_message = 1;
goto exit;
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key exchange message must "
"not be skipped" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
end = ssl->in_msg + ssl->in_hslen;
MBEDTLS_SSL_DEBUG_BUF( 3, "server key exchange", p, end - p );
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
} /* FALLTROUGH */
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
; /* nothing more to do */
else
#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
{
if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
{
if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
p, end - p );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
{
size_t sig_len, hashlen;
unsigned char hash[64];
mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
size_t params_len = p - params;
/*
* Handle the digitally-signed structure
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
if( ssl_parse_signature_algorithm( ssl, &p, end,
&md_alg, &pk_alg ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
{
pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
/* Default hash for ECDSA is SHA-1 */
if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE )
md_alg = MBEDTLS_MD_SHA1;
}
else
#endif
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
/*
* Read signature
*/
if( p > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
sig_len = ( p[0] << 8 ) | p[1];
p += 2;
if( p != end - sig_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len );
/*
* Compute the hash that has been signed
*/
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( md_alg == MBEDTLS_MD_NONE )
{
hashlen = 36;
ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params,
params_len );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( md_alg != MBEDTLS_MD_NONE )
{
/* Info from md_alg will be used instead */
hashlen = 0;
ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, params,
params_len, md_alg );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen != 0 ? hashlen :
(unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) );
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* Verify signature
*/
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,
md_alg, hash, hashlen, p, sig_len ) ) != 0 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
return( ret );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
exit:
ssl->state++;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) );
return( 0 );
}
| 170,170 |
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: jbig2_decode_text_region(Jbig2Ctx *ctx, Jbig2Segment *segment,
const Jbig2TextRegionParams *params,
const Jbig2SymbolDict *const *dicts, const int n_dicts,
Jbig2Image *image, const byte *data, const size_t size, Jbig2ArithCx *GR_stats, Jbig2ArithState *as, Jbig2WordStream *ws)
{
/* relevent bits of 6.4.4 */
uint32_t NINSTANCES;
uint32_t ID;
int32_t STRIPT;
int32_t FIRSTS;
int32_t DT;
int32_t DFS;
int32_t IDS;
int32_t CURS;
int32_t CURT;
int S, T;
int x, y;
bool first_symbol;
uint32_t index, SBNUMSYMS;
Jbig2Image *IB = NULL;
Jbig2HuffmanState *hs = NULL;
Jbig2HuffmanTable *SBSYMCODES = NULL;
int code = 0;
int RI;
SBNUMSYMS = 0;
for (index = 0; index < n_dicts; index++) {
SBNUMSYMS += dicts[index]->n_symbols;
}
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, "symbol list contains %d glyphs in %d dictionaries", SBNUMSYMS, n_dicts);
if (params->SBHUFF) {
Jbig2HuffmanTable *runcodes = NULL;
Jbig2HuffmanParams runcodeparams;
Jbig2HuffmanLine runcodelengths[35];
Jbig2HuffmanLine *symcodelengths = NULL;
Jbig2HuffmanParams symcodeparams;
int err, len, range, r;
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, "huffman coded text region");
hs = jbig2_huffman_new(ctx, ws);
if (hs == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, "failed to allocate storage for text region");
return -1;
}
/* 7.4.3.1.7 - decode symbol ID Huffman table */
/* this is actually part of the segment header, but it is more
convenient to handle it here */
/* parse and build the runlength code huffman table */
for (index = 0; index < 35; index++) {
runcodelengths[index].PREFLEN = jbig2_huffman_get_bits(hs, 4, &code);
if (code < 0)
goto cleanup1;
runcodelengths[index].RANGELEN = 0;
runcodelengths[index].RANGELOW = index;
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, " read runcode%d length %d", index, runcodelengths[index].PREFLEN);
}
runcodeparams.HTOOB = 0;
runcodeparams.lines = runcodelengths;
runcodeparams.n_lines = 35;
runcodes = jbig2_build_huffman_table(ctx, &runcodeparams);
if (runcodes == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "error constructing symbol id runcode table!");
code = -1;
goto cleanup1;
}
/* decode the symbol id codelengths using the runlength table */
symcodelengths = jbig2_new(ctx, Jbig2HuffmanLine, SBNUMSYMS);
if (symcodelengths == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "memory allocation failure reading symbol ID huffman table!");
code = -1;
goto cleanup1;
}
index = 0;
while (index < SBNUMSYMS) {
code = jbig2_huffman_get(hs, runcodes, &err);
if (err != 0 || code < 0 || code >= 35) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "error reading symbol ID huffman table!");
code = err ? err : -1;
goto cleanup1;
}
if (code < 32) {
len = code;
range = 1;
} else {
if (code == 32) {
if (index < 1) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "error decoding symbol id table: run length with no antecedent!");
code = -1;
goto cleanup1;
}
len = symcodelengths[index - 1].PREFLEN;
} else {
len = 0; /* code == 33 or 34 */
}
err = 0;
if (code == 32)
range = jbig2_huffman_get_bits(hs, 2, &err) + 3;
else if (code == 33)
range = jbig2_huffman_get_bits(hs, 3, &err) + 3;
else if (code == 34)
range = jbig2_huffman_get_bits(hs, 7, &err) + 11;
if (err < 0)
goto cleanup1;
}
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, " read runcode%d at index %d (length %d range %d)", code, index, len, range);
if (index + range > SBNUMSYMS) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number,
"runlength extends %d entries beyond the end of symbol id table!", index + range - SBNUMSYMS);
range = SBNUMSYMS - index;
}
for (r = 0; r < range; r++) {
symcodelengths[index + r].PREFLEN = len;
symcodelengths[index + r].RANGELEN = 0;
symcodelengths[index + r].RANGELOW = index + r;
}
index += r;
}
if (index < SBNUMSYMS) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, "runlength codes do not cover the available symbol set");
}
symcodeparams.HTOOB = 0;
symcodeparams.lines = symcodelengths;
symcodeparams.n_lines = SBNUMSYMS;
/* skip to byte boundary */
jbig2_huffman_skip(hs);
/* finally, construct the symbol id huffman table itself */
SBSYMCODES = jbig2_build_huffman_table(ctx, &symcodeparams);
cleanup1:
jbig2_free(ctx->allocator, symcodelengths);
jbig2_release_huffman_table(ctx, runcodes);
if (SBSYMCODES == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "could not construct Symbol ID huffman table!");
jbig2_huffman_free(ctx, hs);
return ((code != 0) ? code : -1);
}
}
/* 6.4.5 (1) */
jbig2_image_clear(ctx, image, params->SBDEFPIXEL);
/* 6.4.6 */
if (params->SBHUFF) {
STRIPT = jbig2_huffman_get(hs, params->SBHUFFDT, &code);
} else {
code = jbig2_arith_int_decode(params->IADT, as, &STRIPT);
}
if (code < 0)
goto cleanup2;
/* 6.4.5 (2) */
STRIPT *= -(params->SBSTRIPS);
FIRSTS = 0;
NINSTANCES = 0;
/* 6.4.5 (3) */
while (NINSTANCES < params->SBNUMINSTANCES) {
/* (3b) */
if (params->SBHUFF) {
DT = jbig2_huffman_get(hs, params->SBHUFFDT, &code);
} else {
code = jbig2_arith_int_decode(params->IADT, as, &DT);
}
if (code < 0)
goto cleanup2;
DT *= params->SBSTRIPS;
STRIPT += DT;
first_symbol = TRUE;
/* 6.4.5 (3c) - decode symbols in strip */
for (;;) {
/* (3c.i) */
if (first_symbol) {
/* 6.4.7 */
if (params->SBHUFF) {
DFS = jbig2_huffman_get(hs, params->SBHUFFFS, &code);
} else {
code = jbig2_arith_int_decode(params->IAFS, as, &DFS);
}
if (code < 0)
goto cleanup2;
FIRSTS += DFS;
CURS = FIRSTS;
first_symbol = FALSE;
} else {
if (NINSTANCES > params->SBNUMINSTANCES) {
code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "too many NINSTANCES (%d) decoded", NINSTANCES);
break;
}
/* (3c.ii) / 6.4.8 */
if (params->SBHUFF) {
IDS = jbig2_huffman_get(hs, params->SBHUFFDS, &code);
} else {
code = jbig2_arith_int_decode(params->IADS, as, &IDS);
}
if (code) {
/* decoded an OOB, reached end of strip */
break;
}
CURS += IDS + params->SBDSOFFSET;
}
/* (3c.iii) / 6.4.9 */
if (params->SBSTRIPS == 1) {
CURT = 0;
} else if (params->SBHUFF) {
CURT = jbig2_huffman_get_bits(hs, params->LOGSBSTRIPS, &code);
} else {
code = jbig2_arith_int_decode(params->IAIT, as, &CURT);
}
if (code < 0)
goto cleanup2;
T = STRIPT + CURT;
/* (3b.iv) / 6.4.10 - decode the symbol id */
if (params->SBHUFF) {
ID = jbig2_huffman_get(hs, SBSYMCODES, &code);
} else {
code = jbig2_arith_iaid_decode(params->IAID, as, (int *)&ID);
}
if (code < 0)
goto cleanup2;
if (ID >= SBNUMSYMS) {
code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "symbol id out of range! (%d/%d)", ID, SBNUMSYMS);
goto cleanup2;
}
/* (3c.v) / 6.4.11 - look up the symbol bitmap IB */
{
uint32_t id = ID;
index = 0;
while (id >= dicts[index]->n_symbols)
id -= dicts[index++]->n_symbols;
IB = jbig2_image_clone(ctx, dicts[index]->glyphs[id]);
/* SumatraPDF: fail on missing glyphs */
if (!IB) {
code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "missing glyph %d/%d!", index, id);
goto cleanup2;
}
}
if (params->SBREFINE) {
if (params->SBHUFF) {
RI = jbig2_huffman_get_bits(hs, 1, &code);
} else {
code = jbig2_arith_int_decode(params->IARI, as, &RI);
}
if (code < 0)
goto cleanup2;
} else {
RI = 0;
}
if (RI) {
Jbig2RefinementRegionParams rparams;
Jbig2Image *IBO;
int32_t RDW, RDH, RDX, RDY;
Jbig2Image *refimage;
int BMSIZE = 0;
int code1 = 0;
int code2 = 0;
int code3 = 0;
int code4 = 0;
int code5 = 0;
/* 6.4.11 (1, 2, 3, 4) */
if (!params->SBHUFF) {
code1 = jbig2_arith_int_decode(params->IARDW, as, &RDW);
code2 = jbig2_arith_int_decode(params->IARDH, as, &RDH);
code3 = jbig2_arith_int_decode(params->IARDX, as, &RDX);
code4 = jbig2_arith_int_decode(params->IARDY, as, &RDY);
} else {
RDW = jbig2_huffman_get(hs, params->SBHUFFRDW, &code1);
RDH = jbig2_huffman_get(hs, params->SBHUFFRDH, &code2);
RDX = jbig2_huffman_get(hs, params->SBHUFFRDX, &code3);
RDY = jbig2_huffman_get(hs, params->SBHUFFRDY, &code4);
BMSIZE = jbig2_huffman_get(hs, params->SBHUFFRSIZE, &code5);
jbig2_huffman_skip(hs);
}
if ((code1 < 0) || (code2 < 0) || (code3 < 0) || (code4 < 0) || (code5 < 0)) {
code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to decode data");
goto cleanup2;
}
/* 6.4.11 (6) */
IBO = IB;
refimage = jbig2_image_new(ctx, IBO->width + RDW, IBO->height + RDH);
if (refimage == NULL) {
jbig2_image_release(ctx, IBO);
if (params->SBHUFF) {
jbig2_release_huffman_table(ctx, SBSYMCODES);
}
return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "couldn't allocate reference image");
}
jbig2_image_clear(ctx, refimage, 0x00);
/* Table 12 */
rparams.GRTEMPLATE = params->SBRTEMPLATE;
rparams.reference = IBO;
rparams.DX = (RDW >> 1) + RDX;
rparams.DY = (RDH >> 1) + RDY;
rparams.TPGRON = 0;
memcpy(rparams.grat, params->sbrat, 4);
code = jbig2_decode_refinement_region(ctx, segment, &rparams, as, refimage, GR_stats);
if (code < 0) {
jbig2_image_release(ctx, refimage);
goto cleanup2;
}
IB = refimage;
jbig2_image_release(ctx, IBO);
/* 6.4.11 (7) */
if (params->SBHUFF) {
jbig2_huffman_advance(hs, BMSIZE);
}
}
/* (3c.vi) */
if ((!params->TRANSPOSED) && (params->REFCORNER > 1)) {
CURS += IB->width - 1;
} else if ((params->TRANSPOSED) && !(params->REFCORNER & 1)) {
CURS += IB->height - 1;
}
/* (3c.vii) */
S = CURS;
/* (3c.viii) */
if (!params->TRANSPOSED) {
switch (params->REFCORNER) {
case JBIG2_CORNER_TOPLEFT:
x = S;
y = T;
break;
case JBIG2_CORNER_TOPRIGHT:
x = S - IB->width + 1;
y = T;
break;
case JBIG2_CORNER_BOTTOMLEFT:
x = S;
y = T - IB->height + 1;
break;
default:
case JBIG2_CORNER_BOTTOMRIGHT:
x = S - IB->width + 1;
y = T - IB->height + 1;
break;
}
} else { /* TRANSPOSED */
switch (params->REFCORNER) {
case JBIG2_CORNER_TOPLEFT:
x = T;
y = S;
break;
case JBIG2_CORNER_TOPRIGHT:
x = T - IB->width + 1;
y = S;
break;
case JBIG2_CORNER_BOTTOMLEFT:
x = T;
y = S - IB->height + 1;
break;
default:
case JBIG2_CORNER_BOTTOMRIGHT:
x = T - IB->width + 1;
y = S - IB->height + 1;
break;
}
}
/* (3c.ix) */
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number,
"composing glyph id %d: %dx%d @ (%d,%d) symbol %d/%d", ID, IB->width, IB->height, x, y, NINSTANCES + 1, params->SBNUMINSTANCES);
#endif
code = jbig2_image_compose(ctx, image, IB, x, y, params->SBCOMBOP);
if (code < 0) {
jbig2_image_release(ctx, IB);
goto cleanup2;
}
/* (3c.x) */
if ((!params->TRANSPOSED) && (params->REFCORNER < 2)) {
CURS += IB->width - 1;
} else if ((params->TRANSPOSED) && (params->REFCORNER & 1)) {
CURS += IB->height - 1;
}
/* (3c.xi) */
NINSTANCES++;
jbig2_image_release(ctx, IB);
}
/* end strip */
}
/* 6.4.5 (4) */
cleanup2:
if (params->SBHUFF) {
jbig2_release_huffman_table(ctx, SBSYMCODES);
}
jbig2_huffman_free(ctx, hs);
return code;
}
Commit Message:
CWE ID: CWE-119 | jbig2_decode_text_region(Jbig2Ctx *ctx, Jbig2Segment *segment,
const Jbig2TextRegionParams *params,
const Jbig2SymbolDict *const *dicts, const uint32_t n_dicts,
Jbig2Image *image, const byte *data, const size_t size, Jbig2ArithCx *GR_stats, Jbig2ArithState *as, Jbig2WordStream *ws)
{
/* relevent bits of 6.4.4 */
uint32_t NINSTANCES;
uint32_t ID;
int32_t STRIPT;
int32_t FIRSTS;
int32_t DT;
int32_t DFS;
int32_t IDS;
int32_t CURS;
int32_t CURT;
int S, T;
int x, y;
bool first_symbol;
uint32_t index, SBNUMSYMS;
Jbig2Image *IB = NULL;
Jbig2HuffmanState *hs = NULL;
Jbig2HuffmanTable *SBSYMCODES = NULL;
int code = 0;
int RI;
SBNUMSYMS = 0;
for (index = 0; index < n_dicts; index++) {
SBNUMSYMS += dicts[index]->n_symbols;
}
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, "symbol list contains %d glyphs in %d dictionaries", SBNUMSYMS, n_dicts);
if (params->SBHUFF) {
Jbig2HuffmanTable *runcodes = NULL;
Jbig2HuffmanParams runcodeparams;
Jbig2HuffmanLine runcodelengths[35];
Jbig2HuffmanLine *symcodelengths = NULL;
Jbig2HuffmanParams symcodeparams;
int err, len, range, r;
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, "huffman coded text region");
hs = jbig2_huffman_new(ctx, ws);
if (hs == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, "failed to allocate storage for text region");
return -1;
}
/* 7.4.3.1.7 - decode symbol ID Huffman table */
/* this is actually part of the segment header, but it is more
convenient to handle it here */
/* parse and build the runlength code huffman table */
for (index = 0; index < 35; index++) {
runcodelengths[index].PREFLEN = jbig2_huffman_get_bits(hs, 4, &code);
if (code < 0)
goto cleanup1;
runcodelengths[index].RANGELEN = 0;
runcodelengths[index].RANGELOW = index;
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, " read runcode%d length %d", index, runcodelengths[index].PREFLEN);
}
runcodeparams.HTOOB = 0;
runcodeparams.lines = runcodelengths;
runcodeparams.n_lines = 35;
runcodes = jbig2_build_huffman_table(ctx, &runcodeparams);
if (runcodes == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "error constructing symbol id runcode table!");
code = -1;
goto cleanup1;
}
/* decode the symbol id codelengths using the runlength table */
symcodelengths = jbig2_new(ctx, Jbig2HuffmanLine, SBNUMSYMS);
if (symcodelengths == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "memory allocation failure reading symbol ID huffman table!");
code = -1;
goto cleanup1;
}
index = 0;
while (index < SBNUMSYMS) {
code = jbig2_huffman_get(hs, runcodes, &err);
if (err != 0 || code < 0 || code >= 35) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "error reading symbol ID huffman table!");
code = err ? err : -1;
goto cleanup1;
}
if (code < 32) {
len = code;
range = 1;
} else {
if (code == 32) {
if (index < 1) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "error decoding symbol id table: run length with no antecedent!");
code = -1;
goto cleanup1;
}
len = symcodelengths[index - 1].PREFLEN;
} else {
len = 0; /* code == 33 or 34 */
}
err = 0;
if (code == 32)
range = jbig2_huffman_get_bits(hs, 2, &err) + 3;
else if (code == 33)
range = jbig2_huffman_get_bits(hs, 3, &err) + 3;
else if (code == 34)
range = jbig2_huffman_get_bits(hs, 7, &err) + 11;
if (err < 0)
goto cleanup1;
}
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, " read runcode%d at index %d (length %d range %d)", code, index, len, range);
if (index + range > SBNUMSYMS) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number,
"runlength extends %d entries beyond the end of symbol id table!", index + range - SBNUMSYMS);
range = SBNUMSYMS - index;
}
for (r = 0; r < range; r++) {
symcodelengths[index + r].PREFLEN = len;
symcodelengths[index + r].RANGELEN = 0;
symcodelengths[index + r].RANGELOW = index + r;
}
index += r;
}
if (index < SBNUMSYMS) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, "runlength codes do not cover the available symbol set");
}
symcodeparams.HTOOB = 0;
symcodeparams.lines = symcodelengths;
symcodeparams.n_lines = SBNUMSYMS;
/* skip to byte boundary */
jbig2_huffman_skip(hs);
/* finally, construct the symbol id huffman table itself */
SBSYMCODES = jbig2_build_huffman_table(ctx, &symcodeparams);
cleanup1:
jbig2_free(ctx->allocator, symcodelengths);
jbig2_release_huffman_table(ctx, runcodes);
if (SBSYMCODES == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "could not construct Symbol ID huffman table!");
jbig2_huffman_free(ctx, hs);
return ((code != 0) ? code : -1);
}
}
/* 6.4.5 (1) */
jbig2_image_clear(ctx, image, params->SBDEFPIXEL);
/* 6.4.6 */
if (params->SBHUFF) {
STRIPT = jbig2_huffman_get(hs, params->SBHUFFDT, &code);
} else {
code = jbig2_arith_int_decode(params->IADT, as, &STRIPT);
}
if (code < 0)
goto cleanup2;
/* 6.4.5 (2) */
STRIPT *= -(params->SBSTRIPS);
FIRSTS = 0;
NINSTANCES = 0;
/* 6.4.5 (3) */
while (NINSTANCES < params->SBNUMINSTANCES) {
/* (3b) */
if (params->SBHUFF) {
DT = jbig2_huffman_get(hs, params->SBHUFFDT, &code);
} else {
code = jbig2_arith_int_decode(params->IADT, as, &DT);
}
if (code < 0)
goto cleanup2;
DT *= params->SBSTRIPS;
STRIPT += DT;
first_symbol = TRUE;
/* 6.4.5 (3c) - decode symbols in strip */
for (;;) {
/* (3c.i) */
if (first_symbol) {
/* 6.4.7 */
if (params->SBHUFF) {
DFS = jbig2_huffman_get(hs, params->SBHUFFFS, &code);
} else {
code = jbig2_arith_int_decode(params->IAFS, as, &DFS);
}
if (code < 0)
goto cleanup2;
FIRSTS += DFS;
CURS = FIRSTS;
first_symbol = FALSE;
} else {
if (NINSTANCES > params->SBNUMINSTANCES) {
code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "too many NINSTANCES (%d) decoded", NINSTANCES);
break;
}
/* (3c.ii) / 6.4.8 */
if (params->SBHUFF) {
IDS = jbig2_huffman_get(hs, params->SBHUFFDS, &code);
} else {
code = jbig2_arith_int_decode(params->IADS, as, &IDS);
}
if (code) {
/* decoded an OOB, reached end of strip */
break;
}
CURS += IDS + params->SBDSOFFSET;
}
/* (3c.iii) / 6.4.9 */
if (params->SBSTRIPS == 1) {
CURT = 0;
} else if (params->SBHUFF) {
CURT = jbig2_huffman_get_bits(hs, params->LOGSBSTRIPS, &code);
} else {
code = jbig2_arith_int_decode(params->IAIT, as, &CURT);
}
if (code < 0)
goto cleanup2;
T = STRIPT + CURT;
/* (3b.iv) / 6.4.10 - decode the symbol id */
if (params->SBHUFF) {
ID = jbig2_huffman_get(hs, SBSYMCODES, &code);
} else {
code = jbig2_arith_iaid_decode(params->IAID, as, (int *)&ID);
}
if (code < 0)
goto cleanup2;
if (ID >= SBNUMSYMS) {
code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "symbol id out of range! (%d/%d)", ID, SBNUMSYMS);
goto cleanup2;
}
/* (3c.v) / 6.4.11 - look up the symbol bitmap IB */
{
uint32_t id = ID;
index = 0;
while (id >= dicts[index]->n_symbols)
id -= dicts[index++]->n_symbols;
IB = jbig2_image_clone(ctx, dicts[index]->glyphs[id]);
/* SumatraPDF: fail on missing glyphs */
if (!IB) {
code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "missing glyph %d/%d!", index, id);
goto cleanup2;
}
}
if (params->SBREFINE) {
if (params->SBHUFF) {
RI = jbig2_huffman_get_bits(hs, 1, &code);
} else {
code = jbig2_arith_int_decode(params->IARI, as, &RI);
}
if (code < 0)
goto cleanup2;
} else {
RI = 0;
}
if (RI) {
Jbig2RefinementRegionParams rparams;
Jbig2Image *IBO;
int32_t RDW, RDH, RDX, RDY;
Jbig2Image *refimage;
int BMSIZE = 0;
int code1 = 0;
int code2 = 0;
int code3 = 0;
int code4 = 0;
int code5 = 0;
/* 6.4.11 (1, 2, 3, 4) */
if (!params->SBHUFF) {
code1 = jbig2_arith_int_decode(params->IARDW, as, &RDW);
code2 = jbig2_arith_int_decode(params->IARDH, as, &RDH);
code3 = jbig2_arith_int_decode(params->IARDX, as, &RDX);
code4 = jbig2_arith_int_decode(params->IARDY, as, &RDY);
} else {
RDW = jbig2_huffman_get(hs, params->SBHUFFRDW, &code1);
RDH = jbig2_huffman_get(hs, params->SBHUFFRDH, &code2);
RDX = jbig2_huffman_get(hs, params->SBHUFFRDX, &code3);
RDY = jbig2_huffman_get(hs, params->SBHUFFRDY, &code4);
BMSIZE = jbig2_huffman_get(hs, params->SBHUFFRSIZE, &code5);
jbig2_huffman_skip(hs);
}
if ((code1 < 0) || (code2 < 0) || (code3 < 0) || (code4 < 0) || (code5 < 0)) {
code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to decode data");
goto cleanup2;
}
/* 6.4.11 (6) */
IBO = IB;
refimage = jbig2_image_new(ctx, IBO->width + RDW, IBO->height + RDH);
if (refimage == NULL) {
jbig2_image_release(ctx, IBO);
if (params->SBHUFF) {
jbig2_release_huffman_table(ctx, SBSYMCODES);
}
return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "couldn't allocate reference image");
}
jbig2_image_clear(ctx, refimage, 0x00);
/* Table 12 */
rparams.GRTEMPLATE = params->SBRTEMPLATE;
rparams.reference = IBO;
rparams.DX = (RDW >> 1) + RDX;
rparams.DY = (RDH >> 1) + RDY;
rparams.TPGRON = 0;
memcpy(rparams.grat, params->sbrat, 4);
code = jbig2_decode_refinement_region(ctx, segment, &rparams, as, refimage, GR_stats);
if (code < 0) {
jbig2_image_release(ctx, refimage);
goto cleanup2;
}
IB = refimage;
jbig2_image_release(ctx, IBO);
/* 6.4.11 (7) */
if (params->SBHUFF) {
jbig2_huffman_advance(hs, BMSIZE);
}
}
/* (3c.vi) */
if ((!params->TRANSPOSED) && (params->REFCORNER > 1)) {
CURS += IB->width - 1;
} else if ((params->TRANSPOSED) && !(params->REFCORNER & 1)) {
CURS += IB->height - 1;
}
/* (3c.vii) */
S = CURS;
/* (3c.viii) */
if (!params->TRANSPOSED) {
switch (params->REFCORNER) {
case JBIG2_CORNER_TOPLEFT:
x = S;
y = T;
break;
case JBIG2_CORNER_TOPRIGHT:
x = S - IB->width + 1;
y = T;
break;
case JBIG2_CORNER_BOTTOMLEFT:
x = S;
y = T - IB->height + 1;
break;
default:
case JBIG2_CORNER_BOTTOMRIGHT:
x = S - IB->width + 1;
y = T - IB->height + 1;
break;
}
} else { /* TRANSPOSED */
switch (params->REFCORNER) {
case JBIG2_CORNER_TOPLEFT:
x = T;
y = S;
break;
case JBIG2_CORNER_TOPRIGHT:
x = T - IB->width + 1;
y = S;
break;
case JBIG2_CORNER_BOTTOMLEFT:
x = T;
y = S - IB->height + 1;
break;
default:
case JBIG2_CORNER_BOTTOMRIGHT:
x = T - IB->width + 1;
y = S - IB->height + 1;
break;
}
}
/* (3c.ix) */
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number,
"composing glyph id %d: %dx%d @ (%d,%d) symbol %d/%d", ID, IB->width, IB->height, x, y, NINSTANCES + 1, params->SBNUMINSTANCES);
#endif
code = jbig2_image_compose(ctx, image, IB, x, y, params->SBCOMBOP);
if (code < 0) {
jbig2_image_release(ctx, IB);
goto cleanup2;
}
/* (3c.x) */
if ((!params->TRANSPOSED) && (params->REFCORNER < 2)) {
CURS += IB->width - 1;
} else if ((params->TRANSPOSED) && (params->REFCORNER & 1)) {
CURS += IB->height - 1;
}
/* (3c.xi) */
NINSTANCES++;
jbig2_image_release(ctx, IB);
}
/* end strip */
}
/* 6.4.5 (4) */
cleanup2:
if (params->SBHUFF) {
jbig2_release_huffman_table(ctx, SBSYMCODES);
}
jbig2_huffman_free(ctx, hs);
return code;
}
| 165,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: mojo::ScopedSharedBufferHandle GamepadProvider::GetSharedBufferHandle() {
base::SharedMemoryHandle handle = base::SharedMemory::DuplicateHandle(
gamepad_shared_buffer_->shared_memory()->handle());
return mojo::WrapSharedMemoryHandle(handle, sizeof(GamepadHardwareBuffer),
true /* read_only */);
}
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787 | mojo::ScopedSharedBufferHandle GamepadProvider::GetSharedBufferHandle() {
return mojo::WrapSharedMemoryHandle(
gamepad_shared_buffer_->shared_memory()->GetReadOnlyHandle(),
sizeof(GamepadHardwareBuffer),
mojo::UnwrappedSharedMemoryHandleProtection::kReadOnly);
}
| 172,867 |
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 sum_init(int csum_type, int seed)
{
char s[4];
if (csum_type < 0)
csum_type = parse_csum_name(NULL, 0);
cursum_type = csum_type;
switch (csum_type) {
case CSUM_MD5:
md5_begin(&md);
break;
case CSUM_MD4:
mdfour_begin(&md);
sumresidue = 0;
break;
case CSUM_MD4_OLD:
break;
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
mdfour_begin(&md);
sumresidue = 0;
SIVAL(s, 0, seed);
break;
}
}
Commit Message:
CWE ID: CWE-354 | void sum_init(int csum_type, int seed)
{
char s[4];
if (csum_type < 0)
csum_type = parse_csum_name(NULL, 0);
cursum_type = csum_type;
switch (csum_type) {
case CSUM_MD5:
md5_begin(&md);
break;
case CSUM_MD4:
mdfour_begin(&md);
sumresidue = 0;
break;
case CSUM_MD4_OLD:
break;
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
case CSUM_MD4_ARCHAIC:
mdfour_begin(&md);
sumresidue = 0;
SIVAL(s, 0, seed);
break;
}
}
| 164,646 |
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: do_decrypt (const RIJNDAEL_context *ctx, unsigned char *bx,
const unsigned char *ax)
{
#ifdef USE_AMD64_ASM
return _gcry_aes_amd64_decrypt_block(ctx->keyschdec, bx, ax, ctx->rounds,
&dec_tables);
#elif defined(USE_ARM_ASM)
return _gcry_aes_arm_decrypt_block(ctx->keyschdec, bx, ax, ctx->rounds,
&dec_tables);
#else
return do_decrypt_fn (ctx, bx, ax);
#endif /*!USE_ARM_ASM && !USE_AMD64_ASM*/
}
Commit Message: AES: move look-up tables to .data section and unshare between processes
* cipher/rijndael-internal.h (ATTR_ALIGNED_64): New.
* cipher/rijndael-tables.h (encT): Move to 'enc_tables' structure.
(enc_tables): New structure for encryption table with counters before
and after.
(encT): New macro.
(dec_tables): Add counters before and after encryption table; Move
from .rodata to .data section.
(do_encrypt): Change 'encT' to 'enc_tables.T'.
(do_decrypt): Change '&dec_tables' to 'dec_tables.T'.
* cipher/cipher-gcm.c (prefetch_table): Make inline; Handle input
with length not multiple of 256.
(prefetch_enc, prefetch_dec): Modify pre- and post-table counters
to unshare look-up table pages between processes.
--
GnuPG-bug-id: 4541
Signed-off-by: Jussi Kivilinna <[email protected]>
CWE ID: CWE-310 | do_decrypt (const RIJNDAEL_context *ctx, unsigned char *bx,
const unsigned char *ax)
{
#ifdef USE_AMD64_ASM
return _gcry_aes_amd64_decrypt_block(ctx->keyschdec, bx, ax, ctx->rounds,
dec_tables.T);
#elif defined(USE_ARM_ASM)
return _gcry_aes_arm_decrypt_block(ctx->keyschdec, bx, ax, ctx->rounds,
dec_tables.T);
#else
return do_decrypt_fn (ctx, bx, ax);
#endif /*!USE_ARM_ASM && !USE_AMD64_ASM*/
}
| 170,211 |
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 csum_len_for_type(int cst)
{
switch (cst) {
case CSUM_NONE:
return 1;
case CSUM_ARCHAIC:
return 2;
case CSUM_MD4:
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
return MD4_DIGEST_LEN;
case CSUM_MD5:
return MD5_DIGEST_LEN;
}
return 0;
}
Commit Message:
CWE ID: CWE-354 | int csum_len_for_type(int cst)
{
switch (cst) {
case CSUM_NONE:
return 1;
case CSUM_MD4_ARCHAIC:
return 2;
case CSUM_MD4:
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
return MD4_DIGEST_LEN;
case CSUM_MD5:
return MD5_DIGEST_LEN;
}
return 0;
}
| 164,642 |
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 WT_InterpolateNoLoop (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 phaseFrac;
EAS_I32 acc0;
const EAS_SAMPLE *pSamples;
EAS_I32 samp1;
EAS_I32 samp2;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
return;
}
pOutputBuffer = pWTIntFrame->pAudioBuffer;
phaseInc = pWTIntFrame->frame.phaseIncrement;
pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum;
phaseFrac = (EAS_I32)pWTVoice->phaseFrac;
/* fetch adjacent samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
while (numSamples--) {
/* linear interpolation */
acc0 = samp2 - samp1;
acc0 = acc0 * phaseFrac;
/*lint -e{704} <avoid divide>*/
acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS);
/* save new output sample in buffer */
/*lint -e{704} <avoid divide>*/
*pOutputBuffer++ = (EAS_I16)(acc0 >> 2);
/* increment phase */
phaseFrac += phaseInc;
/*lint -e{704} <avoid divide>*/
acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS;
/* next sample */
if (acc0 > 0) {
/* advance sample pointer */
pSamples += acc0;
phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK);
/* fetch new samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
}
}
/* save pointer and phase */
pWTVoice->phaseAccum = (EAS_U32) pSamples;
pWTVoice->phaseFrac = (EAS_U32) phaseFrac;
}
Commit Message: Sonivox: add SafetyNet log.
Bug: 26366256
Change-Id: Ief72e01b7cc6d87a015105af847a99d3d9b03cb0
CWE ID: CWE-119 | void WT_InterpolateNoLoop (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 phaseFrac;
EAS_I32 acc0;
const EAS_SAMPLE *pSamples;
EAS_I32 samp1;
EAS_I32 samp2;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
android_errorWriteLog(0x534e4554, "26366256");
return;
}
pOutputBuffer = pWTIntFrame->pAudioBuffer;
phaseInc = pWTIntFrame->frame.phaseIncrement;
pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum;
phaseFrac = (EAS_I32)pWTVoice->phaseFrac;
/* fetch adjacent samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
while (numSamples--) {
/* linear interpolation */
acc0 = samp2 - samp1;
acc0 = acc0 * phaseFrac;
/*lint -e{704} <avoid divide>*/
acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS);
/* save new output sample in buffer */
/*lint -e{704} <avoid divide>*/
*pOutputBuffer++ = (EAS_I16)(acc0 >> 2);
/* increment phase */
phaseFrac += phaseInc;
/*lint -e{704} <avoid divide>*/
acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS;
/* next sample */
if (acc0 > 0) {
/* advance sample pointer */
pSamples += acc0;
phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK);
/* fetch new samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
}
}
/* save pointer and phase */
pWTVoice->phaseAccum = (EAS_U32) pSamples;
pWTVoice->phaseFrac = (EAS_U32) phaseFrac;
}
| 174,603 |
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 qeth_snmp_command(struct qeth_card *card, char __user *udata)
{
struct qeth_cmd_buffer *iob;
struct qeth_ipa_cmd *cmd;
struct qeth_snmp_ureq *ureq;
int req_len;
struct qeth_arp_query_info qinfo = {0, };
int rc = 0;
QETH_CARD_TEXT(card, 3, "snmpcmd");
if (card->info.guestlan)
return -EOPNOTSUPP;
if ((!qeth_adp_supported(card, IPA_SETADP_SET_SNMP_CONTROL)) &&
(!card->options.layer2)) {
return -EOPNOTSUPP;
}
/* skip 4 bytes (data_len struct member) to get req_len */
if (copy_from_user(&req_len, udata + sizeof(int), sizeof(int)))
return -EFAULT;
ureq = memdup_user(udata, req_len + sizeof(struct qeth_snmp_ureq_hdr));
if (IS_ERR(ureq)) {
QETH_CARD_TEXT(card, 2, "snmpnome");
return PTR_ERR(ureq);
}
qinfo.udata_len = ureq->hdr.data_len;
qinfo.udata = kzalloc(qinfo.udata_len, GFP_KERNEL);
if (!qinfo.udata) {
kfree(ureq);
return -ENOMEM;
}
qinfo.udata_offset = sizeof(struct qeth_snmp_ureq_hdr);
iob = qeth_get_adapter_cmd(card, IPA_SETADP_SET_SNMP_CONTROL,
QETH_SNMP_SETADP_CMDLENGTH + req_len);
cmd = (struct qeth_ipa_cmd *)(iob->data+IPA_PDU_HEADER_SIZE);
memcpy(&cmd->data.setadapterparms.data.snmp, &ureq->cmd, req_len);
rc = qeth_send_ipa_snmp_cmd(card, iob, QETH_SETADP_BASE_LEN + req_len,
qeth_snmp_command_cb, (void *)&qinfo);
if (rc)
QETH_DBF_MESSAGE(2, "SNMP command failed on %s: (0x%x)\n",
QETH_CARD_IFNAME(card), rc);
else {
if (copy_to_user(udata, qinfo.udata, qinfo.udata_len))
rc = -EFAULT;
}
kfree(ureq);
kfree(qinfo.udata);
return rc;
}
Commit Message: qeth: avoid buffer overflow in snmp ioctl
Check user-defined length in snmp ioctl request and allow request
only if it fits into a qeth command buffer.
Signed-off-by: Ursula Braun <[email protected]>
Signed-off-by: Frank Blaschka <[email protected]>
Reviewed-by: Heiko Carstens <[email protected]>
Reported-by: Nico Golde <[email protected]>
Reported-by: Fabian Yamaguchi <[email protected]>
Cc: <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | int qeth_snmp_command(struct qeth_card *card, char __user *udata)
{
struct qeth_cmd_buffer *iob;
struct qeth_ipa_cmd *cmd;
struct qeth_snmp_ureq *ureq;
unsigned int req_len;
struct qeth_arp_query_info qinfo = {0, };
int rc = 0;
QETH_CARD_TEXT(card, 3, "snmpcmd");
if (card->info.guestlan)
return -EOPNOTSUPP;
if ((!qeth_adp_supported(card, IPA_SETADP_SET_SNMP_CONTROL)) &&
(!card->options.layer2)) {
return -EOPNOTSUPP;
}
/* skip 4 bytes (data_len struct member) to get req_len */
if (copy_from_user(&req_len, udata + sizeof(int), sizeof(int)))
return -EFAULT;
if (req_len > (QETH_BUFSIZE - IPA_PDU_HEADER_SIZE -
sizeof(struct qeth_ipacmd_hdr) -
sizeof(struct qeth_ipacmd_setadpparms_hdr)))
return -EINVAL;
ureq = memdup_user(udata, req_len + sizeof(struct qeth_snmp_ureq_hdr));
if (IS_ERR(ureq)) {
QETH_CARD_TEXT(card, 2, "snmpnome");
return PTR_ERR(ureq);
}
qinfo.udata_len = ureq->hdr.data_len;
qinfo.udata = kzalloc(qinfo.udata_len, GFP_KERNEL);
if (!qinfo.udata) {
kfree(ureq);
return -ENOMEM;
}
qinfo.udata_offset = sizeof(struct qeth_snmp_ureq_hdr);
iob = qeth_get_adapter_cmd(card, IPA_SETADP_SET_SNMP_CONTROL,
QETH_SNMP_SETADP_CMDLENGTH + req_len);
cmd = (struct qeth_ipa_cmd *)(iob->data+IPA_PDU_HEADER_SIZE);
memcpy(&cmd->data.setadapterparms.data.snmp, &ureq->cmd, req_len);
rc = qeth_send_ipa_snmp_cmd(card, iob, QETH_SETADP_BASE_LEN + req_len,
qeth_snmp_command_cb, (void *)&qinfo);
if (rc)
QETH_DBF_MESSAGE(2, "SNMP command failed on %s: (0x%x)\n",
QETH_CARD_IFNAME(card), rc);
else {
if (copy_to_user(udata, qinfo.udata, qinfo.udata_len))
rc = -EFAULT;
}
kfree(ureq);
kfree(qinfo.udata);
return rc;
}
| 165,940 |
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 sctp_generate_heartbeat_event(unsigned long data)
{
int error = 0;
struct sctp_transport *transport = (struct sctp_transport *) data;
struct sctp_association *asoc = transport->asoc;
struct net *net = sock_net(asoc->base.sk);
bh_lock_sock(asoc->base.sk);
if (sock_owned_by_user(asoc->base.sk)) {
pr_debug("%s: sock is busy\n", __func__);
/* Try again later. */
if (!mod_timer(&transport->hb_timer, jiffies + (HZ/20)))
sctp_transport_hold(transport);
goto out_unlock;
}
/* Is this structure just waiting around for us to actually
* get destroyed?
*/
if (transport->dead)
goto out_unlock;
error = sctp_do_sm(net, SCTP_EVENT_T_TIMEOUT,
SCTP_ST_TIMEOUT(SCTP_EVENT_TIMEOUT_HEARTBEAT),
asoc->state, asoc->ep, asoc,
transport, GFP_ATOMIC);
if (error)
asoc->base.sk->sk_err = -error;
out_unlock:
bh_unlock_sock(asoc->base.sk);
sctp_transport_put(transport);
}
Commit Message: sctp: Prevent soft lockup when sctp_accept() is called during a timeout event
A case can occur when sctp_accept() is called by the user during
a heartbeat timeout event after the 4-way handshake. Since
sctp_assoc_migrate() changes both assoc->base.sk and assoc->ep, the
bh_sock_lock in sctp_generate_heartbeat_event() will be taken with
the listening socket but released with the new association socket.
The result is a deadlock on any future attempts to take the listening
socket lock.
Note that this race can occur with other SCTP timeouts that take
the bh_lock_sock() in the event sctp_accept() is called.
BUG: soft lockup - CPU#9 stuck for 67s! [swapper:0]
...
RIP: 0010:[<ffffffff8152d48e>] [<ffffffff8152d48e>] _spin_lock+0x1e/0x30
RSP: 0018:ffff880028323b20 EFLAGS: 00000206
RAX: 0000000000000002 RBX: ffff880028323b20 RCX: 0000000000000000
RDX: 0000000000000000 RSI: ffff880028323be0 RDI: ffff8804632c4b48
RBP: ffffffff8100bb93 R08: 0000000000000000 R09: 0000000000000000
R10: ffff880610662280 R11: 0000000000000100 R12: ffff880028323aa0
R13: ffff8804383c3880 R14: ffff880028323a90 R15: ffffffff81534225
FS: 0000000000000000(0000) GS:ffff880028320000(0000) knlGS:0000000000000000
CS: 0010 DS: 0018 ES: 0018 CR0: 000000008005003b
CR2: 00000000006df528 CR3: 0000000001a85000 CR4: 00000000000006e0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
Process swapper (pid: 0, threadinfo ffff880616b70000, task ffff880616b6cab0)
Stack:
ffff880028323c40 ffffffffa01c2582 ffff880614cfb020 0000000000000000
<d> 0100000000000000 00000014383a6c44 ffff8804383c3880 ffff880614e93c00
<d> ffff880614e93c00 0000000000000000 ffff8804632c4b00 ffff8804383c38b8
Call Trace:
<IRQ>
[<ffffffffa01c2582>] ? sctp_rcv+0x492/0xa10 [sctp]
[<ffffffff8148c559>] ? nf_iterate+0x69/0xb0
[<ffffffff814974a0>] ? ip_local_deliver_finish+0x0/0x2d0
[<ffffffff8148c716>] ? nf_hook_slow+0x76/0x120
[<ffffffff814974a0>] ? ip_local_deliver_finish+0x0/0x2d0
[<ffffffff8149757d>] ? ip_local_deliver_finish+0xdd/0x2d0
[<ffffffff81497808>] ? ip_local_deliver+0x98/0xa0
[<ffffffff81496ccd>] ? ip_rcv_finish+0x12d/0x440
[<ffffffff81497255>] ? ip_rcv+0x275/0x350
[<ffffffff8145cfeb>] ? __netif_receive_skb+0x4ab/0x750
...
With lockdep debugging:
=====================================
[ BUG: bad unlock balance detected! ]
-------------------------------------
CslRx/12087 is trying to release lock (slock-AF_INET) at:
[<ffffffffa01bcae0>] sctp_generate_timeout_event+0x40/0xe0 [sctp]
but there are no more locks to release!
other info that might help us debug this:
2 locks held by CslRx/12087:
#0: (&asoc->timers[i]){+.-...}, at: [<ffffffff8108ce1f>] run_timer_softirq+0x16f/0x3e0
#1: (slock-AF_INET){+.-...}, at: [<ffffffffa01bcac3>] sctp_generate_timeout_event+0x23/0xe0 [sctp]
Ensure the socket taken is also the same one that is released by
saving a copy of the socket before entering the timeout event
critical section.
Signed-off-by: Karl Heiss <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | void sctp_generate_heartbeat_event(unsigned long data)
{
int error = 0;
struct sctp_transport *transport = (struct sctp_transport *) data;
struct sctp_association *asoc = transport->asoc;
struct sock *sk = asoc->base.sk;
struct net *net = sock_net(sk);
bh_lock_sock(sk);
if (sock_owned_by_user(sk)) {
pr_debug("%s: sock is busy\n", __func__);
/* Try again later. */
if (!mod_timer(&transport->hb_timer, jiffies + (HZ/20)))
sctp_transport_hold(transport);
goto out_unlock;
}
/* Is this structure just waiting around for us to actually
* get destroyed?
*/
if (transport->dead)
goto out_unlock;
error = sctp_do_sm(net, SCTP_EVENT_T_TIMEOUT,
SCTP_ST_TIMEOUT(SCTP_EVENT_TIMEOUT_HEARTBEAT),
asoc->state, asoc->ep, asoc,
transport, GFP_ATOMIC);
if (error)
sk->sk_err = -error;
out_unlock:
bh_unlock_sock(sk);
sctp_transport_put(transport);
}
| 167,500 |
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 Cues::Init() const
{
if (m_cue_points)
return;
assert(m_count == 0);
assert(m_preload_count == 0);
IMkvReader* const pReader = m_pSegment->m_pReader;
const long long stop = m_start + m_size;
long long pos = m_start;
long cue_points_size = 0;
while (pos < stop)
{
const long long idpos = pos;
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); //TODO
assert((pos + len) <= stop);
pos += len; //consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; //consume Size field
assert((pos + size) <= stop);
if (id == 0x3B) //CuePoint ID
PreloadCuePoint(cue_points_size, idpos);
pos += size; //consume payload
assert(pos <= stop);
}
}
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 | void Cues::Init() const
long len;
const long long id = ReadUInt(pReader, m_pos, len);
assert(id >= 0); // TODO
assert((m_pos + len) <= stop);
m_pos += len; // consume ID
const long long size = ReadUInt(pReader, m_pos, len);
assert(size >= 0);
assert((m_pos + len) <= stop);
m_pos += len; // consume Size field
assert((m_pos + size) <= stop);
if (id != 0x3B) { // CuePoint ID
m_pos += size; // consume payload
assert(m_pos <= stop);
| 174,390 |
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: userauth_gssapi(struct ssh *ssh)
{
Authctxt *authctxt = ssh->authctxt;
gss_OID_desc goid = {0, NULL};
Gssctxt *ctxt = NULL;
int r, present;
u_int mechs;
OM_uint32 ms;
size_t len;
u_char *doid = NULL;
if (!authctxt->valid || authctxt->user == NULL)
return (0);
if ((r = sshpkt_get_u32(ssh, &mechs)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
if (mechs == 0) {
debug("Mechanism negotiation is not supported");
return (0);
}
do {
mechs--;
free(doid);
present = 0;
if ((r = sshpkt_get_string(ssh, &doid, &len)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
if (len > 2 && doid[0] == SSH_GSS_OIDTYPE &&
doid[1] == len - 2) {
goid.elements = doid + 2;
goid.length = len - 2;
ssh_gssapi_test_oid_supported(&ms, &goid, &present);
} else {
logit("Badly formed OID received");
}
} while (mechs > 0 && !present);
if (!present) {
free(doid);
authctxt->server_caused_failure = 1;
return (0);
}
if (GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctxt, &goid)))) {
if (ctxt != NULL)
ssh_gssapi_delete_ctx(&ctxt);
free(doid);
authctxt->server_caused_failure = 1;
return (0);
}
authctxt->methoddata = (void *)ctxt;
/* Return the OID that we received */
if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_GSSAPI_RESPONSE)) != 0 ||
(r = sshpkt_put_string(ssh, doid, len)) != 0 ||
(r = sshpkt_send(ssh)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
free(doid);
ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
authctxt->postponed = 1;
return (0);
}
Commit Message: delay bailout for invalid authenticating user until after the packet
containing the request has been fully parsed. Reported by Dariusz Tytko
and Michał Sajdak; ok deraadt
CWE ID: CWE-200 | userauth_gssapi(struct ssh *ssh)
{
Authctxt *authctxt = ssh->authctxt;
gss_OID_desc goid = {0, NULL};
Gssctxt *ctxt = NULL;
int r, present;
u_int mechs;
OM_uint32 ms;
size_t len;
u_char *doid = NULL;
if ((r = sshpkt_get_u32(ssh, &mechs)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
if (mechs == 0) {
debug("Mechanism negotiation is not supported");
return (0);
}
do {
mechs--;
free(doid);
present = 0;
if ((r = sshpkt_get_string(ssh, &doid, &len)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
if (len > 2 && doid[0] == SSH_GSS_OIDTYPE &&
doid[1] == len - 2) {
goid.elements = doid + 2;
goid.length = len - 2;
ssh_gssapi_test_oid_supported(&ms, &goid, &present);
} else {
logit("Badly formed OID received");
}
} while (mechs > 0 && !present);
if (!present) {
free(doid);
authctxt->server_caused_failure = 1;
return (0);
}
if (!authctxt->valid || authctxt->user == NULL) {
debug2("%s: disabled because of invalid user", __func__);
free(doid);
return (0);
}
if (GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctxt, &goid)))) {
if (ctxt != NULL)
ssh_gssapi_delete_ctx(&ctxt);
free(doid);
authctxt->server_caused_failure = 1;
return (0);
}
authctxt->methoddata = (void *)ctxt;
/* Return the OID that we received */
if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_GSSAPI_RESPONSE)) != 0 ||
(r = sshpkt_put_string(ssh, doid, len)) != 0 ||
(r = sshpkt_send(ssh)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
free(doid);
ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
authctxt->postponed = 1;
return (0);
}
| 169,104 |
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: MediaMetadataRetriever::MediaMetadataRetriever()
{
ALOGV("constructor");
const sp<IMediaPlayerService>& service(getService());
if (service == 0) {
ALOGE("failed to obtain MediaMetadataRetrieverService");
return;
}
sp<IMediaMetadataRetriever> retriever(service->createMetadataRetriever());
if (retriever == 0) {
ALOGE("failed to create IMediaMetadataRetriever object from server");
}
mRetriever = retriever;
}
Commit Message: Get service by value instead of reference
to prevent a cleared service binder from being used.
Bug: 26040840
Change-Id: Ifb5483c55b172d3553deb80dbe27f2204b86ecdb
CWE ID: CWE-119 | MediaMetadataRetriever::MediaMetadataRetriever()
{
ALOGV("constructor");
const sp<IMediaPlayerService> service(getService());
if (service == 0) {
ALOGE("failed to obtain MediaMetadataRetrieverService");
return;
}
sp<IMediaMetadataRetriever> retriever(service->createMetadataRetriever());
if (retriever == 0) {
ALOGE("failed to create IMediaMetadataRetriever object from server");
}
mRetriever = retriever;
}
| 173,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: static int read_entry(
git_index_entry **out,
size_t *out_size,
git_index *index,
const void *buffer,
size_t buffer_size,
const char *last)
{
size_t path_length, entry_size;
const char *path_ptr;
struct entry_short source;
git_index_entry entry = {{0}};
bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP;
char *tmp_path = NULL;
if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size)
return -1;
/* buffer is not guaranteed to be aligned */
memcpy(&source, buffer, sizeof(struct entry_short));
entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds);
entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds);
entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds);
entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds);
entry.dev = ntohl(source.dev);
entry.ino = ntohl(source.ino);
entry.mode = ntohl(source.mode);
entry.uid = ntohl(source.uid);
entry.gid = ntohl(source.gid);
entry.file_size = ntohl(source.file_size);
git_oid_cpy(&entry.id, &source.oid);
entry.flags = ntohs(source.flags);
if (entry.flags & GIT_IDXENTRY_EXTENDED) {
uint16_t flags_raw;
size_t flags_offset;
flags_offset = offsetof(struct entry_long, flags_extended);
memcpy(&flags_raw, (const char *) buffer + flags_offset,
sizeof(flags_raw));
flags_raw = ntohs(flags_raw);
memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw));
path_ptr = (const char *) buffer + offsetof(struct entry_long, path);
} else
path_ptr = (const char *) buffer + offsetof(struct entry_short, path);
if (!compressed) {
path_length = entry.flags & GIT_IDXENTRY_NAMEMASK;
/* if this is a very long string, we must find its
* real length without overflowing */
if (path_length == 0xFFF) {
const char *path_end;
path_end = memchr(path_ptr, '\0', buffer_size);
if (path_end == NULL)
return -1;
path_length = path_end - path_ptr;
}
entry_size = index_entry_size(path_length, 0, entry.flags);
entry.path = (char *)path_ptr;
} else {
size_t varint_len, last_len, prefix_len, suffix_len, path_len;
uintmax_t strip_len;
strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len);
last_len = strlen(last);
if (varint_len == 0 || last_len < strip_len)
return index_error_invalid("incorrect prefix length");
prefix_len = last_len - strip_len;
suffix_len = strlen(path_ptr + varint_len);
GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len);
GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1);
tmp_path = git__malloc(path_len);
GITERR_CHECK_ALLOC(tmp_path);
memcpy(tmp_path, last, prefix_len);
memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1);
entry_size = index_entry_size(suffix_len, varint_len, entry.flags);
entry.path = tmp_path;
}
if (entry_size == 0)
return -1;
if (INDEX_FOOTER_SIZE + entry_size > buffer_size)
return -1;
if (index_entry_dup(out, index, &entry) < 0) {
git__free(tmp_path);
return -1;
}
git__free(tmp_path);
*out_size = entry_size;
return 0;
}
Commit Message: index: error out on unreasonable prefix-compressed path lengths
When computing the complete path length from the encoded
prefix-compressed path, we end up just allocating the complete path
without ever checking what the encoded path length actually is. This can
easily lead to a denial of service by just encoding an unreasonable long
path name inside of the index. Git already enforces a maximum path
length of 4096 bytes. As we also have that enforcement ready in some
places, just make sure that the resulting path is smaller than
GIT_PATH_MAX.
Reported-by: Krishna Ram Prakash R <[email protected]>
Reported-by: Vivek Parikh <[email protected]>
CWE ID: CWE-190 | static int read_entry(
git_index_entry **out,
size_t *out_size,
git_index *index,
const void *buffer,
size_t buffer_size,
const char *last)
{
size_t path_length, entry_size;
const char *path_ptr;
struct entry_short source;
git_index_entry entry = {{0}};
bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP;
char *tmp_path = NULL;
if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size)
return -1;
/* buffer is not guaranteed to be aligned */
memcpy(&source, buffer, sizeof(struct entry_short));
entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds);
entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds);
entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds);
entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds);
entry.dev = ntohl(source.dev);
entry.ino = ntohl(source.ino);
entry.mode = ntohl(source.mode);
entry.uid = ntohl(source.uid);
entry.gid = ntohl(source.gid);
entry.file_size = ntohl(source.file_size);
git_oid_cpy(&entry.id, &source.oid);
entry.flags = ntohs(source.flags);
if (entry.flags & GIT_IDXENTRY_EXTENDED) {
uint16_t flags_raw;
size_t flags_offset;
flags_offset = offsetof(struct entry_long, flags_extended);
memcpy(&flags_raw, (const char *) buffer + flags_offset,
sizeof(flags_raw));
flags_raw = ntohs(flags_raw);
memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw));
path_ptr = (const char *) buffer + offsetof(struct entry_long, path);
} else
path_ptr = (const char *) buffer + offsetof(struct entry_short, path);
if (!compressed) {
path_length = entry.flags & GIT_IDXENTRY_NAMEMASK;
/* if this is a very long string, we must find its
* real length without overflowing */
if (path_length == 0xFFF) {
const char *path_end;
path_end = memchr(path_ptr, '\0', buffer_size);
if (path_end == NULL)
return -1;
path_length = path_end - path_ptr;
}
entry_size = index_entry_size(path_length, 0, entry.flags);
entry.path = (char *)path_ptr;
} else {
size_t varint_len, last_len, prefix_len, suffix_len, path_len;
uintmax_t strip_len;
strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len);
last_len = strlen(last);
if (varint_len == 0 || last_len < strip_len)
return index_error_invalid("incorrect prefix length");
prefix_len = last_len - strip_len;
suffix_len = strlen(path_ptr + varint_len);
GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len);
GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1);
if (path_len > GIT_PATH_MAX)
return index_error_invalid("unreasonable path length");
tmp_path = git__malloc(path_len);
GITERR_CHECK_ALLOC(tmp_path);
memcpy(tmp_path, last, prefix_len);
memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1);
entry_size = index_entry_size(suffix_len, varint_len, entry.flags);
entry.path = tmp_path;
}
if (entry_size == 0)
return -1;
if (INDEX_FOOTER_SIZE + entry_size > buffer_size)
return -1;
if (index_entry_dup(out, index, &entry) < 0) {
git__free(tmp_path);
return -1;
}
git__free(tmp_path);
*out_size = entry_size;
return 0;
}
| 170,171 |
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: URLFetcher* FakeURLFetcherFactory::CreateURLFetcher(
int id,
const GURL& url,
URLFetcher::RequestType request_type,
URLFetcher::Delegate* d) {
FakeResponseMap::const_iterator it = fake_responses_.find(url);
if (it == fake_responses_.end()) {
DLOG(ERROR) << "No baked response for URL: " << url.spec();
return NULL;
}
return new FakeURLFetcher(url, request_type, d,
it->second.first, it->second.second);
}
Commit Message: Use URLFetcher::Create instead of new in http_bridge.cc.
This change modified http_bridge so that it uses a factory to construct
the URLFetcher. Moreover, it modified sync_backend_host_unittest.cc to
use an URLFetcher factory which will prevent access to www.example.com during
the test.
BUG=none
TEST=sync_backend_host_unittest.cc
Review URL: http://codereview.chromium.org/7053011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87227 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | URLFetcher* FakeURLFetcherFactory::CreateURLFetcher(
int id,
const GURL& url,
URLFetcher::RequestType request_type,
URLFetcher::Delegate* d) {
FakeResponseMap::const_iterator it = fake_responses_.find(url);
if (it == fake_responses_.end()) {
if (default_factory_ == NULL) {
// If we don't have a baked response for that URL we return NULL.
DLOG(ERROR) << "No baked response for URL: " << url.spec();
return NULL;
} else {
return default_factory_->CreateURLFetcher(id, url, request_type, d);
}
}
return new FakeURLFetcher(url, request_type, d,
it->second.first, it->second.second);
}
| 170,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: SPL_METHOD(RecursiveDirectoryIterator, getSubPathname)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *sub_name;
int len;
char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (intern->u.dir.sub_path) {
len = spprintf(&sub_name, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name);
RETURN_STRINGL(sub_name, len, 0);
} else {
RETURN_STRING(intern->u.dir.entry.d_name, 1);
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(RecursiveDirectoryIterator, getSubPathname)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *sub_name;
int len;
char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (intern->u.dir.sub_path) {
len = spprintf(&sub_name, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name);
RETURN_STRINGL(sub_name, len, 0);
} else {
RETURN_STRING(intern->u.dir.entry.d_name, 1);
}
}
| 167,047 |
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: parse_cosine_rec_hdr(struct wtap_pkthdr *phdr, const char *line,
int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
int num_items_scanned;
int yy, mm, dd, hr, min, sec, csec, pkt_len;
int pro, off, pri, rm, error;
guint code1, code2;
char if_name[COSINE_MAX_IF_NAME_LEN] = "", direction[6] = "";
struct tm tm;
if (sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d:",
&yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) {
/* appears to be output to a control blade */
num_items_scanned = sscanf(line,
"%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]",
&yy, &mm, &dd, &hr, &min, &sec, &csec,
direction, if_name, &pkt_len,
&pro, &off, &pri, &rm, &error,
&code1, &code2);
if (num_items_scanned != 17) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: purported control blade line doesn't have code values");
return -1;
}
} else {
/* appears to be output to PE */
num_items_scanned = sscanf(line,
"%5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]",
direction, if_name, &pkt_len,
&pro, &off, &pri, &rm, &error,
&code1, &code2);
if (num_items_scanned != 10) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: header line is neither control blade nor PE output");
return -1;
}
yy = mm = dd = hr = min = sec = csec = 0;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
tm.tm_year = yy - 1900;
tm.tm_mon = mm - 1;
tm.tm_mday = dd;
tm.tm_hour = hr;
tm.tm_min = min;
tm.tm_sec = sec;
tm.tm_isdst = -1;
phdr->ts.secs = mktime(&tm);
phdr->ts.nsecs = csec * 10000000;
phdr->len = pkt_len;
/* XXX need to handle other encapsulations like Cisco HDLC,
Frame Relay and ATM */
if (strncmp(if_name, "TEST:", 5) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_TEST;
} else if (strncmp(if_name, "PPoATM:", 7) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPoATM;
} else if (strncmp(if_name, "PPoFR:", 6) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPoFR;
} else if (strncmp(if_name, "ATM:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_ATM;
} else if (strncmp(if_name, "FR:", 3) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_FR;
} else if (strncmp(if_name, "HDLC:", 5) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_HDLC;
} else if (strncmp(if_name, "PPP:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPP;
} else if (strncmp(if_name, "ETH:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_ETH;
} else {
pseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN;
}
if (strncmp(direction, "l2-tx", 5) == 0) {
pseudo_header->cosine.direction = COSINE_DIR_TX;
} else if (strncmp(direction, "l2-rx", 5) == 0) {
pseudo_header->cosine.direction = COSINE_DIR_RX;
}
g_strlcpy(pseudo_header->cosine.if_name, if_name,
COSINE_MAX_IF_NAME_LEN);
pseudo_header->cosine.pro = pro;
pseudo_header->cosine.off = off;
pseudo_header->cosine.pri = pri;
pseudo_header->cosine.rm = rm;
pseudo_header->cosine.err = error;
return pkt_len;
}
Commit Message: Fix packet length handling.
Treat the packet length as unsigned - it shouldn't be negative in the
file. If it is, that'll probably cause the sscanf to fail, so we'll
report the file as bad.
Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to
allocate a huge amount of memory, just as we do in other file readers.
Use the now-validated packet size as the length in
ws_buffer_assure_space(), so we are certain to have enough space, and
don't allocate too much space.
Merge the header and packet data parsing routines while we're at it.
Bug: 12395
Change-Id: Ia70f33b71ff28451190fcf144c333fd1362646b2
Reviewed-on: https://code.wireshark.org/review/15172
Reviewed-by: Guy Harris <[email protected]>
CWE ID: CWE-119 | parse_cosine_rec_hdr(struct wtap_pkthdr *phdr, const char *line,
static gboolean
parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
char *line, int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
int num_items_scanned;
int yy, mm, dd, hr, min, sec, csec;
guint pkt_len;
int pro, off, pri, rm, error;
guint code1, code2;
char if_name[COSINE_MAX_IF_NAME_LEN] = "", direction[6] = "";
struct tm tm;
guint8 *pd;
int i, hex_lines, n, caplen = 0;
if (sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d:",
&yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) {
/* appears to be output to a control blade */
num_items_scanned = sscanf(line,
"%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]",
&yy, &mm, &dd, &hr, &min, &sec, &csec,
direction, if_name, &pkt_len,
&pro, &off, &pri, &rm, &error,
&code1, &code2);
if (num_items_scanned != 17) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: purported control blade line doesn't have code values");
return FALSE;
}
} else {
/* appears to be output to PE */
num_items_scanned = sscanf(line,
"%5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]",
direction, if_name, &pkt_len,
&pro, &off, &pri, &rm, &error,
&code1, &code2);
if (num_items_scanned != 10) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: header line is neither control blade nor PE output");
return FALSE;
}
yy = mm = dd = hr = min = sec = csec = 0;
}
if (pkt_len > WTAP_MAX_PACKET_SIZE) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup_printf("cosine: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
tm.tm_year = yy - 1900;
tm.tm_mon = mm - 1;
tm.tm_mday = dd;
tm.tm_hour = hr;
tm.tm_min = min;
tm.tm_sec = sec;
tm.tm_isdst = -1;
phdr->ts.secs = mktime(&tm);
phdr->ts.nsecs = csec * 10000000;
phdr->len = pkt_len;
/* XXX need to handle other encapsulations like Cisco HDLC,
Frame Relay and ATM */
if (strncmp(if_name, "TEST:", 5) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_TEST;
} else if (strncmp(if_name, "PPoATM:", 7) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPoATM;
} else if (strncmp(if_name, "PPoFR:", 6) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPoFR;
} else if (strncmp(if_name, "ATM:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_ATM;
} else if (strncmp(if_name, "FR:", 3) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_FR;
} else if (strncmp(if_name, "HDLC:", 5) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_HDLC;
} else if (strncmp(if_name, "PPP:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPP;
} else if (strncmp(if_name, "ETH:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_ETH;
} else {
pseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN;
}
if (strncmp(direction, "l2-tx", 5) == 0) {
pseudo_header->cosine.direction = COSINE_DIR_TX;
} else if (strncmp(direction, "l2-rx", 5) == 0) {
pseudo_header->cosine.direction = COSINE_DIR_RX;
}
g_strlcpy(pseudo_header->cosine.if_name, if_name,
COSINE_MAX_IF_NAME_LEN);
pseudo_header->cosine.pro = pro;
pseudo_header->cosine.off = off;
pseudo_header->cosine.pri = pri;
pseudo_header->cosine.rm = rm;
pseudo_header->cosine.err = error;
| 169,966 |
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: MagickExport Image *CloneImage(const Image *image,const size_t columns,
const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception)
{
Image
*clone_image;
double
scale;
size_t
length;
/*
Clone the image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if ((image->columns == 0) || (image->rows == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"NegativeOrZeroImageSize","`%s'",image->filename);
return((Image *) NULL);
}
clone_image=(Image *) AcquireMagickMemory(sizeof(*clone_image));
if (clone_image == (Image *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(clone_image,0,sizeof(*clone_image));
clone_image->signature=MagickCoreSignature;
clone_image->storage_class=image->storage_class;
clone_image->number_channels=image->number_channels;
clone_image->number_meta_channels=image->number_meta_channels;
clone_image->metacontent_extent=image->metacontent_extent;
clone_image->colorspace=image->colorspace;
clone_image->read_mask=image->read_mask;
clone_image->write_mask=image->write_mask;
clone_image->alpha_trait=image->alpha_trait;
clone_image->columns=image->columns;
clone_image->rows=image->rows;
clone_image->dither=image->dither;
if (image->colormap != (PixelInfo *) NULL)
{
/*
Allocate and copy the image colormap.
*/
clone_image->colors=image->colors;
length=(size_t) image->colors;
clone_image->colormap=(PixelInfo *) AcquireQuantumMemory(length,
sizeof(*clone_image->colormap));
if (clone_image->colormap == (PixelInfo *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
(void) CopyMagickMemory(clone_image->colormap,image->colormap,length*
sizeof(*clone_image->colormap));
}
clone_image->image_info=CloneImageInfo(image->image_info);
(void) CloneImageProfiles(clone_image,image);
(void) CloneImageProperties(clone_image,image);
(void) CloneImageArtifacts(clone_image,image);
GetTimerInfo(&clone_image->timer);
if (image->ascii85 != (void *) NULL)
Ascii85Initialize(clone_image);
clone_image->magick_columns=image->magick_columns;
clone_image->magick_rows=image->magick_rows;
clone_image->type=image->type;
clone_image->channel_mask=image->channel_mask;
clone_image->channel_map=ClonePixelChannelMap(image->channel_map);
(void) CopyMagickString(clone_image->magick_filename,image->magick_filename,
MagickPathExtent);
(void) CopyMagickString(clone_image->magick,image->magick,MagickPathExtent);
(void) CopyMagickString(clone_image->filename,image->filename,
MagickPathExtent);
clone_image->progress_monitor=image->progress_monitor;
clone_image->client_data=image->client_data;
clone_image->reference_count=1;
clone_image->next=image->next;
clone_image->previous=image->previous;
clone_image->list=NewImageList();
if (detach == MagickFalse)
clone_image->blob=ReferenceBlob(image->blob);
else
{
clone_image->next=NewImageList();
clone_image->previous=NewImageList();
clone_image->blob=CloneBlobInfo((BlobInfo *) NULL);
}
clone_image->ping=image->ping;
clone_image->debug=IsEventLogging();
clone_image->semaphore=AcquireSemaphoreInfo();
if ((columns == 0) || (rows == 0))
{
if (image->montage != (char *) NULL)
(void) CloneString(&clone_image->montage,image->montage);
if (image->directory != (char *) NULL)
(void) CloneString(&clone_image->directory,image->directory);
clone_image->cache=ReferencePixelCache(image->cache);
return(clone_image);
}
scale=1.0;
if (image->columns != 0)
scale=(double) columns/(double) image->columns;
clone_image->page.width=(size_t) floor(scale*image->page.width+0.5);
clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5);
clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5);
scale=1.0;
if (image->rows != 0)
scale=(double) rows/(double) image->rows;
clone_image->page.height=(size_t) floor(scale*image->page.height+0.5);
clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5);
clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5);
clone_image->columns=columns;
clone_image->rows=rows;
clone_image->cache=ClonePixelCache(image->cache);
return(clone_image);
}
Commit Message: Set pixel cache to undefined if any resource limit is exceeded
CWE ID: CWE-119 | MagickExport Image *CloneImage(const Image *image,const size_t columns,
const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception)
{
Image
*clone_image;
double
scale;
size_t
length;
/*
Clone the image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if ((image->columns == 0) || (image->rows == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"NegativeOrZeroImageSize","`%s'",image->filename);
return((Image *) NULL);
}
clone_image=(Image *) AcquireMagickMemory(sizeof(*clone_image));
if (clone_image == (Image *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(clone_image,0,sizeof(*clone_image));
clone_image->signature=MagickCoreSignature;
clone_image->storage_class=image->storage_class;
clone_image->number_channels=image->number_channels;
clone_image->number_meta_channels=image->number_meta_channels;
clone_image->metacontent_extent=image->metacontent_extent;
clone_image->colorspace=image->colorspace;
clone_image->read_mask=image->read_mask;
clone_image->write_mask=image->write_mask;
clone_image->alpha_trait=image->alpha_trait;
clone_image->columns=image->columns;
clone_image->rows=image->rows;
clone_image->dither=image->dither;
if (image->colormap != (PixelInfo *) NULL)
{
/*
Allocate and copy the image colormap.
*/
clone_image->colors=image->colors;
length=(size_t) image->colors;
clone_image->colormap=(PixelInfo *) AcquireQuantumMemory(length,
sizeof(*clone_image->colormap));
if (clone_image->colormap == (PixelInfo *) NULL)
{
clone_image=DestroyImage(clone_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickMemory(clone_image->colormap,image->colormap,length*
sizeof(*clone_image->colormap));
}
clone_image->image_info=CloneImageInfo(image->image_info);
(void) CloneImageProfiles(clone_image,image);
(void) CloneImageProperties(clone_image,image);
(void) CloneImageArtifacts(clone_image,image);
GetTimerInfo(&clone_image->timer);
if (image->ascii85 != (void *) NULL)
Ascii85Initialize(clone_image);
clone_image->magick_columns=image->magick_columns;
clone_image->magick_rows=image->magick_rows;
clone_image->type=image->type;
clone_image->channel_mask=image->channel_mask;
clone_image->channel_map=ClonePixelChannelMap(image->channel_map);
(void) CopyMagickString(clone_image->magick_filename,image->magick_filename,
MagickPathExtent);
(void) CopyMagickString(clone_image->magick,image->magick,MagickPathExtent);
(void) CopyMagickString(clone_image->filename,image->filename,
MagickPathExtent);
clone_image->progress_monitor=image->progress_monitor;
clone_image->client_data=image->client_data;
clone_image->reference_count=1;
clone_image->next=image->next;
clone_image->previous=image->previous;
clone_image->list=NewImageList();
if (detach == MagickFalse)
clone_image->blob=ReferenceBlob(image->blob);
else
{
clone_image->next=NewImageList();
clone_image->previous=NewImageList();
clone_image->blob=CloneBlobInfo((BlobInfo *) NULL);
}
clone_image->ping=image->ping;
clone_image->debug=IsEventLogging();
clone_image->semaphore=AcquireSemaphoreInfo();
if ((columns == 0) || (rows == 0))
{
if (image->montage != (char *) NULL)
(void) CloneString(&clone_image->montage,image->montage);
if (image->directory != (char *) NULL)
(void) CloneString(&clone_image->directory,image->directory);
clone_image->cache=ReferencePixelCache(image->cache);
return(clone_image);
}
scale=1.0;
if (image->columns != 0)
scale=(double) columns/(double) image->columns;
clone_image->page.width=(size_t) floor(scale*image->page.width+0.5);
clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5);
clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5);
scale=1.0;
if (image->rows != 0)
scale=(double) rows/(double) image->rows;
clone_image->page.height=(size_t) floor(scale*image->page.height+0.5);
clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5);
clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5);
clone_image->columns=columns;
clone_image->rows=rows;
clone_image->cache=ClonePixelCache(image->cache);
return(clone_image);
}
| 169,960 |
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 Segment::DoLoadCluster(long long& pos, long& len) {
if (m_pos < 0)
return DoLoadClusterUnknownSize(pos, len);
long long total, avail;
long status = m_pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
long long cluster_off = -1; // offset relative to start of segment
long long cluster_size = -1; // size of cluster payload
for (;;) {
if ((total >= 0) && (m_pos >= total))
return 1; // no more clusters
if ((segment_stop >= 0) && (m_pos >= segment_stop))
return 1; // no more clusters
pos = m_pos;
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id < 0) // error (or underflow)
return static_cast<long>(id);
pos += len; // consume ID
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) // error
return static_cast<long>(size);
pos += len; // consume length of size of element
if (size == 0) { // weird
m_pos = pos;
continue;
}
const long long unknown_size = (1LL << (7 * len)) - 1;
#if 0 // we must handle this to support live webm
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; //TODO: allow this
#endif
if ((segment_stop >= 0) && (size != unknown_size) &&
((pos + size) > segment_stop)) {
return E_FILE_FORMAT_INVALID;
}
#if 0 // commented-out, to support incremental cluster parsing
len = static_cast<long>(size);
if ((pos + size) > avail)
return E_BUFFER_NOT_FULL;
#endif
if (id == 0x0C53BB6B) { // Cues ID
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; // TODO: liberalize
if (m_pCues == NULL) {
const long long element_size = (pos - idpos) + size;
m_pCues = new Cues(this, pos, size, idpos, element_size);
assert(m_pCues); // TODO
}
m_pos = pos + size; // consume payload
continue;
}
if (id != 0x0F43B675) { // Cluster ID
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; // TODO: liberalize
m_pos = pos + size; // consume payload
continue;
}
cluster_off = idpos - m_start; // relative pos
if (size != unknown_size)
cluster_size = size;
break;
}
assert(cluster_off >= 0); // have cluster
long long pos_;
long len_;
status = Cluster::HasBlockEntries(this, cluster_off, pos_, len_);
if (status < 0) { // error, or underflow
pos = pos_;
len = len_;
return status;
}
const long idx = m_clusterCount;
if (m_clusterPreloadCount > 0) {
assert(idx < m_clusterSize);
Cluster* const pCluster = m_clusters[idx];
assert(pCluster);
assert(pCluster->m_index < 0);
const long long off = pCluster->GetPosition();
assert(off >= 0);
if (off == cluster_off) { // preloaded already
if (status == 0) // no entries found
return E_FILE_FORMAT_INVALID;
if (cluster_size >= 0)
pos += cluster_size;
else {
const long long element_size = pCluster->GetElementSize();
if (element_size <= 0)
return E_FILE_FORMAT_INVALID; // TODO: handle this case
pos = pCluster->m_element_start + element_size;
}
pCluster->m_index = idx; // move from preloaded to loaded
++m_clusterCount;
--m_clusterPreloadCount;
m_pos = pos; // consume payload
assert((segment_stop < 0) || (m_pos <= segment_stop));
return 0; // success
}
}
if (status == 0) { // no entries found
if (cluster_size < 0)
return E_FILE_FORMAT_INVALID; // TODO: handle this
pos += cluster_size;
if ((total >= 0) && (pos >= total)) {
m_pos = total;
return 1; // no more clusters
}
if ((segment_stop >= 0) && (pos >= segment_stop)) {
m_pos = segment_stop;
return 1; // no more clusters
}
m_pos = pos;
return 2; // try again
}
Cluster* const pCluster = Cluster::Create(this, idx, cluster_off);
assert(pCluster);
AppendCluster(pCluster);
assert(m_clusters);
assert(idx < m_clusterSize);
assert(m_clusters[idx] == pCluster);
if (cluster_size >= 0) {
pos += cluster_size;
m_pos = pos;
assert((segment_stop < 0) || (m_pos <= segment_stop));
return 0;
}
m_pUnknownSize = pCluster;
m_pos = -pos;
return 0; // partial success, since we have a new cluster
#if 0
if (cluster_size < 0) { //unknown size
const long long payload_pos = pos; //absolute pos of cluster payload
for (;;) { //determine cluster size
if ((total >= 0) && (pos >= total))
break;
if ((segment_stop >= 0) && (pos >= segment_stop))
break; //no more clusters
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id < 0) //error (or underflow)
return static_cast<long>(id);
if (id == 0x0F43B675) //Cluster ID
break;
if (id == 0x0C53BB6B) //Cues ID
break;
switch (id)
{
case 0x20: //BlockGroup
case 0x23: //Simple Block
case 0x67: //TimeCode
case 0x2B: //PrevSize
break;
default:
assert(false);
break;
}
pos += len; //consume ID (of sub-element)
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
pos += len; //consume size field of element
if (size == 0) //weird
continue;
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; //not allowed for sub-elements
if ((segment_stop >= 0) && ((pos + size) > segment_stop)) //weird
return E_FILE_FORMAT_INVALID;
pos += size; //consume payload of sub-element
assert((segment_stop < 0) || (pos <= segment_stop));
} //determine cluster size
cluster_size = pos - payload_pos;
assert(cluster_size >= 0);
pos = payload_pos; //reset and re-parse original cluster
}
if (m_clusterPreloadCount > 0)
{
assert(idx < m_clusterSize);
Cluster* const pCluster = m_clusters[idx];
assert(pCluster);
assert(pCluster->m_index < 0);
const long long off = pCluster->GetPosition();
assert(off >= 0);
if (off == cluster_off) //preloaded already
return E_FILE_FORMAT_INVALID; //subtle
}
m_pos = pos + cluster_size; //consume payload
assert((segment_stop < 0) || (m_pos <= segment_stop));
return 2; //try to find another cluster
#endif
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long Segment::DoLoadCluster(long long& pos, long& len) {
if (m_pos < 0)
return DoLoadClusterUnknownSize(pos, len);
long long total, avail;
long status = m_pReader->Length(&total, &avail);
if (status < 0) // error
return status;
if (total >= 0 && avail > total)
return E_FILE_FORMAT_INVALID;
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
long long cluster_off = -1; // offset relative to start of segment
long long cluster_size = -1; // size of cluster payload
for (;;) {
if ((total >= 0) && (m_pos >= total))
return 1; // no more clusters
if ((segment_stop >= 0) && (m_pos >= segment_stop))
return 1; // no more clusters
pos = m_pos;
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadID(m_pReader, idpos, len);
if (id < 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume ID
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) // error
return static_cast<long>(size);
pos += len; // consume length of size of element
if (size == 0) { // weird
m_pos = pos;
continue;
}
const long long unknown_size = (1LL << (7 * len)) - 1;
if ((segment_stop >= 0) && (size != unknown_size) &&
((pos + size) > segment_stop)) {
return E_FILE_FORMAT_INVALID;
}
if (id == 0x0C53BB6B) { // Cues ID
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; // TODO: liberalize
if (m_pCues == NULL) {
const long long element_size = (pos - idpos) + size;
m_pCues = new (std::nothrow) Cues(this, pos, size, idpos, element_size);
if (m_pCues == NULL)
return -1;
}
m_pos = pos + size; // consume payload
continue;
}
if (id != 0x0F43B675) { // Cluster ID
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; // TODO: liberalize
m_pos = pos + size; // consume payload
continue;
}
cluster_off = idpos - m_start; // relative pos
if (size != unknown_size)
cluster_size = size;
break;
}
if (cluster_off < 0) {
// No cluster, die.
return E_FILE_FORMAT_INVALID;
}
long long pos_;
long len_;
status = Cluster::HasBlockEntries(this, cluster_off, pos_, len_);
if (status < 0) { // error, or underflow
pos = pos_;
len = len_;
return status;
}
const long idx = m_clusterCount;
if (m_clusterPreloadCount > 0) {
if (idx >= m_clusterSize)
return E_FILE_FORMAT_INVALID;
Cluster* const pCluster = m_clusters[idx];
if (pCluster == NULL || pCluster->m_index >= 0)
return E_FILE_FORMAT_INVALID;
const long long off = pCluster->GetPosition();
if (off < 0)
return E_FILE_FORMAT_INVALID;
if (off == cluster_off) { // preloaded already
if (status == 0) // no entries found
return E_FILE_FORMAT_INVALID;
if (cluster_size >= 0)
pos += cluster_size;
else {
const long long element_size = pCluster->GetElementSize();
if (element_size <= 0)
return E_FILE_FORMAT_INVALID; // TODO: handle this case
pos = pCluster->m_element_start + element_size;
}
pCluster->m_index = idx; // move from preloaded to loaded
++m_clusterCount;
--m_clusterPreloadCount;
m_pos = pos; // consume payload
if (segment_stop >= 0 && m_pos > segment_stop)
return E_FILE_FORMAT_INVALID;
return 0; // success
}
}
if (status == 0) { // no entries found
if (cluster_size >= 0)
pos += cluster_size;
if ((total >= 0) && (pos >= total)) {
m_pos = total;
return 1; // no more clusters
}
if ((segment_stop >= 0) && (pos >= segment_stop)) {
m_pos = segment_stop;
return 1; // no more clusters
}
m_pos = pos;
return 2; // try again
}
Cluster* const pCluster = Cluster::Create(this, idx, cluster_off);
if (pCluster == NULL)
return -1;
if (!AppendCluster(pCluster)) {
delete pCluster;
return -1;
}
if (cluster_size >= 0) {
pos += cluster_size;
m_pos = pos;
if (segment_stop > 0 && m_pos > segment_stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
m_pUnknownSize = pCluster;
m_pos = -pos;
return 0; // partial success, since we have a new cluster
// status == 0 means "no block entries found"
// pos designates start of payload
// m_pos has NOT been adjusted yet (in case we need to come back here)
}
| 173,808 |
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 asymmetric_key_match(const struct key *key,
const struct key_match_data *match_data)
{
const struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key);
const char *description = match_data->raw_data;
const char *spec = description;
const char *id;
ptrdiff_t speclen;
if (!subtype || !spec || !*spec)
return 0;
/* See if the full key description matches as is */
if (key->description && strcmp(key->description, description) == 0)
return 1;
/* All tests from here on break the criterion description into a
* specifier, a colon and then an identifier.
*/
id = strchr(spec, ':');
if (!id)
return 0;
speclen = id - spec;
id++;
if (speclen == 2 && memcmp(spec, "id", 2) == 0)
return asymmetric_keyid_match(asymmetric_key_id(key), id);
if (speclen == subtype->name_len &&
memcmp(spec, subtype->name, speclen) == 0)
return 1;
return 0;
}
Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse
A previous patch added a ->match_preparse() method to the key type. This is
allowed to override the function called by the iteration algorithm.
Therefore, we can just set a default that simply checks for an exact match of
the key description with the original criterion data and allow match_preparse
to override it as needed.
The key_type::match op is then redundant and can be removed, as can the
user_match() function.
Signed-off-by: David Howells <[email protected]>
Acked-by: Vivek Goyal <[email protected]>
CWE ID: CWE-476 | static int asymmetric_key_match(const struct key *key,
static int asymmetric_key_cmp(const struct key *key,
const struct key_match_data *match_data)
{
const struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key);
const char *description = match_data->raw_data;
const char *spec = description;
const char *id;
ptrdiff_t speclen;
if (!subtype || !spec || !*spec)
return 0;
/* See if the full key description matches as is */
if (key->description && strcmp(key->description, description) == 0)
return 1;
/* All tests from here on break the criterion description into a
* specifier, a colon and then an identifier.
*/
id = strchr(spec, ':');
if (!id)
return 0;
speclen = id - spec;
id++;
if (speclen == 2 && memcmp(spec, "id", 2) == 0)
return asymmetric_keyid_match(asymmetric_key_id(key), id);
if (speclen == subtype->name_len &&
memcmp(spec, subtype->name, speclen) == 0)
return 1;
return 0;
}
| 168,436 |
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 BlobURLRegistry::unregisterURL(const KURL& url)
{
ThreadableBlobRegistry::unregisterBlobURL(url);
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void BlobURLRegistry::unregisterURL(const KURL& url)
{
BlobRegistry::unregisterBlobURL(url);
}
| 170,678 |
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: GpuChannelHost::GpuChannelHost(
GpuChannelHostFactory* factory, int gpu_process_id, int client_id)
: factory_(factory),
gpu_process_id_(gpu_process_id),
client_id_(client_id),
state_(kUnconnected) {
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | GpuChannelHost::GpuChannelHost(
GpuChannelHostFactory* factory, int gpu_host_id, int client_id)
: factory_(factory),
client_id_(client_id),
gpu_host_id_(gpu_host_id),
state_(kUnconnected) {
}
| 170,929 |
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: InputMethodDescriptors* CrosMock::CreateInputMethodDescriptors() {
InputMethodDescriptors* descriptors = new InputMethodDescriptors;
descriptors->push_back(
input_method::GetFallbackInputMethodDescriptor());
return descriptors;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | InputMethodDescriptors* CrosMock::CreateInputMethodDescriptors() {
input_method::InputMethodDescriptors*
CrosMock::CreateInputMethodDescriptors() {
input_method::InputMethodDescriptors* descriptors =
new input_method::InputMethodDescriptors;
descriptors->push_back(
input_method::GetFallbackInputMethodDescriptor());
return descriptors;
}
| 170,475 |
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: magic_setparam(struct magic_set *ms, int param, const void *val)
{
switch (param) {
case MAGIC_PARAM_INDIR_MAX:
ms->indir_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_NAME_MAX:
ms->name_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_ELF_PHNUM_MAX:
ms->elf_phnum_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_ELF_SHNUM_MAX:
ms->elf_shnum_max = *(const size_t *)val;
return 0;
default:
errno = EINVAL;
return -1;
}
}
Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander
Cherepanov)
- Restructure ELF note printing so that we don't print the same message
multiple times on repeated notes of the same kind.
CWE ID: CWE-399 | magic_setparam(struct magic_set *ms, int param, const void *val)
{
switch (param) {
case MAGIC_PARAM_INDIR_MAX:
ms->indir_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_NAME_MAX:
ms->name_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_ELF_PHNUM_MAX:
ms->elf_phnum_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_ELF_SHNUM_MAX:
ms->elf_shnum_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_ELF_NOTES_MAX:
ms->elf_notes_max = *(const size_t *)val;
return 0;
default:
errno = EINVAL;
return -1;
}
}
| 166,775 |
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: setup_server_realm(krb5_principal sprinc)
{
krb5_error_code kret;
kdc_realm_t *newrealm;
kret = 0;
if (kdc_numrealms > 1) {
if (!(newrealm = find_realm_data(sprinc->realm.data,
(krb5_ui_4) sprinc->realm.length)))
kret = ENOENT;
else
kdc_active_realm = newrealm;
}
else
kdc_active_realm = kdc_realmlist[0];
return(kret);
}
Commit Message: Multi-realm KDC null deref [CVE-2013-1418]
If a KDC serves multiple realms, certain requests can cause
setup_server_realm() to dereference a null pointer, crashing the KDC.
CVSSv2: AV:N/AC:M/Au:N/C:N/I:N/A:P/E:POC/RL:OF/RC:C
A related but more minor vulnerability requires authentication to
exploit, and is only present if a third-party KDC database module can
dereference a null pointer under certain conditions.
(back ported from commit 5d2d9a1abe46a2c1a8614d4672d08d9d30a5f8bf)
ticket: 7757 (new)
version_fixed: 1.10.7
status: resolved
CWE ID: | setup_server_realm(krb5_principal sprinc)
{
krb5_error_code kret;
kdc_realm_t *newrealm;
kret = 0;
if (sprinc == NULL)
return NULL;
if (kdc_numrealms > 1) {
if (!(newrealm = find_realm_data(sprinc->realm.data,
(krb5_ui_4) sprinc->realm.length)))
kret = ENOENT;
else
kdc_active_realm = newrealm;
}
else
kdc_active_realm = kdc_realmlist[0];
return(kret);
}
| 165,933 |
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 do_ip_setsockopt(struct sock *sk, int level,
int optname, char __user *optval, unsigned int optlen)
{
struct inet_sock *inet = inet_sk(sk);
int val = 0, err;
if (((1<<optname) & ((1<<IP_PKTINFO) | (1<<IP_RECVTTL) |
(1<<IP_RECVOPTS) | (1<<IP_RECVTOS) |
(1<<IP_RETOPTS) | (1<<IP_TOS) |
(1<<IP_TTL) | (1<<IP_HDRINCL) |
(1<<IP_MTU_DISCOVER) | (1<<IP_RECVERR) |
(1<<IP_ROUTER_ALERT) | (1<<IP_FREEBIND) |
(1<<IP_PASSSEC) | (1<<IP_TRANSPARENT) |
(1<<IP_MINTTL) | (1<<IP_NODEFRAG))) ||
optname == IP_MULTICAST_TTL ||
optname == IP_MULTICAST_ALL ||
optname == IP_MULTICAST_LOOP ||
optname == IP_RECVORIGDSTADDR) {
if (optlen >= sizeof(int)) {
if (get_user(val, (int __user *) optval))
return -EFAULT;
} else if (optlen >= sizeof(char)) {
unsigned char ucval;
if (get_user(ucval, (unsigned char __user *) optval))
return -EFAULT;
val = (int) ucval;
}
}
/* If optlen==0, it is equivalent to val == 0 */
if (ip_mroute_opt(optname))
return ip_mroute_setsockopt(sk, optname, optval, optlen);
err = 0;
lock_sock(sk);
switch (optname) {
case IP_OPTIONS:
{
struct ip_options *opt = NULL;
if (optlen > 40)
goto e_inval;
err = ip_options_get_from_user(sock_net(sk), &opt,
optval, optlen);
if (err)
break;
if (inet->is_icsk) {
struct inet_connection_sock *icsk = inet_csk(sk);
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
if (sk->sk_family == PF_INET ||
(!((1 << sk->sk_state) &
(TCPF_LISTEN | TCPF_CLOSE)) &&
inet->inet_daddr != LOOPBACK4_IPV6)) {
#endif
if (inet->opt)
icsk->icsk_ext_hdr_len -= inet->opt->optlen;
if (opt)
icsk->icsk_ext_hdr_len += opt->optlen;
icsk->icsk_sync_mss(sk, icsk->icsk_pmtu_cookie);
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
}
#endif
}
opt = xchg(&inet->opt, opt);
kfree(opt);
break;
}
case IP_PKTINFO:
if (val)
inet->cmsg_flags |= IP_CMSG_PKTINFO;
else
inet->cmsg_flags &= ~IP_CMSG_PKTINFO;
break;
case IP_RECVTTL:
if (val)
inet->cmsg_flags |= IP_CMSG_TTL;
else
inet->cmsg_flags &= ~IP_CMSG_TTL;
break;
case IP_RECVTOS:
if (val)
inet->cmsg_flags |= IP_CMSG_TOS;
else
inet->cmsg_flags &= ~IP_CMSG_TOS;
break;
case IP_RECVOPTS:
if (val)
inet->cmsg_flags |= IP_CMSG_RECVOPTS;
else
inet->cmsg_flags &= ~IP_CMSG_RECVOPTS;
break;
case IP_RETOPTS:
if (val)
inet->cmsg_flags |= IP_CMSG_RETOPTS;
else
inet->cmsg_flags &= ~IP_CMSG_RETOPTS;
break;
case IP_PASSSEC:
if (val)
inet->cmsg_flags |= IP_CMSG_PASSSEC;
else
inet->cmsg_flags &= ~IP_CMSG_PASSSEC;
break;
case IP_RECVORIGDSTADDR:
if (val)
inet->cmsg_flags |= IP_CMSG_ORIGDSTADDR;
else
inet->cmsg_flags &= ~IP_CMSG_ORIGDSTADDR;
break;
case IP_TOS: /* This sets both TOS and Precedence */
if (sk->sk_type == SOCK_STREAM) {
val &= ~3;
val |= inet->tos & 3;
}
if (inet->tos != val) {
inet->tos = val;
sk->sk_priority = rt_tos2priority(val);
sk_dst_reset(sk);
}
break;
case IP_TTL:
if (optlen < 1)
goto e_inval;
if (val != -1 && (val < 0 || val > 255))
goto e_inval;
inet->uc_ttl = val;
break;
case IP_HDRINCL:
if (sk->sk_type != SOCK_RAW) {
err = -ENOPROTOOPT;
break;
}
inet->hdrincl = val ? 1 : 0;
break;
case IP_NODEFRAG:
if (sk->sk_type != SOCK_RAW) {
err = -ENOPROTOOPT;
break;
}
inet->nodefrag = val ? 1 : 0;
break;
case IP_MTU_DISCOVER:
if (val < IP_PMTUDISC_DONT || val > IP_PMTUDISC_PROBE)
goto e_inval;
inet->pmtudisc = val;
break;
case IP_RECVERR:
inet->recverr = !!val;
if (!val)
skb_queue_purge(&sk->sk_error_queue);
break;
case IP_MULTICAST_TTL:
if (sk->sk_type == SOCK_STREAM)
goto e_inval;
if (optlen < 1)
goto e_inval;
if (val == -1)
val = 1;
if (val < 0 || val > 255)
goto e_inval;
inet->mc_ttl = val;
break;
case IP_MULTICAST_LOOP:
if (optlen < 1)
goto e_inval;
inet->mc_loop = !!val;
break;
case IP_MULTICAST_IF:
{
struct ip_mreqn mreq;
struct net_device *dev = NULL;
if (sk->sk_type == SOCK_STREAM)
goto e_inval;
/*
* Check the arguments are allowable
*/
if (optlen < sizeof(struct in_addr))
goto e_inval;
err = -EFAULT;
if (optlen >= sizeof(struct ip_mreqn)) {
if (copy_from_user(&mreq, optval, sizeof(mreq)))
break;
} else {
memset(&mreq, 0, sizeof(mreq));
if (optlen >= sizeof(struct in_addr) &&
copy_from_user(&mreq.imr_address, optval,
sizeof(struct in_addr)))
break;
}
if (!mreq.imr_ifindex) {
if (mreq.imr_address.s_addr == htonl(INADDR_ANY)) {
inet->mc_index = 0;
inet->mc_addr = 0;
err = 0;
break;
}
dev = ip_dev_find(sock_net(sk), mreq.imr_address.s_addr);
if (dev)
mreq.imr_ifindex = dev->ifindex;
} else
dev = dev_get_by_index(sock_net(sk), mreq.imr_ifindex);
err = -EADDRNOTAVAIL;
if (!dev)
break;
dev_put(dev);
err = -EINVAL;
if (sk->sk_bound_dev_if &&
mreq.imr_ifindex != sk->sk_bound_dev_if)
break;
inet->mc_index = mreq.imr_ifindex;
inet->mc_addr = mreq.imr_address.s_addr;
err = 0;
break;
}
case IP_ADD_MEMBERSHIP:
case IP_DROP_MEMBERSHIP:
{
struct ip_mreqn mreq;
err = -EPROTO;
if (inet_sk(sk)->is_icsk)
break;
if (optlen < sizeof(struct ip_mreq))
goto e_inval;
err = -EFAULT;
if (optlen >= sizeof(struct ip_mreqn)) {
if (copy_from_user(&mreq, optval, sizeof(mreq)))
break;
} else {
memset(&mreq, 0, sizeof(mreq));
if (copy_from_user(&mreq, optval, sizeof(struct ip_mreq)))
break;
}
if (optname == IP_ADD_MEMBERSHIP)
err = ip_mc_join_group(sk, &mreq);
else
err = ip_mc_leave_group(sk, &mreq);
break;
}
case IP_MSFILTER:
{
struct ip_msfilter *msf;
if (optlen < IP_MSFILTER_SIZE(0))
goto e_inval;
if (optlen > sysctl_optmem_max) {
err = -ENOBUFS;
break;
}
msf = kmalloc(optlen, GFP_KERNEL);
if (!msf) {
err = -ENOBUFS;
break;
}
err = -EFAULT;
if (copy_from_user(msf, optval, optlen)) {
kfree(msf);
break;
}
/* numsrc >= (1G-4) overflow in 32 bits */
if (msf->imsf_numsrc >= 0x3ffffffcU ||
msf->imsf_numsrc > sysctl_igmp_max_msf) {
kfree(msf);
err = -ENOBUFS;
break;
}
if (IP_MSFILTER_SIZE(msf->imsf_numsrc) > optlen) {
kfree(msf);
err = -EINVAL;
break;
}
err = ip_mc_msfilter(sk, msf, 0);
kfree(msf);
break;
}
case IP_BLOCK_SOURCE:
case IP_UNBLOCK_SOURCE:
case IP_ADD_SOURCE_MEMBERSHIP:
case IP_DROP_SOURCE_MEMBERSHIP:
{
struct ip_mreq_source mreqs;
int omode, add;
if (optlen != sizeof(struct ip_mreq_source))
goto e_inval;
if (copy_from_user(&mreqs, optval, sizeof(mreqs))) {
err = -EFAULT;
break;
}
if (optname == IP_BLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 1;
} else if (optname == IP_UNBLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 0;
} else if (optname == IP_ADD_SOURCE_MEMBERSHIP) {
struct ip_mreqn mreq;
mreq.imr_multiaddr.s_addr = mreqs.imr_multiaddr;
mreq.imr_address.s_addr = mreqs.imr_interface;
mreq.imr_ifindex = 0;
err = ip_mc_join_group(sk, &mreq);
if (err && err != -EADDRINUSE)
break;
omode = MCAST_INCLUDE;
add = 1;
} else /* IP_DROP_SOURCE_MEMBERSHIP */ {
omode = MCAST_INCLUDE;
add = 0;
}
err = ip_mc_source(add, omode, sk, &mreqs, 0);
break;
}
case MCAST_JOIN_GROUP:
case MCAST_LEAVE_GROUP:
{
struct group_req greq;
struct sockaddr_in *psin;
struct ip_mreqn mreq;
if (optlen < sizeof(struct group_req))
goto e_inval;
err = -EFAULT;
if (copy_from_user(&greq, optval, sizeof(greq)))
break;
psin = (struct sockaddr_in *)&greq.gr_group;
if (psin->sin_family != AF_INET)
goto e_inval;
memset(&mreq, 0, sizeof(mreq));
mreq.imr_multiaddr = psin->sin_addr;
mreq.imr_ifindex = greq.gr_interface;
if (optname == MCAST_JOIN_GROUP)
err = ip_mc_join_group(sk, &mreq);
else
err = ip_mc_leave_group(sk, &mreq);
break;
}
case MCAST_JOIN_SOURCE_GROUP:
case MCAST_LEAVE_SOURCE_GROUP:
case MCAST_BLOCK_SOURCE:
case MCAST_UNBLOCK_SOURCE:
{
struct group_source_req greqs;
struct ip_mreq_source mreqs;
struct sockaddr_in *psin;
int omode, add;
if (optlen != sizeof(struct group_source_req))
goto e_inval;
if (copy_from_user(&greqs, optval, sizeof(greqs))) {
err = -EFAULT;
break;
}
if (greqs.gsr_group.ss_family != AF_INET ||
greqs.gsr_source.ss_family != AF_INET) {
err = -EADDRNOTAVAIL;
break;
}
psin = (struct sockaddr_in *)&greqs.gsr_group;
mreqs.imr_multiaddr = psin->sin_addr.s_addr;
psin = (struct sockaddr_in *)&greqs.gsr_source;
mreqs.imr_sourceaddr = psin->sin_addr.s_addr;
mreqs.imr_interface = 0; /* use index for mc_source */
if (optname == MCAST_BLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 1;
} else if (optname == MCAST_UNBLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 0;
} else if (optname == MCAST_JOIN_SOURCE_GROUP) {
struct ip_mreqn mreq;
psin = (struct sockaddr_in *)&greqs.gsr_group;
mreq.imr_multiaddr = psin->sin_addr;
mreq.imr_address.s_addr = 0;
mreq.imr_ifindex = greqs.gsr_interface;
err = ip_mc_join_group(sk, &mreq);
if (err && err != -EADDRINUSE)
break;
greqs.gsr_interface = mreq.imr_ifindex;
omode = MCAST_INCLUDE;
add = 1;
} else /* MCAST_LEAVE_SOURCE_GROUP */ {
omode = MCAST_INCLUDE;
add = 0;
}
err = ip_mc_source(add, omode, sk, &mreqs,
greqs.gsr_interface);
break;
}
case MCAST_MSFILTER:
{
struct sockaddr_in *psin;
struct ip_msfilter *msf = NULL;
struct group_filter *gsf = NULL;
int msize, i, ifindex;
if (optlen < GROUP_FILTER_SIZE(0))
goto e_inval;
if (optlen > sysctl_optmem_max) {
err = -ENOBUFS;
break;
}
gsf = kmalloc(optlen, GFP_KERNEL);
if (!gsf) {
err = -ENOBUFS;
break;
}
err = -EFAULT;
if (copy_from_user(gsf, optval, optlen))
goto mc_msf_out;
/* numsrc >= (4G-140)/128 overflow in 32 bits */
if (gsf->gf_numsrc >= 0x1ffffff ||
gsf->gf_numsrc > sysctl_igmp_max_msf) {
err = -ENOBUFS;
goto mc_msf_out;
}
if (GROUP_FILTER_SIZE(gsf->gf_numsrc) > optlen) {
err = -EINVAL;
goto mc_msf_out;
}
msize = IP_MSFILTER_SIZE(gsf->gf_numsrc);
msf = kmalloc(msize, GFP_KERNEL);
if (!msf) {
err = -ENOBUFS;
goto mc_msf_out;
}
ifindex = gsf->gf_interface;
psin = (struct sockaddr_in *)&gsf->gf_group;
if (psin->sin_family != AF_INET) {
err = -EADDRNOTAVAIL;
goto mc_msf_out;
}
msf->imsf_multiaddr = psin->sin_addr.s_addr;
msf->imsf_interface = 0;
msf->imsf_fmode = gsf->gf_fmode;
msf->imsf_numsrc = gsf->gf_numsrc;
err = -EADDRNOTAVAIL;
for (i = 0; i < gsf->gf_numsrc; ++i) {
psin = (struct sockaddr_in *)&gsf->gf_slist[i];
if (psin->sin_family != AF_INET)
goto mc_msf_out;
msf->imsf_slist[i] = psin->sin_addr.s_addr;
}
kfree(gsf);
gsf = NULL;
err = ip_mc_msfilter(sk, msf, ifindex);
mc_msf_out:
kfree(msf);
kfree(gsf);
break;
}
case IP_MULTICAST_ALL:
if (optlen < 1)
goto e_inval;
if (val != 0 && val != 1)
goto e_inval;
inet->mc_all = val;
break;
case IP_ROUTER_ALERT:
err = ip_ra_control(sk, val ? 1 : 0, NULL);
break;
case IP_FREEBIND:
if (optlen < 1)
goto e_inval;
inet->freebind = !!val;
break;
case IP_IPSEC_POLICY:
case IP_XFRM_POLICY:
err = -EPERM;
if (!capable(CAP_NET_ADMIN))
break;
err = xfrm_user_policy(sk, optname, optval, optlen);
break;
case IP_TRANSPARENT:
if (!capable(CAP_NET_ADMIN)) {
err = -EPERM;
break;
}
if (optlen < 1)
goto e_inval;
inet->transparent = !!val;
break;
case IP_MINTTL:
if (optlen < 1)
goto e_inval;
if (val < 0 || val > 255)
goto e_inval;
inet->min_ttl = val;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
e_inval:
release_sock(sk);
return -EINVAL;
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static int do_ip_setsockopt(struct sock *sk, int level,
int optname, char __user *optval, unsigned int optlen)
{
struct inet_sock *inet = inet_sk(sk);
int val = 0, err;
if (((1<<optname) & ((1<<IP_PKTINFO) | (1<<IP_RECVTTL) |
(1<<IP_RECVOPTS) | (1<<IP_RECVTOS) |
(1<<IP_RETOPTS) | (1<<IP_TOS) |
(1<<IP_TTL) | (1<<IP_HDRINCL) |
(1<<IP_MTU_DISCOVER) | (1<<IP_RECVERR) |
(1<<IP_ROUTER_ALERT) | (1<<IP_FREEBIND) |
(1<<IP_PASSSEC) | (1<<IP_TRANSPARENT) |
(1<<IP_MINTTL) | (1<<IP_NODEFRAG))) ||
optname == IP_MULTICAST_TTL ||
optname == IP_MULTICAST_ALL ||
optname == IP_MULTICAST_LOOP ||
optname == IP_RECVORIGDSTADDR) {
if (optlen >= sizeof(int)) {
if (get_user(val, (int __user *) optval))
return -EFAULT;
} else if (optlen >= sizeof(char)) {
unsigned char ucval;
if (get_user(ucval, (unsigned char __user *) optval))
return -EFAULT;
val = (int) ucval;
}
}
/* If optlen==0, it is equivalent to val == 0 */
if (ip_mroute_opt(optname))
return ip_mroute_setsockopt(sk, optname, optval, optlen);
err = 0;
lock_sock(sk);
switch (optname) {
case IP_OPTIONS:
{
struct ip_options_rcu *old, *opt = NULL;
if (optlen > 40)
goto e_inval;
err = ip_options_get_from_user(sock_net(sk), &opt,
optval, optlen);
if (err)
break;
old = rcu_dereference_protected(inet->inet_opt,
sock_owned_by_user(sk));
if (inet->is_icsk) {
struct inet_connection_sock *icsk = inet_csk(sk);
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
if (sk->sk_family == PF_INET ||
(!((1 << sk->sk_state) &
(TCPF_LISTEN | TCPF_CLOSE)) &&
inet->inet_daddr != LOOPBACK4_IPV6)) {
#endif
if (old)
icsk->icsk_ext_hdr_len -= old->opt.optlen;
if (opt)
icsk->icsk_ext_hdr_len += opt->opt.optlen;
icsk->icsk_sync_mss(sk, icsk->icsk_pmtu_cookie);
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
}
#endif
}
rcu_assign_pointer(inet->inet_opt, opt);
if (old)
call_rcu(&old->rcu, opt_kfree_rcu);
break;
}
case IP_PKTINFO:
if (val)
inet->cmsg_flags |= IP_CMSG_PKTINFO;
else
inet->cmsg_flags &= ~IP_CMSG_PKTINFO;
break;
case IP_RECVTTL:
if (val)
inet->cmsg_flags |= IP_CMSG_TTL;
else
inet->cmsg_flags &= ~IP_CMSG_TTL;
break;
case IP_RECVTOS:
if (val)
inet->cmsg_flags |= IP_CMSG_TOS;
else
inet->cmsg_flags &= ~IP_CMSG_TOS;
break;
case IP_RECVOPTS:
if (val)
inet->cmsg_flags |= IP_CMSG_RECVOPTS;
else
inet->cmsg_flags &= ~IP_CMSG_RECVOPTS;
break;
case IP_RETOPTS:
if (val)
inet->cmsg_flags |= IP_CMSG_RETOPTS;
else
inet->cmsg_flags &= ~IP_CMSG_RETOPTS;
break;
case IP_PASSSEC:
if (val)
inet->cmsg_flags |= IP_CMSG_PASSSEC;
else
inet->cmsg_flags &= ~IP_CMSG_PASSSEC;
break;
case IP_RECVORIGDSTADDR:
if (val)
inet->cmsg_flags |= IP_CMSG_ORIGDSTADDR;
else
inet->cmsg_flags &= ~IP_CMSG_ORIGDSTADDR;
break;
case IP_TOS: /* This sets both TOS and Precedence */
if (sk->sk_type == SOCK_STREAM) {
val &= ~3;
val |= inet->tos & 3;
}
if (inet->tos != val) {
inet->tos = val;
sk->sk_priority = rt_tos2priority(val);
sk_dst_reset(sk);
}
break;
case IP_TTL:
if (optlen < 1)
goto e_inval;
if (val != -1 && (val < 0 || val > 255))
goto e_inval;
inet->uc_ttl = val;
break;
case IP_HDRINCL:
if (sk->sk_type != SOCK_RAW) {
err = -ENOPROTOOPT;
break;
}
inet->hdrincl = val ? 1 : 0;
break;
case IP_NODEFRAG:
if (sk->sk_type != SOCK_RAW) {
err = -ENOPROTOOPT;
break;
}
inet->nodefrag = val ? 1 : 0;
break;
case IP_MTU_DISCOVER:
if (val < IP_PMTUDISC_DONT || val > IP_PMTUDISC_PROBE)
goto e_inval;
inet->pmtudisc = val;
break;
case IP_RECVERR:
inet->recverr = !!val;
if (!val)
skb_queue_purge(&sk->sk_error_queue);
break;
case IP_MULTICAST_TTL:
if (sk->sk_type == SOCK_STREAM)
goto e_inval;
if (optlen < 1)
goto e_inval;
if (val == -1)
val = 1;
if (val < 0 || val > 255)
goto e_inval;
inet->mc_ttl = val;
break;
case IP_MULTICAST_LOOP:
if (optlen < 1)
goto e_inval;
inet->mc_loop = !!val;
break;
case IP_MULTICAST_IF:
{
struct ip_mreqn mreq;
struct net_device *dev = NULL;
if (sk->sk_type == SOCK_STREAM)
goto e_inval;
/*
* Check the arguments are allowable
*/
if (optlen < sizeof(struct in_addr))
goto e_inval;
err = -EFAULT;
if (optlen >= sizeof(struct ip_mreqn)) {
if (copy_from_user(&mreq, optval, sizeof(mreq)))
break;
} else {
memset(&mreq, 0, sizeof(mreq));
if (optlen >= sizeof(struct in_addr) &&
copy_from_user(&mreq.imr_address, optval,
sizeof(struct in_addr)))
break;
}
if (!mreq.imr_ifindex) {
if (mreq.imr_address.s_addr == htonl(INADDR_ANY)) {
inet->mc_index = 0;
inet->mc_addr = 0;
err = 0;
break;
}
dev = ip_dev_find(sock_net(sk), mreq.imr_address.s_addr);
if (dev)
mreq.imr_ifindex = dev->ifindex;
} else
dev = dev_get_by_index(sock_net(sk), mreq.imr_ifindex);
err = -EADDRNOTAVAIL;
if (!dev)
break;
dev_put(dev);
err = -EINVAL;
if (sk->sk_bound_dev_if &&
mreq.imr_ifindex != sk->sk_bound_dev_if)
break;
inet->mc_index = mreq.imr_ifindex;
inet->mc_addr = mreq.imr_address.s_addr;
err = 0;
break;
}
case IP_ADD_MEMBERSHIP:
case IP_DROP_MEMBERSHIP:
{
struct ip_mreqn mreq;
err = -EPROTO;
if (inet_sk(sk)->is_icsk)
break;
if (optlen < sizeof(struct ip_mreq))
goto e_inval;
err = -EFAULT;
if (optlen >= sizeof(struct ip_mreqn)) {
if (copy_from_user(&mreq, optval, sizeof(mreq)))
break;
} else {
memset(&mreq, 0, sizeof(mreq));
if (copy_from_user(&mreq, optval, sizeof(struct ip_mreq)))
break;
}
if (optname == IP_ADD_MEMBERSHIP)
err = ip_mc_join_group(sk, &mreq);
else
err = ip_mc_leave_group(sk, &mreq);
break;
}
case IP_MSFILTER:
{
struct ip_msfilter *msf;
if (optlen < IP_MSFILTER_SIZE(0))
goto e_inval;
if (optlen > sysctl_optmem_max) {
err = -ENOBUFS;
break;
}
msf = kmalloc(optlen, GFP_KERNEL);
if (!msf) {
err = -ENOBUFS;
break;
}
err = -EFAULT;
if (copy_from_user(msf, optval, optlen)) {
kfree(msf);
break;
}
/* numsrc >= (1G-4) overflow in 32 bits */
if (msf->imsf_numsrc >= 0x3ffffffcU ||
msf->imsf_numsrc > sysctl_igmp_max_msf) {
kfree(msf);
err = -ENOBUFS;
break;
}
if (IP_MSFILTER_SIZE(msf->imsf_numsrc) > optlen) {
kfree(msf);
err = -EINVAL;
break;
}
err = ip_mc_msfilter(sk, msf, 0);
kfree(msf);
break;
}
case IP_BLOCK_SOURCE:
case IP_UNBLOCK_SOURCE:
case IP_ADD_SOURCE_MEMBERSHIP:
case IP_DROP_SOURCE_MEMBERSHIP:
{
struct ip_mreq_source mreqs;
int omode, add;
if (optlen != sizeof(struct ip_mreq_source))
goto e_inval;
if (copy_from_user(&mreqs, optval, sizeof(mreqs))) {
err = -EFAULT;
break;
}
if (optname == IP_BLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 1;
} else if (optname == IP_UNBLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 0;
} else if (optname == IP_ADD_SOURCE_MEMBERSHIP) {
struct ip_mreqn mreq;
mreq.imr_multiaddr.s_addr = mreqs.imr_multiaddr;
mreq.imr_address.s_addr = mreqs.imr_interface;
mreq.imr_ifindex = 0;
err = ip_mc_join_group(sk, &mreq);
if (err && err != -EADDRINUSE)
break;
omode = MCAST_INCLUDE;
add = 1;
} else /* IP_DROP_SOURCE_MEMBERSHIP */ {
omode = MCAST_INCLUDE;
add = 0;
}
err = ip_mc_source(add, omode, sk, &mreqs, 0);
break;
}
case MCAST_JOIN_GROUP:
case MCAST_LEAVE_GROUP:
{
struct group_req greq;
struct sockaddr_in *psin;
struct ip_mreqn mreq;
if (optlen < sizeof(struct group_req))
goto e_inval;
err = -EFAULT;
if (copy_from_user(&greq, optval, sizeof(greq)))
break;
psin = (struct sockaddr_in *)&greq.gr_group;
if (psin->sin_family != AF_INET)
goto e_inval;
memset(&mreq, 0, sizeof(mreq));
mreq.imr_multiaddr = psin->sin_addr;
mreq.imr_ifindex = greq.gr_interface;
if (optname == MCAST_JOIN_GROUP)
err = ip_mc_join_group(sk, &mreq);
else
err = ip_mc_leave_group(sk, &mreq);
break;
}
case MCAST_JOIN_SOURCE_GROUP:
case MCAST_LEAVE_SOURCE_GROUP:
case MCAST_BLOCK_SOURCE:
case MCAST_UNBLOCK_SOURCE:
{
struct group_source_req greqs;
struct ip_mreq_source mreqs;
struct sockaddr_in *psin;
int omode, add;
if (optlen != sizeof(struct group_source_req))
goto e_inval;
if (copy_from_user(&greqs, optval, sizeof(greqs))) {
err = -EFAULT;
break;
}
if (greqs.gsr_group.ss_family != AF_INET ||
greqs.gsr_source.ss_family != AF_INET) {
err = -EADDRNOTAVAIL;
break;
}
psin = (struct sockaddr_in *)&greqs.gsr_group;
mreqs.imr_multiaddr = psin->sin_addr.s_addr;
psin = (struct sockaddr_in *)&greqs.gsr_source;
mreqs.imr_sourceaddr = psin->sin_addr.s_addr;
mreqs.imr_interface = 0; /* use index for mc_source */
if (optname == MCAST_BLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 1;
} else if (optname == MCAST_UNBLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 0;
} else if (optname == MCAST_JOIN_SOURCE_GROUP) {
struct ip_mreqn mreq;
psin = (struct sockaddr_in *)&greqs.gsr_group;
mreq.imr_multiaddr = psin->sin_addr;
mreq.imr_address.s_addr = 0;
mreq.imr_ifindex = greqs.gsr_interface;
err = ip_mc_join_group(sk, &mreq);
if (err && err != -EADDRINUSE)
break;
greqs.gsr_interface = mreq.imr_ifindex;
omode = MCAST_INCLUDE;
add = 1;
} else /* MCAST_LEAVE_SOURCE_GROUP */ {
omode = MCAST_INCLUDE;
add = 0;
}
err = ip_mc_source(add, omode, sk, &mreqs,
greqs.gsr_interface);
break;
}
case MCAST_MSFILTER:
{
struct sockaddr_in *psin;
struct ip_msfilter *msf = NULL;
struct group_filter *gsf = NULL;
int msize, i, ifindex;
if (optlen < GROUP_FILTER_SIZE(0))
goto e_inval;
if (optlen > sysctl_optmem_max) {
err = -ENOBUFS;
break;
}
gsf = kmalloc(optlen, GFP_KERNEL);
if (!gsf) {
err = -ENOBUFS;
break;
}
err = -EFAULT;
if (copy_from_user(gsf, optval, optlen))
goto mc_msf_out;
/* numsrc >= (4G-140)/128 overflow in 32 bits */
if (gsf->gf_numsrc >= 0x1ffffff ||
gsf->gf_numsrc > sysctl_igmp_max_msf) {
err = -ENOBUFS;
goto mc_msf_out;
}
if (GROUP_FILTER_SIZE(gsf->gf_numsrc) > optlen) {
err = -EINVAL;
goto mc_msf_out;
}
msize = IP_MSFILTER_SIZE(gsf->gf_numsrc);
msf = kmalloc(msize, GFP_KERNEL);
if (!msf) {
err = -ENOBUFS;
goto mc_msf_out;
}
ifindex = gsf->gf_interface;
psin = (struct sockaddr_in *)&gsf->gf_group;
if (psin->sin_family != AF_INET) {
err = -EADDRNOTAVAIL;
goto mc_msf_out;
}
msf->imsf_multiaddr = psin->sin_addr.s_addr;
msf->imsf_interface = 0;
msf->imsf_fmode = gsf->gf_fmode;
msf->imsf_numsrc = gsf->gf_numsrc;
err = -EADDRNOTAVAIL;
for (i = 0; i < gsf->gf_numsrc; ++i) {
psin = (struct sockaddr_in *)&gsf->gf_slist[i];
if (psin->sin_family != AF_INET)
goto mc_msf_out;
msf->imsf_slist[i] = psin->sin_addr.s_addr;
}
kfree(gsf);
gsf = NULL;
err = ip_mc_msfilter(sk, msf, ifindex);
mc_msf_out:
kfree(msf);
kfree(gsf);
break;
}
case IP_MULTICAST_ALL:
if (optlen < 1)
goto e_inval;
if (val != 0 && val != 1)
goto e_inval;
inet->mc_all = val;
break;
case IP_ROUTER_ALERT:
err = ip_ra_control(sk, val ? 1 : 0, NULL);
break;
case IP_FREEBIND:
if (optlen < 1)
goto e_inval;
inet->freebind = !!val;
break;
case IP_IPSEC_POLICY:
case IP_XFRM_POLICY:
err = -EPERM;
if (!capable(CAP_NET_ADMIN))
break;
err = xfrm_user_policy(sk, optname, optval, optlen);
break;
case IP_TRANSPARENT:
if (!capable(CAP_NET_ADMIN)) {
err = -EPERM;
break;
}
if (optlen < 1)
goto e_inval;
inet->transparent = !!val;
break;
case IP_MINTTL:
if (optlen < 1)
goto e_inval;
if (val < 0 || val > 255)
goto e_inval;
inet->min_ttl = val;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
e_inval:
release_sock(sk);
return -EINVAL;
}
| 165,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: int trigger_fpga_config(void)
{
int ret = 0, init_l;
/* approx 10ms */
u32 timeout = 10000;
/* make sure the FPGA_can access the EEPROM */
toggle_fpga_eeprom_bus(false);
/* assert CONF_SEL_L to be able to drive FPGA_PROG_L */
qrio_gpio_direction_output(GPIO_A, CONF_SEL_L, 0);
/* trigger the config start */
qrio_gpio_direction_output(GPIO_A, FPGA_PROG_L, 0);
/* small delay for INIT_L line */
udelay(10);
/* wait for FPGA_INIT to be asserted */
do {
init_l = qrio_get_gpio(GPIO_A, FPGA_INIT_L);
if (timeout-- == 0) {
printf("FPGA_INIT timeout\n");
ret = -EFAULT;
break;
}
udelay(10);
} while (init_l);
/* deassert FPGA_PROG, config should start */
qrio_set_gpio(GPIO_A, FPGA_PROG_L, 1);
return ret;
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787 | int trigger_fpga_config(void)
{
int ret = 0, init_l;
/* approx 10ms */
u32 timeout = 10000;
/* make sure the FPGA_can access the EEPROM */
toggle_fpga_eeprom_bus(false);
/* assert CONF_SEL_L to be able to drive FPGA_PROG_L */
qrio_gpio_direction_output(QRIO_GPIO_A, CONF_SEL_L, 0);
/* trigger the config start */
qrio_gpio_direction_output(QRIO_GPIO_A, FPGA_PROG_L, 0);
/* small delay for INIT_L line */
udelay(10);
/* wait for FPGA_INIT to be asserted */
do {
init_l = qrio_get_gpio(QRIO_GPIO_A, FPGA_INIT_L);
if (timeout-- == 0) {
printf("FPGA_INIT timeout\n");
ret = -EFAULT;
break;
}
udelay(10);
} while (init_l);
/* deassert FPGA_PROG, config should start */
qrio_set_gpio(QRIO_GPIO_A, FPGA_PROG_L, 1);
return ret;
}
| 169,635 |
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 void removeElementPreservingChildren(PassRefPtr<DocumentFragment> fragment, HTMLElement* element)
{
ExceptionCode ignoredExceptionCode;
RefPtr<Node> nextChild;
for (RefPtr<Node> child = element->firstChild(); child; child = nextChild) {
nextChild = child->nextSibling();
element->removeChild(child.get(), ignoredExceptionCode);
ASSERT(!ignoredExceptionCode);
fragment->insertBefore(child, element, ignoredExceptionCode);
ASSERT(!ignoredExceptionCode);
}
fragment->removeChild(element, ignoredExceptionCode);
ASSERT(!ignoredExceptionCode);
}
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 | static inline void removeElementPreservingChildren(PassRefPtr<DocumentFragment> fragment, HTMLElement* element)
| 170,436 |
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: std::unique_ptr<SymmetricKey>* GetPaddingKey() {
static base::NoDestructor<std::unique_ptr<SymmetricKey>> s_padding_key([] {
return SymmetricKey::GenerateRandomKey(kPaddingKeyAlgorithm, 128);
}());
return s_padding_key.get();
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | std::unique_ptr<SymmetricKey>* GetPaddingKey() {
std::unique_ptr<SymmetricKey>* GetPaddingKeyInternal() {
static base::NoDestructor<std::unique_ptr<SymmetricKey>> s_padding_key([] {
return SymmetricKey::GenerateRandomKey(kPaddingKeyAlgorithm, 128);
}());
return s_padding_key.get();
}
| 173,000 |
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 Browser::CanCloseContentsAt(int index) {
if (!CanCloseTab())
return false;
if (tab_handler_->GetTabStripModel()->count() > 1)
return true;
return CanCloseWithInProgressDownloads();
}
Commit Message: chromeos: fix bug where "aw snap" page replaces first tab if it was a NTP when closing window with > 1 tab.
BUG=chromium-os:12088
TEST=verify bug per bug report.
Review URL: http://codereview.chromium.org/6882058
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83031 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool Browser::CanCloseContentsAt(int index) {
bool Browser::CanCloseContents(std::vector<int>* indices) {
DCHECK(!indices->empty());
TabCloseableStateWatcher* watcher =
g_browser_process->tab_closeable_state_watcher();
bool can_close_all = !watcher || watcher->CanCloseTabs(this, indices);
if (indices->empty()) // Cannot close any tab.
return false;
// Now, handle cases where at least one tab can be closed.
// If we are closing all the tabs for this browser, make sure to check for
if (tab_handler_->GetTabStripModel()->count() ==
static_cast<int>(indices->size()) &&
!CanCloseWithInProgressDownloads()) {
indices->clear();
can_close_all = false;
}
return can_close_all;
}
| 170,303 |
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 check_pointer_type_change(Notifier *notifier, void *data)
{
VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
int absolute = qemu_input_is_absolute();
if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1);
vnc_framebuffer_update(vs, absolute, 0,
surface_width(vs->vd->ds),
surface_height(vs->vd->ds),
VNC_ENCODING_POINTER_TYPE_CHANGE);
vnc_unlock_output(vs);
vnc_flush(vs);
vnc_unlock_output(vs);
vnc_flush(vs);
}
vs->absolute = absolute;
}
Commit Message:
CWE ID: CWE-125 | static void check_pointer_type_change(Notifier *notifier, void *data)
{
VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
int absolute = qemu_input_is_absolute();
if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1);
vnc_framebuffer_update(vs, absolute, 0,
pixman_image_get_width(vs->vd->server),
pixman_image_get_height(vs->vd->server),
VNC_ENCODING_POINTER_TYPE_CHANGE);
vnc_unlock_output(vs);
vnc_flush(vs);
vnc_unlock_output(vs);
vnc_flush(vs);
}
vs->absolute = absolute;
}
| 165,458 |
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 v8::Handle<v8::Value> overloadedMethod2Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.overloadedMethod2");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
if (args.Length() <= 1) {
imp->overloadedMethod(objArg);
return v8::Handle<v8::Value>();
}
EXCEPTION_BLOCK(int, intArg, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)));
imp->overloadedMethod(objArg, intArg);
return v8::Handle<v8::Value>();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static v8::Handle<v8::Value> overloadedMethod2Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.overloadedMethod2");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
if (args.Length() <= 1) {
imp->overloadedMethod(objArg);
return v8::Handle<v8::Value>();
}
EXCEPTION_BLOCK(int, intArg, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)));
imp->overloadedMethod(objArg, intArg);
return v8::Handle<v8::Value>();
}
| 171,098 |
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 dtls1_clear_queues(SSL *s)
{
pitem *item = NULL;
hm_fragment *frag = NULL;
while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
frag = (hm_fragment *)item->data;
dtls1_hm_fragment_free(frag);
pitem_free(item);
}
while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
frag = (hm_fragment *)item->data;
pqueue_free(s->d1->buffered_messages);
}
}
Commit Message:
CWE ID: CWE-399 | static void dtls1_clear_queues(SSL *s)
{
dtls1_clear_received_buffer(s);
dtls1_clear_sent_buffer(s);
}
void dtls1_clear_received_buffer(SSL *s)
{
pitem *item = NULL;
hm_fragment *frag = NULL;
while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
frag = (hm_fragment *)item->data;
dtls1_hm_fragment_free(frag);
pitem_free(item);
}
}
void dtls1_clear_sent_buffer(SSL *s)
{
pitem *item = NULL;
hm_fragment *frag = NULL;
while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
frag = (hm_fragment *)item->data;
pqueue_free(s->d1->buffered_messages);
}
}
| 165,195 |
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 svc_rdma_init(void)
{
dprintk("SVCRDMA Module Init, register RPC RDMA transport\n");
dprintk("\tsvcrdma_ord : %d\n", svcrdma_ord);
dprintk("\tmax_requests : %u\n", svcrdma_max_requests);
dprintk("\tsq_depth : %u\n",
svcrdma_max_requests * RPCRDMA_SQ_DEPTH_MULT);
dprintk("\tmax_bc_requests : %u\n", svcrdma_max_bc_requests);
dprintk("\tmax_inline : %d\n", svcrdma_max_req_size);
svc_rdma_wq = alloc_workqueue("svc_rdma", 0, 0);
if (!svc_rdma_wq)
return -ENOMEM;
if (!svcrdma_table_header)
svcrdma_table_header =
register_sysctl_table(svcrdma_root_table);
/* Register RDMA with the SVC transport switch */
svc_reg_xprt_class(&svc_rdma_class);
#if defined(CONFIG_SUNRPC_BACKCHANNEL)
svc_reg_xprt_class(&svc_rdma_bc_class);
#endif
return 0;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | int svc_rdma_init(void)
{
dprintk("SVCRDMA Module Init, register RPC RDMA transport\n");
dprintk("\tsvcrdma_ord : %d\n", svcrdma_ord);
dprintk("\tmax_requests : %u\n", svcrdma_max_requests);
dprintk("\tmax_bc_requests : %u\n", svcrdma_max_bc_requests);
dprintk("\tmax_inline : %d\n", svcrdma_max_req_size);
svc_rdma_wq = alloc_workqueue("svc_rdma", 0, 0);
if (!svc_rdma_wq)
return -ENOMEM;
if (!svcrdma_table_header)
svcrdma_table_header =
register_sysctl_table(svcrdma_root_table);
/* Register RDMA with the SVC transport switch */
svc_reg_xprt_class(&svc_rdma_class);
#if defined(CONFIG_SUNRPC_BACKCHANNEL)
svc_reg_xprt_class(&svc_rdma_bc_class);
#endif
return 0;
}
| 168,156 |
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: tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){
uint16 edge=0;
tsize_t written=0;
unsigned char* buffer=NULL;
tsize_t bufferoffset=0;
unsigned char* samplebuffer=NULL;
tsize_t samplebufferoffset=0;
tsize_t read=0;
uint16 i=0;
ttile_t tilecount=0;
/* tsize_t tilesize=0; */
ttile_t septilecount=0;
tsize_t septilesize=0;
#ifdef JPEG_SUPPORT
unsigned char* jpt;
float* xfloatp;
uint32 xuint32=0;
#endif
/* Fail if prior error (in particular, can't trust tiff_datasize) */
if (t2p->t2p_error != T2P_ERR_OK)
return(0);
edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0)
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
|| (t2p->pdf_compression == T2P_COMPRESS_JPEG)
#endif
)
){
#ifdef CCITT_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_G4){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
TIFFReverseBits(buffer, t2p->tiff_datasize);
}
t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_ZIP){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
TIFFReverseBits(buffer, t2p->tiff_datasize);
}
t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_OJPEG){
if(! t2p->pdf_ojpegdata){
TIFFError(TIFF2PDF_MODULE,
"No support for OJPEG image %s with "
"bad tables",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
_TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength);
if(edge!=0){
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
buffer[7]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff;
buffer[8]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff;
}
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
buffer[9]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff;
buffer[10]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff;
}
}
bufferoffset=t2p->pdf_ojpegdatalength;
bufferoffset+=TIFFReadRawTile(input,
tile,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
((unsigned char*)buffer)[bufferoffset++]=0xff;
((unsigned char*)buffer)[bufferoffset++]=0xd9;
t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_JPEG){
unsigned char table_end[2];
uint32 count = 0;
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate " TIFF_SIZE_FORMAT " bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(TIFF_SIZE_T) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) {
if (count >= 4) {
int retTIFFReadRawTile;
/* Ignore EOI marker of JpegTables */
_TIFFmemcpy(buffer, jpt, count - 2);
bufferoffset += count - 2;
/* Store last 2 bytes of the JpegTables */
table_end[0] = buffer[bufferoffset-2];
table_end[1] = buffer[bufferoffset-1];
xuint32 = bufferoffset;
bufferoffset -= 2;
retTIFFReadRawTile= TIFFReadRawTile(
input,
tile,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
if( retTIFFReadRawTile < 0 )
{
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
bufferoffset += retTIFFReadRawTile;
/* Overwrite SOI marker of image scan with previously */
/* saved end of JpegTables */
buffer[xuint32-2]=table_end[0];
buffer[xuint32-1]=table_end[1];
}
}
t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
}
#endif
(void)0;
}
if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for "
"t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
read = TIFFReadEncodedTile(
input,
tile,
(tdata_t) &buffer[bufferoffset],
t2p->tiff_datasize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
} else {
if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){
septilesize=TIFFTileSize(input);
septilecount=TIFFNumberOfTiles(input);
/* tilesize=septilesize*t2p->tiff_samplesperpixel; */
tilecount=septilecount/t2p->tiff_samplesperpixel;
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(samplebuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
samplebufferoffset=0;
for(i=0;i<t2p->tiff_samplesperpixel;i++){
read =
TIFFReadEncodedTile(input,
tile + i*tilecount,
(tdata_t) &(samplebuffer[samplebufferoffset]),
septilesize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile + i*tilecount,
TIFFFileName(input));
_TIFFfree(samplebuffer);
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
samplebufferoffset+=read;
}
t2p_sample_planar_separate_to_contig(
t2p,
&(buffer[bufferoffset]),
samplebuffer,
samplebufferoffset);
bufferoffset+=samplebufferoffset;
_TIFFfree(samplebuffer);
}
if(buffer==NULL){
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
read = TIFFReadEncodedTile(
input,
tile,
(tdata_t) &buffer[bufferoffset],
t2p->tiff_datasize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgba_to_rgb(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){
TIFFError(TIFF2PDF_MODULE,
"No support for YCbCr to RGB in tile for %s",
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){
t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
}
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){
t2p_tile_collapse_left(
buffer,
TIFFTileRowSize(input),
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
t2p_disable(output);
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
TIFFSetField(
output,
TIFFTAG_IMAGEWIDTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
} else {
TIFFSetField(
output,
TIFFTAG_IMAGEWIDTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
}
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
TIFFSetField(
output,
TIFFTAG_IMAGELENGTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
TIFFSetField(
output,
TIFFTAG_ROWSPERSTRIP,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
} else {
TIFFSetField(
output,
TIFFTAG_IMAGELENGTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
TIFFSetField(
output,
TIFFTAG_ROWSPERSTRIP,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
}
TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
switch(t2p->pdf_compression){
case T2P_COMPRESS_NONE:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
break;
#ifdef CCITT_SUPPORT
case T2P_COMPRESS_G4:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
break;
#endif
#ifdef JPEG_SUPPORT
case T2P_COMPRESS_JPEG:
if (t2p->tiff_photometric==PHOTOMETRIC_YCBCR) {
uint16 hor = 0, ver = 0;
if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver)!=0) {
if (hor != 0 && ver != 0) {
TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver);
}
}
if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){
TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp);
}
}
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */
if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
} else {
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW);
}
}
if(t2p->pdf_colorspace & T2P_CS_GRAY){
(void)0;
}
if(t2p->pdf_colorspace & T2P_CS_CMYK){
(void)0;
}
if(t2p->pdf_defaultcompressionquality != 0){
TIFFSetField(output,
TIFFTAG_JPEGQUALITY,
t2p->pdf_defaultcompressionquality);
}
break;
#endif
#ifdef ZIP_SUPPORT
case T2P_COMPRESS_ZIP:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE);
if(t2p->pdf_defaultcompressionquality%100 != 0){
TIFFSetField(output,
TIFFTAG_PREDICTOR,
t2p->pdf_defaultcompressionquality % 100);
}
if(t2p->pdf_defaultcompressionquality/100 != 0){
TIFFSetField(output,
TIFFTAG_ZIPQUALITY,
(t2p->pdf_defaultcompressionquality / 100));
}
break;
#endif
default:
break;
}
t2p_enable(output);
t2p->outputwritten = 0;
bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer,
TIFFStripSize(output));
if (buffer != NULL) {
_TIFFfree(buffer);
buffer = NULL;
}
if (bufferoffset == -1) {
TIFFError(TIFF2PDF_MODULE,
"Error writing encoded tile to output PDF %s",
TIFFFileName(output));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
written = t2p->outputwritten;
return(written);
}
Commit Message: * tools/tiff2pdf.c: avoid potential heap-based overflow in
t2p_readwrite_pdf_image_tile().
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2640
CWE ID: CWE-189 | tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){
uint16 edge=0;
tsize_t written=0;
unsigned char* buffer=NULL;
tsize_t bufferoffset=0;
unsigned char* samplebuffer=NULL;
tsize_t samplebufferoffset=0;
tsize_t read=0;
uint16 i=0;
ttile_t tilecount=0;
/* tsize_t tilesize=0; */
ttile_t septilecount=0;
tsize_t septilesize=0;
#ifdef JPEG_SUPPORT
unsigned char* jpt;
float* xfloatp;
uint32 xuint32=0;
#endif
/* Fail if prior error (in particular, can't trust tiff_datasize) */
if (t2p->t2p_error != T2P_ERR_OK)
return(0);
edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0)
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
|| (t2p->pdf_compression == T2P_COMPRESS_JPEG)
#endif
)
){
#ifdef CCITT_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_G4){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
TIFFReverseBits(buffer, t2p->tiff_datasize);
}
t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_ZIP){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
TIFFReverseBits(buffer, t2p->tiff_datasize);
}
t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_OJPEG){
if(! t2p->pdf_ojpegdata){
TIFFError(TIFF2PDF_MODULE,
"No support for OJPEG image %s with "
"bad tables",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
_TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength);
if(edge!=0){
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
buffer[7]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff;
buffer[8]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff;
}
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
buffer[9]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff;
buffer[10]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff;
}
}
bufferoffset=t2p->pdf_ojpegdatalength;
bufferoffset+=TIFFReadRawTile(input,
tile,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
((unsigned char*)buffer)[bufferoffset++]=0xff;
((unsigned char*)buffer)[bufferoffset++]=0xd9;
t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_JPEG){
unsigned char table_end[2];
uint32 count = 0;
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate " TIFF_SIZE_FORMAT " bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(TIFF_SIZE_T) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) {
if (count > 4) {
int retTIFFReadRawTile;
/* Ignore EOI marker of JpegTables */
_TIFFmemcpy(buffer, jpt, count - 2);
bufferoffset += count - 2;
/* Store last 2 bytes of the JpegTables */
table_end[0] = buffer[bufferoffset-2];
table_end[1] = buffer[bufferoffset-1];
xuint32 = bufferoffset;
bufferoffset -= 2;
retTIFFReadRawTile= TIFFReadRawTile(
input,
tile,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
if( retTIFFReadRawTile < 0 )
{
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
bufferoffset += retTIFFReadRawTile;
/* Overwrite SOI marker of image scan with previously */
/* saved end of JpegTables */
buffer[xuint32-2]=table_end[0];
buffer[xuint32-1]=table_end[1];
}
}
t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
}
#endif
(void)0;
}
if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for "
"t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
read = TIFFReadEncodedTile(
input,
tile,
(tdata_t) &buffer[bufferoffset],
t2p->tiff_datasize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
} else {
if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){
septilesize=TIFFTileSize(input);
septilecount=TIFFNumberOfTiles(input);
/* tilesize=septilesize*t2p->tiff_samplesperpixel; */
tilecount=septilecount/t2p->tiff_samplesperpixel;
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(samplebuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
samplebufferoffset=0;
for(i=0;i<t2p->tiff_samplesperpixel;i++){
read =
TIFFReadEncodedTile(input,
tile + i*tilecount,
(tdata_t) &(samplebuffer[samplebufferoffset]),
septilesize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile + i*tilecount,
TIFFFileName(input));
_TIFFfree(samplebuffer);
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
samplebufferoffset+=read;
}
t2p_sample_planar_separate_to_contig(
t2p,
&(buffer[bufferoffset]),
samplebuffer,
samplebufferoffset);
bufferoffset+=samplebufferoffset;
_TIFFfree(samplebuffer);
}
if(buffer==NULL){
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
read = TIFFReadEncodedTile(
input,
tile,
(tdata_t) &buffer[bufferoffset],
t2p->tiff_datasize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgba_to_rgb(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){
TIFFError(TIFF2PDF_MODULE,
"No support for YCbCr to RGB in tile for %s",
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){
t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
}
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){
t2p_tile_collapse_left(
buffer,
TIFFTileRowSize(input),
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
t2p_disable(output);
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
TIFFSetField(
output,
TIFFTAG_IMAGEWIDTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
} else {
TIFFSetField(
output,
TIFFTAG_IMAGEWIDTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
}
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
TIFFSetField(
output,
TIFFTAG_IMAGELENGTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
TIFFSetField(
output,
TIFFTAG_ROWSPERSTRIP,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
} else {
TIFFSetField(
output,
TIFFTAG_IMAGELENGTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
TIFFSetField(
output,
TIFFTAG_ROWSPERSTRIP,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
}
TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
switch(t2p->pdf_compression){
case T2P_COMPRESS_NONE:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
break;
#ifdef CCITT_SUPPORT
case T2P_COMPRESS_G4:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
break;
#endif
#ifdef JPEG_SUPPORT
case T2P_COMPRESS_JPEG:
if (t2p->tiff_photometric==PHOTOMETRIC_YCBCR) {
uint16 hor = 0, ver = 0;
if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver)!=0) {
if (hor != 0 && ver != 0) {
TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver);
}
}
if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){
TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp);
}
}
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */
if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
} else {
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW);
}
}
if(t2p->pdf_colorspace & T2P_CS_GRAY){
(void)0;
}
if(t2p->pdf_colorspace & T2P_CS_CMYK){
(void)0;
}
if(t2p->pdf_defaultcompressionquality != 0){
TIFFSetField(output,
TIFFTAG_JPEGQUALITY,
t2p->pdf_defaultcompressionquality);
}
break;
#endif
#ifdef ZIP_SUPPORT
case T2P_COMPRESS_ZIP:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE);
if(t2p->pdf_defaultcompressionquality%100 != 0){
TIFFSetField(output,
TIFFTAG_PREDICTOR,
t2p->pdf_defaultcompressionquality % 100);
}
if(t2p->pdf_defaultcompressionquality/100 != 0){
TIFFSetField(output,
TIFFTAG_ZIPQUALITY,
(t2p->pdf_defaultcompressionquality / 100));
}
break;
#endif
default:
break;
}
t2p_enable(output);
t2p->outputwritten = 0;
bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer,
TIFFStripSize(output));
if (buffer != NULL) {
_TIFFfree(buffer);
buffer = NULL;
}
if (bufferoffset == -1) {
TIFFError(TIFF2PDF_MODULE,
"Error writing encoded tile to output PDF %s",
TIFFFileName(output));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
written = t2p->outputwritten;
return(written);
}
| 168,531 |
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 compare_img(const vpx_image_t *img1,
const vpx_image_t *img2) {
bool match = (img1->fmt == img2->fmt) &&
(img1->d_w == img2->d_w) &&
(img1->d_h == img2->d_h);
const unsigned int width_y = img1->d_w;
const unsigned int height_y = img1->d_h;
unsigned int i;
for (i = 0; i < height_y; ++i)
match = (memcmp(img1->planes[VPX_PLANE_Y] + i * img1->stride[VPX_PLANE_Y],
img2->planes[VPX_PLANE_Y] + i * img2->stride[VPX_PLANE_Y],
width_y) == 0) && match;
const unsigned int width_uv = (img1->d_w + 1) >> 1;
const unsigned int height_uv = (img1->d_h + 1) >> 1;
for (i = 0; i < height_uv; ++i)
match = (memcmp(img1->planes[VPX_PLANE_U] + i * img1->stride[VPX_PLANE_U],
img2->planes[VPX_PLANE_U] + i * img2->stride[VPX_PLANE_U],
width_uv) == 0) && match;
for (i = 0; i < height_uv; ++i)
match = (memcmp(img1->planes[VPX_PLANE_V] + i * img1->stride[VPX_PLANE_V],
img2->planes[VPX_PLANE_V] + i * img2->stride[VPX_PLANE_V],
width_uv) == 0) && match;
return match;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | static bool compare_img(const vpx_image_t *img1,
const vpx_image_t *img2) {
bool match = (img1->fmt == img2->fmt) &&
(img1->cs == img2->cs) &&
(img1->d_w == img2->d_w) &&
(img1->d_h == img2->d_h);
const unsigned int width_y = img1->d_w;
const unsigned int height_y = img1->d_h;
unsigned int i;
for (i = 0; i < height_y; ++i)
match = (memcmp(img1->planes[VPX_PLANE_Y] + i * img1->stride[VPX_PLANE_Y],
img2->planes[VPX_PLANE_Y] + i * img2->stride[VPX_PLANE_Y],
width_y) == 0) && match;
const unsigned int width_uv = (img1->d_w + 1) >> 1;
const unsigned int height_uv = (img1->d_h + 1) >> 1;
for (i = 0; i < height_uv; ++i)
match = (memcmp(img1->planes[VPX_PLANE_U] + i * img1->stride[VPX_PLANE_U],
img2->planes[VPX_PLANE_U] + i * img2->stride[VPX_PLANE_U],
width_uv) == 0) && match;
for (i = 0; i < height_uv; ++i)
match = (memcmp(img1->planes[VPX_PLANE_V] + i * img1->stride[VPX_PLANE_V],
img2->planes[VPX_PLANE_V] + i * img2->stride[VPX_PLANE_V],
width_uv) == 0) && match;
return match;
}
| 174,541 |
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: virtual void RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | virtual void RemoveObserver(Observer* observer) {
virtual void RemoveObserver(InputMethodLibrary::Observer* observer) {
observers_.RemoveObserver(observer);
}
| 170,503 |
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 *__dma_alloc_coherent(struct device *dev, size_t size,
dma_addr_t *dma_handle, gfp_t flags,
struct dma_attrs *attrs)
{
if (dev == NULL) {
WARN_ONCE(1, "Use an actual device structure for DMA allocation\n");
return NULL;
}
if (IS_ENABLED(CONFIG_ZONE_DMA) &&
dev->coherent_dma_mask <= DMA_BIT_MASK(32))
flags |= GFP_DMA;
if (IS_ENABLED(CONFIG_DMA_CMA) && (flags & __GFP_WAIT)) {
struct page *page;
void *addr;
size = PAGE_ALIGN(size);
page = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT,
get_order(size));
if (!page)
return NULL;
*dma_handle = phys_to_dma(dev, page_to_phys(page));
addr = page_address(page);
if (flags & __GFP_ZERO)
memset(addr, 0, size);
return addr;
} else {
return swiotlb_alloc_coherent(dev, size, dma_handle, flags);
}
}
Commit Message: arm64: dma-mapping: always clear allocated buffers
Buffers allocated by dma_alloc_coherent() are always zeroed on Alpha,
ARM (32bit), MIPS, PowerPC, x86/x86_64 and probably other architectures.
It turned out that some drivers rely on this 'feature'. Allocated buffer
might be also exposed to userspace with dma_mmap() call, so clearing it
is desired from security point of view to avoid exposing random memory
to userspace. This patch unifies dma_alloc_coherent() behavior on ARM64
architecture with other implementations by unconditionally zeroing
allocated buffer.
Cc: <[email protected]> # v3.14+
Signed-off-by: Marek Szyprowski <[email protected]>
Signed-off-by: Will Deacon <[email protected]>
CWE ID: CWE-200 | static void *__dma_alloc_coherent(struct device *dev, size_t size,
dma_addr_t *dma_handle, gfp_t flags,
struct dma_attrs *attrs)
{
if (dev == NULL) {
WARN_ONCE(1, "Use an actual device structure for DMA allocation\n");
return NULL;
}
if (IS_ENABLED(CONFIG_ZONE_DMA) &&
dev->coherent_dma_mask <= DMA_BIT_MASK(32))
flags |= GFP_DMA;
if (IS_ENABLED(CONFIG_DMA_CMA) && (flags & __GFP_WAIT)) {
struct page *page;
void *addr;
size = PAGE_ALIGN(size);
page = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT,
get_order(size));
if (!page)
return NULL;
*dma_handle = phys_to_dma(dev, page_to_phys(page));
addr = page_address(page);
memset(addr, 0, size);
return addr;
} else {
return swiotlb_alloc_coherent(dev, size, dma_handle, flags);
}
}
| 167,471 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void SendHandwritingStroke(const HandwritingStroke& stroke) {
if (!initialized_successfully_)
return;
chromeos::SendHandwritingStroke(input_method_status_connection_, stroke);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | virtual void SendHandwritingStroke(const HandwritingStroke& stroke) {
virtual void SendHandwritingStroke(
const input_method::HandwritingStroke& stroke) {
if (!initialized_successfully_)
return;
ibus_controller_->SendHandwritingStroke(stroke);
}
| 170,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: main(int argc, char **argv)
{
int i, valgrind_mode = 0;
int valgrind_tool = 0;
int valgrind_gdbserver = 0;
char buf[16384], **args, *home;
char valgrind_path[PATH_MAX] = "";
const char *valgrind_log = NULL;
Eina_Bool really_know = EINA_FALSE;
struct sigaction action;
pid_t child = -1;
#ifdef E_CSERVE
pid_t cs_child = -1;
Eina_Bool cs_use = EINA_FALSE;
#endif
#if !defined(__OpenBSD__) && !defined(__NetBSD__) && !defined(__FreeBSD__) && \
!defined(__FreeBSD_kernel__) && !(defined (__MACH__) && defined (__APPLE__))
Eina_Bool restart = EINA_TRUE;
#endif
unsetenv("NOTIFY_SOCKET");
/* Setup USR1 to detach from the child process and let it get gdb by advanced users */
action.sa_sigaction = _sigusr1;
action.sa_flags = SA_RESETHAND;
sigemptyset(&action.sa_mask);
sigaction(SIGUSR1, &action, NULL);
eina_init();
/* reexcute myself with dbus-launch if dbus-launch is not running yet */
if ((!getenv("DBUS_SESSION_BUS_ADDRESS")) &&
(!getenv("DBUS_LAUNCHD_SESSION_BUS_SOCKET")))
{
char **dbus_argv;
dbus_argv = alloca((argc + 3) * sizeof (char *));
dbus_argv[0] = "dbus-launch";
dbus_argv[1] = "--exit-with-session";
copy_args(dbus_argv + 2, argv, argc);
dbus_argv[2 + argc] = NULL;
execvp("dbus-launch", dbus_argv);
}
prefix_determine(argv[0]);
env_set("E_START", argv[0]);
for (i = 1; i < argc; i++)
{
if (!strcmp(argv[i], "-valgrind-gdb"))
valgrind_gdbserver = 1;
else if (!strncmp(argv[i], "-valgrind", sizeof("-valgrind") - 1))
{
const char *val = argv[i] + sizeof("-valgrind") - 1;
if (*val == '\0') valgrind_mode = 1;
else if (*val == '-')
{
val++;
if (!strncmp(val, "log-file=", sizeof("log-file=") - 1))
{
valgrind_log = val + sizeof("log-file=") - 1;
if (*valgrind_log == '\0') valgrind_log = NULL;
}
}
else if (*val == '=')
{
val++;
if (!strcmp(val, "all")) valgrind_mode = VALGRIND_MODE_ALL;
else valgrind_mode = atoi(val);
}
else
printf("Unknown valgrind option: %s\n", argv[i]);
}
else if (!strcmp(argv[i], "-display"))
{
i++;
env_set("DISPLAY", argv[i]);
}
else if (!strcmp(argv[i], "-massif"))
valgrind_tool = 1;
else if (!strcmp(argv[i], "-callgrind"))
valgrind_tool = 2;
else if ((!strcmp(argv[i], "-h")) ||
(!strcmp(argv[i], "-help")) ||
(!strcmp(argv[i], "--help")))
{
printf
(
"Options:\n"
"\t-valgrind[=MODE]\n"
"\t\tRun enlightenment from inside valgrind, mode is OR of:\n"
"\t\t 1 = plain valgrind to catch crashes (default)\n"
"\t\t 2 = trace children (thumbnailer, efm slaves, ...)\n"
"\t\t 4 = check leak\n"
"\t\t 8 = show reachable after processes finish.\n"
"\t\t all = all of above\n"
"\t-massif\n"
"\t\tRun enlightenment from inside massif valgrind tool.\n"
"\t-callgrind\n"
"\t\tRun enlightenment from inside callgrind valgrind tool.\n"
"\t-valgrind-log-file=<FILENAME>\n"
"\t\tSave valgrind log to file, see valgrind's --log-file for details.\n"
"\n"
"Please run:\n"
"\tenlightenment %s\n"
"for more options.\n",
argv[i]);
exit(0);
}
else if (!strcmp(argv[i], "-i-really-know-what-i-am-doing-and-accept-full-responsibility-for-it"))
really_know = EINA_TRUE;
}
if (really_know)
_env_path_append("PATH", eina_prefix_bin_get(pfx));
else
_env_path_prepend("PATH", eina_prefix_bin_get(pfx));
if (valgrind_mode || valgrind_tool)
{
if (!find_valgrind(valgrind_path, sizeof(valgrind_path)))
{
printf("E - valgrind required but no binary found! Ignoring request.\n");
valgrind_mode = 0;
}
}
printf("E - PID=%i, valgrind=%d", getpid(), valgrind_mode);
if (valgrind_mode)
{
printf(" valgrind-command='%s'", valgrind_path);
if (valgrind_log) printf(" valgrind-log-file='%s'", valgrind_log);
}
putchar('\n');
/* mtrack memory tracker support */
home = getenv("HOME");
if (home)
{
FILE *f;
/* if you have ~/.e-mtrack, then the tracker will be enabled
* using the content of this file as the path to the mtrack.so
* shared object that is the mtrack preload */
snprintf(buf, sizeof(buf), "%s/.e-mtrack", home);
f = fopen(buf, "r");
if (f)
{
if (fgets(buf, sizeof(buf), f))
{
int len = strlen(buf);
if ((len > 1) && (buf[len - 1] == '\n'))
{
buf[len - 1] = 0;
len--;
}
env_set("LD_PRELOAD", buf);
env_set("MTRACK", "track");
env_set("E_START_MTRACK", "track");
snprintf(buf, sizeof(buf), "%s/.e-mtrack.log", home);
env_set("MTRACK_TRACE_FILE", buf);
}
fclose(f);
}
}
/* run e directly now */
snprintf(buf, sizeof(buf), "%s/enlightenment", eina_prefix_bin_get(pfx));
args = alloca((argc + 2 + VALGRIND_MAX_ARGS) * sizeof(char *));
i = valgrind_append(args, valgrind_gdbserver, valgrind_mode, valgrind_tool, valgrind_path, valgrind_log);
args[i++] = buf;
copy_args(args + i, argv + 1, argc - 1);
args[i + argc - 1] = NULL;
if (valgrind_tool || valgrind_mode)
really_know = EINA_TRUE;
#if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || \
defined(__FreeBSD_kernel__) || (defined (__MACH__) && defined (__APPLE__))
execv(args[0], args);
#endif
/* not run at the moment !! */
#if !defined(__OpenBSD__) && !defined(__NetBSD__) && !defined(__FreeBSD__) && \
!defined(__FreeBSD_kernel__) && !(defined (__MACH__) && defined (__APPLE__))
#ifdef E_CSERVE
if (getenv("E_CSERVE"))
{
cs_use = EINA_TRUE;
cs_child = _cserve2_start();
}
#endif
/* Now looping until */
while (restart)
{
stop_ptrace = EINA_FALSE;
child = fork();
if (child < 0) /* failed attempt */
return -1;
else if (child == 0)
{
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
/* in the child */
ptrace(PT_TRACE_ME, 0, NULL, NULL);
#endif
execv(args[0], args);
return 0; /* We failed, 0 mean normal exit from E with no restart or crash so let exit */
}
else
{
env_set("E_RESTART", "1");
/* in the parent */
pid_t result;
int status;
Eina_Bool done = EINA_FALSE;
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
ptrace(PT_ATTACH, child, NULL, NULL);
result = waitpid(child, &status, 0);
if ((!really_know) && (!stop_ptrace))
{
if (WIFSTOPPED(status))
ptrace(PT_CONTINUE, child, NULL, NULL);
}
#endif
while (!done)
{
Eina_Bool remember_sigill = EINA_FALSE;
Eina_Bool remember_sigusr1 = EINA_FALSE;
result = waitpid(child, &status, WNOHANG);
if (!result)
{
/* Wait for evas_cserve2 and E */
result = waitpid(-1, &status, 0);
}
if (result == child)
{
if ((WIFSTOPPED(status)) && (!stop_ptrace))
{
char buffer[4096];
char *backtrace_str = NULL;
siginfo_t sig;
int r = 0;
int back;
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
r = ptrace(PT_GETSIGINFO, child, NULL, &sig);
#endif
back = r == 0 &&
sig.si_signo != SIGTRAP ? sig.si_signo : 0;
if (sig.si_signo == SIGUSR1)
{
if (remember_sigill)
remember_sigusr1 = EINA_TRUE;
}
else if (sig.si_signo == SIGILL)
{
remember_sigill = EINA_TRUE;
}
else
{
remember_sigill = EINA_FALSE;
}
if (r != 0 ||
(sig.si_signo != SIGSEGV &&
sig.si_signo != SIGFPE &&
sig.si_signo != SIGABRT))
{
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
ptrace(PT_CONTINUE, child, NULL, back);
#endif
continue;
}
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
/* E18 should be in pause, we can detach */
ptrace(PT_DETACH, child, NULL, back);
#endif
/* And call gdb if available */
r = 0;
if (home)
{
/* call e_sys gdb */
snprintf(buffer, 4096,
"%s/enlightenment/utils/enlightenment_sys gdb %i %s/.e-crashdump.txt",
eina_prefix_lib_get(pfx),
child,
home);
r = system(buffer);
r = system(buffer);
fprintf(stderr, "called gdb with '%s' = %i\n",
buffer, WEXITSTATUS(r));
snprintf(buffer, 4096,
"%s/.e-crashdump.txt",
home);
backtrace_str = strdup(buffer);
r = WEXITSTATUS(r);
}
/* call e_alert */
snprintf(buffer, 4096,
backtrace_str ?
"%s/enlightenment/utils/enlightenment_alert %i %i '%s' %i" :
"%s/enlightenment/utils/enlightenment_alert %i %i '%s' %i",
eina_prefix_lib_get(pfx),
sig.si_signo == SIGSEGV && remember_sigusr1 ? SIGILL : sig.si_signo,
child,
backtrace_str,
r);
r = system(buffer);
/* kill e */
kill(child, SIGKILL);
if (WEXITSTATUS(r) != 1)
{
restart = EINA_FALSE;
}
}
else if (!WIFEXITED(status))
{
done = EINA_TRUE;
}
else if (stop_ptrace)
{
done = EINA_TRUE;
}
}
else if (result == -1)
{
if (errno != EINTR)
{
done = EINA_TRUE;
restart = EINA_FALSE;
}
else
{
if (stop_ptrace)
{
kill(child, SIGSTOP);
usleep(200000);
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
ptrace(PT_DETACH, child, NULL, NULL);
#endif
}
}
}
#ifdef E_CSERVE
else if (cs_use && (result == cs_child))
{
if (WIFSIGNALED(status))
{
printf("E - cserve2 terminated with signal %d\n",
WTERMSIG(status));
cs_child = _cserve2_start();
}
else if (WIFEXITED(status))
{
printf("E - cserve2 exited with code %d\n",
WEXITSTATUS(status));
cs_child = -1;
}
}
#endif
}
}
}
#endif
#ifdef E_CSERVE
if (cs_child > 0)
{
pid_t result;
int status;
alarm(2);
kill(cs_child, SIGINT);
result = waitpid(cs_child, &status, 0);
if (result != cs_child)
{
printf("E - cserve2 did not shutdown in 2 seconds, killing!\n");
kill(cs_child, SIGKILL);
}
}
#endif
return -1;
}
Commit Message:
CWE ID: CWE-264 | main(int argc, char **argv)
{
int i, valgrind_mode = 0;
int valgrind_tool = 0;
int valgrind_gdbserver = 0;
char buf[16384], **args, *home;
char valgrind_path[PATH_MAX] = "";
const char *valgrind_log = NULL;
Eina_Bool really_know = EINA_FALSE;
struct sigaction action;
pid_t child = -1;
#ifdef E_CSERVE
pid_t cs_child = -1;
Eina_Bool cs_use = EINA_FALSE;
#endif
#if !defined(__OpenBSD__) && !defined(__NetBSD__) && !defined(__FreeBSD__) && \
!defined(__FreeBSD_kernel__) && !(defined (__MACH__) && defined (__APPLE__))
Eina_Bool restart = EINA_TRUE;
#endif
unsetenv("NOTIFY_SOCKET");
/* Setup USR1 to detach from the child process and let it get gdb by advanced users */
action.sa_sigaction = _sigusr1;
action.sa_flags = SA_RESETHAND;
sigemptyset(&action.sa_mask);
sigaction(SIGUSR1, &action, NULL);
eina_init();
/* reexcute myself with dbus-launch if dbus-launch is not running yet */
if ((!getenv("DBUS_SESSION_BUS_ADDRESS")) &&
(!getenv("DBUS_LAUNCHD_SESSION_BUS_SOCKET")))
{
char **dbus_argv;
dbus_argv = alloca((argc + 3) * sizeof (char *));
dbus_argv[0] = "dbus-launch";
dbus_argv[1] = "--exit-with-session";
copy_args(dbus_argv + 2, argv, argc);
dbus_argv[2 + argc] = NULL;
execvp("dbus-launch", dbus_argv);
}
prefix_determine(argv[0]);
env_set("E_START", argv[0]);
for (i = 1; i < argc; i++)
{
if (!strcmp(argv[i], "-valgrind-gdb"))
valgrind_gdbserver = 1;
else if (!strncmp(argv[i], "-valgrind", sizeof("-valgrind") - 1))
{
const char *val = argv[i] + sizeof("-valgrind") - 1;
if (*val == '\0') valgrind_mode = 1;
else if (*val == '-')
{
val++;
if (!strncmp(val, "log-file=", sizeof("log-file=") - 1))
{
valgrind_log = val + sizeof("log-file=") - 1;
if (*valgrind_log == '\0') valgrind_log = NULL;
}
}
else if (*val == '=')
{
val++;
if (!strcmp(val, "all")) valgrind_mode = VALGRIND_MODE_ALL;
else valgrind_mode = atoi(val);
}
else
printf("Unknown valgrind option: %s\n", argv[i]);
}
else if (!strcmp(argv[i], "-display"))
{
i++;
env_set("DISPLAY", argv[i]);
}
else if (!strcmp(argv[i], "-massif"))
valgrind_tool = 1;
else if (!strcmp(argv[i], "-callgrind"))
valgrind_tool = 2;
else if ((!strcmp(argv[i], "-h")) ||
(!strcmp(argv[i], "-help")) ||
(!strcmp(argv[i], "--help")))
{
printf
(
"Options:\n"
"\t-valgrind[=MODE]\n"
"\t\tRun enlightenment from inside valgrind, mode is OR of:\n"
"\t\t 1 = plain valgrind to catch crashes (default)\n"
"\t\t 2 = trace children (thumbnailer, efm slaves, ...)\n"
"\t\t 4 = check leak\n"
"\t\t 8 = show reachable after processes finish.\n"
"\t\t all = all of above\n"
"\t-massif\n"
"\t\tRun enlightenment from inside massif valgrind tool.\n"
"\t-callgrind\n"
"\t\tRun enlightenment from inside callgrind valgrind tool.\n"
"\t-valgrind-log-file=<FILENAME>\n"
"\t\tSave valgrind log to file, see valgrind's --log-file for details.\n"
"\n"
"Please run:\n"
"\tenlightenment %s\n"
"for more options.\n",
argv[i]);
exit(0);
}
else if (!strcmp(argv[i], "-i-really-know-what-i-am-doing-and-accept-full-responsibility-for-it"))
really_know = EINA_TRUE;
}
if (really_know)
_env_path_append("PATH", eina_prefix_bin_get(pfx));
else
_env_path_prepend("PATH", eina_prefix_bin_get(pfx));
if (valgrind_mode || valgrind_tool)
{
if (!find_valgrind(valgrind_path, sizeof(valgrind_path)))
{
printf("E - valgrind required but no binary found! Ignoring request.\n");
valgrind_mode = 0;
}
}
printf("E - PID=%i, valgrind=%d", getpid(), valgrind_mode);
if (valgrind_mode)
{
printf(" valgrind-command='%s'", valgrind_path);
if (valgrind_log) printf(" valgrind-log-file='%s'", valgrind_log);
}
putchar('\n');
/* mtrack memory tracker support */
home = getenv("HOME");
if (home)
{
FILE *f;
/* if you have ~/.e-mtrack, then the tracker will be enabled
* using the content of this file as the path to the mtrack.so
* shared object that is the mtrack preload */
snprintf(buf, sizeof(buf), "%s/.e-mtrack", home);
f = fopen(buf, "r");
if (f)
{
if (fgets(buf, sizeof(buf), f))
{
int len = strlen(buf);
if ((len > 1) && (buf[len - 1] == '\n'))
{
buf[len - 1] = 0;
len--;
}
env_set("LD_PRELOAD", buf);
env_set("MTRACK", "track");
env_set("E_START_MTRACK", "track");
snprintf(buf, sizeof(buf), "%s/.e-mtrack.log", home);
env_set("MTRACK_TRACE_FILE", buf);
}
fclose(f);
}
}
/* run e directly now */
snprintf(buf, sizeof(buf), "%s/enlightenment", eina_prefix_bin_get(pfx));
args = alloca((argc + 2 + VALGRIND_MAX_ARGS) * sizeof(char *));
i = valgrind_append(args, valgrind_gdbserver, valgrind_mode, valgrind_tool, valgrind_path, valgrind_log);
args[i++] = buf;
copy_args(args + i, argv + 1, argc - 1);
args[i + argc - 1] = NULL;
if (valgrind_tool || valgrind_mode)
really_know = EINA_TRUE;
#if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || \
defined(__FreeBSD_kernel__) || (defined (__MACH__) && defined (__APPLE__))
execv(args[0], args);
#endif
/* not run at the moment !! */
#if !defined(__OpenBSD__) && !defined(__NetBSD__) && !defined(__FreeBSD__) && \
!defined(__FreeBSD_kernel__) && !(defined (__MACH__) && defined (__APPLE__))
#ifdef E_CSERVE
if (getenv("E_CSERVE"))
{
cs_use = EINA_TRUE;
cs_child = _cserve2_start();
}
#endif
/* Now looping until */
while (restart)
{
stop_ptrace = EINA_FALSE;
child = fork();
if (child < 0) /* failed attempt */
return -1;
else if (child == 0)
{
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
/* in the child */
ptrace(PT_TRACE_ME, 0, NULL, NULL);
#endif
execv(args[0], args);
return 0; /* We failed, 0 mean normal exit from E with no restart or crash so let exit */
}
else
{
env_set("E_RESTART", "1");
/* in the parent */
pid_t result;
int status;
Eina_Bool done = EINA_FALSE;
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
ptrace(PT_ATTACH, child, NULL, NULL);
result = waitpid(child, &status, 0);
if ((!really_know) && (!stop_ptrace))
{
if (WIFSTOPPED(status))
ptrace(PT_CONTINUE, child, NULL, NULL);
}
#endif
while (!done)
{
Eina_Bool remember_sigill = EINA_FALSE;
Eina_Bool remember_sigusr1 = EINA_FALSE;
result = waitpid(child, &status, WNOHANG);
if (!result)
{
/* Wait for evas_cserve2 and E */
result = waitpid(-1, &status, 0);
}
if (result == child)
{
if ((WIFSTOPPED(status)) && (!stop_ptrace))
{
char buffer[4096];
char *backtrace_str = NULL;
siginfo_t sig;
int r = 0;
int back;
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
r = ptrace(PT_GETSIGINFO, child, NULL, &sig);
#endif
back = r == 0 &&
sig.si_signo != SIGTRAP ? sig.si_signo : 0;
if (sig.si_signo == SIGUSR1)
{
if (remember_sigill)
remember_sigusr1 = EINA_TRUE;
}
else if (sig.si_signo == SIGILL)
{
remember_sigill = EINA_TRUE;
}
else
{
remember_sigill = EINA_FALSE;
}
if (r != 0 ||
(sig.si_signo != SIGSEGV &&
sig.si_signo != SIGFPE &&
sig.si_signo != SIGABRT))
{
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
ptrace(PT_CONTINUE, child, NULL, back);
#endif
continue;
}
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
/* E18 should be in pause, we can detach */
ptrace(PT_DETACH, child, NULL, back);
#endif
/* And call gdb if available */
r = 0;
if (home)
{
/* call e_sys gdb */
snprintf(buffer, 4096,
"gdb %i %s/.e-crashdump.txt",
child,
home);
r = system(buffer);
r = system(buffer);
fprintf(stderr, "called gdb with '%s' = %i\n",
buffer, WEXITSTATUS(r));
snprintf(buffer, 4096,
"%s/.e-crashdump.txt",
home);
backtrace_str = strdup(buffer);
r = WEXITSTATUS(r);
}
/* call e_alert */
snprintf(buffer, 4096,
backtrace_str ?
"%s/enlightenment/utils/enlightenment_alert %i %i '%s' %i" :
"%s/enlightenment/utils/enlightenment_alert %i %i '%s' %i",
eina_prefix_lib_get(pfx),
sig.si_signo == SIGSEGV && remember_sigusr1 ? SIGILL : sig.si_signo,
child,
backtrace_str,
r);
r = system(buffer);
/* kill e */
kill(child, SIGKILL);
if (WEXITSTATUS(r) != 1)
{
restart = EINA_FALSE;
}
}
else if (!WIFEXITED(status))
{
done = EINA_TRUE;
}
else if (stop_ptrace)
{
done = EINA_TRUE;
}
}
else if (result == -1)
{
if (errno != EINTR)
{
done = EINA_TRUE;
restart = EINA_FALSE;
}
else
{
if (stop_ptrace)
{
kill(child, SIGSTOP);
usleep(200000);
#ifdef HAVE_SYS_PTRACE_H
if (!really_know)
ptrace(PT_DETACH, child, NULL, NULL);
#endif
}
}
}
#ifdef E_CSERVE
else if (cs_use && (result == cs_child))
{
if (WIFSIGNALED(status))
{
printf("E - cserve2 terminated with signal %d\n",
WTERMSIG(status));
cs_child = _cserve2_start();
}
else if (WIFEXITED(status))
{
printf("E - cserve2 exited with code %d\n",
WEXITSTATUS(status));
cs_child = -1;
}
}
#endif
}
}
}
#endif
#ifdef E_CSERVE
if (cs_child > 0)
{
pid_t result;
int status;
alarm(2);
kill(cs_child, SIGINT);
result = waitpid(cs_child, &status, 0);
if (result != cs_child)
{
printf("E - cserve2 did not shutdown in 2 seconds, killing!\n");
kill(cs_child, SIGKILL);
}
}
#endif
return -1;
}
| 165,511 |
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 string_check(char *buf, const char *buf2)
{
if(strcmp(buf, buf2)) {
/* they shouldn't differ */
printf("sprintf failed:\nwe '%s'\nsystem: '%s'\n",
buf, buf2);
return 1;
}
return 0;
}
Commit Message: printf: fix floating point buffer overflow issues
... and add a bunch of floating point printf tests
CWE ID: CWE-119 | static int string_check(char *buf, const char *buf2)
static int _string_check(int linenumber, char *buf, const char *buf2)
{
if(strcmp(buf, buf2)) {
/* they shouldn't differ */
printf("sprintf line %d failed:\nwe '%s'\nsystem: '%s'\n",
linenumber, buf, buf2);
return 1;
}
return 0;
}
| 169,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: void RenderThreadImpl::Init(
const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
TRACE_EVENT0("startup", "RenderThreadImpl::Init");
base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
base::PlatformThread::CurrentId(),
kTraceEventRendererMainThreadSortIndex);
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
blink::WebView::SetUseExternalPopupMenus(true);
#endif
lazy_tls.Pointer()->Set(this);
ChildProcess::current()->set_main_thread(this);
metrics::InitializeSingleSampleMetricsFactory(
base::BindRepeating(&CreateSingleSampleMetricsProvider,
message_loop()->task_runner(), GetConnector()));
gpu_ = ui::Gpu::Create(
GetConnector(),
IsRunningInMash() ? ui::mojom::kServiceName : mojom::kBrowserServiceName,
GetIOTaskRunner());
viz::mojom::SharedBitmapAllocationNotifierPtr
shared_bitmap_allocation_notifier_ptr;
GetConnector()->BindInterface(
mojom::kBrowserServiceName,
mojo::MakeRequest(&shared_bitmap_allocation_notifier_ptr));
shared_bitmap_manager_ = std::make_unique<viz::ClientSharedBitmapManager>(
viz::mojom::ThreadSafeSharedBitmapAllocationNotifierPtr::Create(
shared_bitmap_allocation_notifier_ptr.PassInterface(),
GetChannel()->ipc_task_runner_refptr()));
notification_dispatcher_ =
new NotificationDispatcher(thread_safe_sender());
AddFilter(notification_dispatcher_->GetFilter());
resource_dispatcher_.reset(new ResourceDispatcher(
this, message_loop()->task_runner()));
resource_message_filter_ =
new ChildResourceMessageFilter(resource_dispatcher_.get());
AddFilter(resource_message_filter_.get());
quota_message_filter_ =
new QuotaMessageFilter(thread_safe_sender());
quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender(),
quota_message_filter_.get()));
AddFilter(quota_message_filter_->GetFilter());
auto registry = std::make_unique<service_manager::BinderRegistry>();
BlinkInterfaceRegistryImpl interface_registry(registry->GetWeakPtr());
InitializeWebKit(resource_task_queue, &interface_registry);
blink_initialized_time_ = base::TimeTicks::Now();
webkit_shared_timer_suspended_ = false;
widget_count_ = 0;
hidden_widget_count_ = 0;
idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
idle_notifications_to_skip_ = 0;
appcache_dispatcher_.reset(
new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
dom_storage_dispatcher_.reset(new DomStorageDispatcher());
main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher());
main_thread_cache_storage_dispatcher_.reset(
new CacheStorageDispatcher(thread_safe_sender()));
file_system_dispatcher_.reset(new FileSystemDispatcher());
resource_dispatch_throttler_.reset(new ResourceDispatchThrottler(
static_cast<RenderThread*>(this), renderer_scheduler_.get(),
base::TimeDelta::FromSecondsD(kThrottledResourceRequestFlushPeriodS),
kMaxResourceRequestsPerFlushWhenThrottled));
resource_dispatcher_->set_message_sender(resource_dispatch_throttler_.get());
blob_message_filter_ = new BlobMessageFilter(GetFileThreadTaskRunner());
AddFilter(blob_message_filter_.get());
vc_manager_.reset(new VideoCaptureImplManager());
browser_plugin_manager_.reset(new BrowserPluginManager());
AddObserver(browser_plugin_manager_.get());
#if BUILDFLAG(ENABLE_WEBRTC)
peer_connection_tracker_.reset(new PeerConnectionTracker());
AddObserver(peer_connection_tracker_.get());
p2p_socket_dispatcher_ = new P2PSocketDispatcher(GetIOTaskRunner().get());
AddFilter(p2p_socket_dispatcher_.get());
peer_connection_factory_.reset(
new PeerConnectionDependencyFactory(p2p_socket_dispatcher_.get()));
aec_dump_message_filter_ = new AecDumpMessageFilter(
GetIOTaskRunner(), message_loop()->task_runner());
AddFilter(aec_dump_message_filter_.get());
#endif // BUILDFLAG(ENABLE_WEBRTC)
audio_input_message_filter_ = new AudioInputMessageFilter(GetIOTaskRunner());
AddFilter(audio_input_message_filter_.get());
scoped_refptr<AudioMessageFilter> audio_message_filter;
if (!base::FeatureList::IsEnabled(
features::kUseMojoAudioOutputStreamFactory)) {
audio_message_filter =
base::MakeRefCounted<AudioMessageFilter>(GetIOTaskRunner());
AddFilter(audio_message_filter.get());
}
audio_ipc_factory_.emplace(std::move(audio_message_filter),
GetIOTaskRunner());
midi_message_filter_ = new MidiMessageFilter(GetIOTaskRunner());
AddFilter(midi_message_filter_.get());
AddFilter((new CacheStorageMessageFilter(thread_safe_sender()))->GetFilter());
AddFilter((new ServiceWorkerContextMessageFilter())->GetFilter());
#if defined(USE_AURA)
if (IsRunningInMash()) {
CreateRenderWidgetWindowTreeClientFactory(GetServiceManagerConnection());
}
#endif
registry->AddInterface(base::Bind(&SharedWorkerFactoryImpl::Create),
base::ThreadTaskRunnerHandle::Get());
GetServiceManagerConnection()->AddConnectionFilter(
std::make_unique<SimpleConnectionFilter>(std::move(registry)));
{
auto registry_with_source_info =
std::make_unique<service_manager::BinderRegistryWithArgs<
const service_manager::BindSourceInfo&>>();
registry_with_source_info->AddInterface(
base::Bind(&CreateFrameFactory), base::ThreadTaskRunnerHandle::Get());
GetServiceManagerConnection()->AddConnectionFilter(
std::make_unique<SimpleConnectionFilterWithSourceInfo>(
std::move(registry_with_source_info)));
}
GetContentClient()->renderer()->RenderThreadStarted();
StartServiceManagerConnection();
GetAssociatedInterfaceRegistry()->AddInterface(
base::Bind(&RenderThreadImpl::OnRendererInterfaceRequest,
base::Unretained(this)));
InitSkiaEventTracer();
base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
skia::SkiaMemoryDumpProvider::GetInstance(), "Skia", nullptr);
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
#if defined(ENABLE_IPC_FUZZER)
if (command_line.HasSwitch(switches::kIpcDumpDirectory)) {
base::FilePath dump_directory =
command_line.GetSwitchValuePath(switches::kIpcDumpDirectory);
IPC::ChannelProxy::OutgoingMessageFilter* filter =
LoadExternalIPCDumper(dump_directory);
GetChannel()->set_outgoing_message_filter(filter);
}
#endif
cc::SetClientNameForMetrics("Renderer");
is_threaded_animation_enabled_ =
!command_line.HasSwitch(cc::switches::kDisableThreadedAnimation);
is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
is_partial_raster_enabled_ =
!command_line.HasSwitch(switches::kDisablePartialRaster);
is_gpu_memory_buffer_compositor_resources_enabled_ = command_line.HasSwitch(
switches::kEnableGpuMemoryBufferCompositorResources);
#if defined(OS_MACOSX)
is_elastic_overscroll_enabled_ = true;
#else
is_elastic_overscroll_enabled_ = false;
#endif
std::string image_texture_target_string =
command_line.GetSwitchValueASCII(switches::kContentImageTextureTarget);
buffer_to_texture_target_map_ =
viz::StringToBufferToTextureTargetMap(image_texture_target_string);
if (command_line.HasSwitch(switches::kDisableLCDText)) {
is_lcd_text_enabled_ = false;
} else if (command_line.HasSwitch(switches::kEnableLCDText)) {
is_lcd_text_enabled_ = true;
} else {
#if defined(OS_ANDROID)
is_lcd_text_enabled_ = false;
#else
is_lcd_text_enabled_ = true;
#endif
}
if (command_line.HasSwitch(switches::kDisableGpuCompositing))
is_gpu_compositing_disabled_ = true;
is_gpu_rasterization_forced_ =
command_line.HasSwitch(switches::kForceGpuRasterization);
is_async_worker_context_enabled_ =
command_line.HasSwitch(switches::kEnableGpuAsyncWorkerContext);
if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
std::string string_value = command_line.GetSwitchValueASCII(
switches::kGpuRasterizationMSAASampleCount);
bool parsed_msaa_sample_count =
base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
DCHECK(parsed_msaa_sample_count) << string_value;
DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
} else {
gpu_rasterization_msaa_sample_count_ = -1;
}
if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
is_distance_field_text_enabled_ = false;
} else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
is_distance_field_text_enabled_ = true;
} else {
is_distance_field_text_enabled_ = false;
}
WebRuntimeFeatures::EnableCompositorImageAnimations(
command_line.HasSwitch(switches::kEnableCompositorImageAnimations));
media::InitializeMediaLibrary();
#if defined(OS_ANDROID)
if (!command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode) &&
media::MediaCodecUtil::IsMediaCodecAvailable()) {
media::EnablePlatformDecoderSupport();
}
#endif
memory_pressure_listener_.reset(new base::MemoryPressureListener(
base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this)),
base::Bind(&RenderThreadImpl::OnSyncMemoryPressure,
base::Unretained(this))));
if (base::FeatureList::IsEnabled(features::kMemoryCoordinator)) {
base::MemoryPressureListener::SetNotificationsSuppressed(true);
mojom::MemoryCoordinatorHandlePtr parent_coordinator;
GetConnector()->BindInterface(mojom::kBrowserServiceName,
mojo::MakeRequest(&parent_coordinator));
memory_coordinator_ = CreateChildMemoryCoordinator(
std::move(parent_coordinator), this);
}
int num_raster_threads = 0;
std::string string_value =
command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
bool parsed_num_raster_threads =
base::StringToInt(string_value, &num_raster_threads);
DCHECK(parsed_num_raster_threads) << string_value;
DCHECK_GT(num_raster_threads, 0);
categorized_worker_pool_->Start(num_raster_threads);
discardable_memory::mojom::DiscardableSharedMemoryManagerPtr manager_ptr;
if (IsRunningInMash()) {
#if defined(USE_AURA)
GetServiceManagerConnection()->GetConnector()->BindInterface(
ui::mojom::kServiceName, &manager_ptr);
#else
NOTREACHED();
#endif
} else {
ChildThread::Get()->GetConnector()->BindInterface(
mojom::kBrowserServiceName, mojo::MakeRequest(&manager_ptr));
}
discardable_shared_memory_manager_ = std::make_unique<
discardable_memory::ClientDiscardableSharedMemoryManager>(
std::move(manager_ptr), GetIOTaskRunner());
base::DiscardableMemoryAllocator::SetInstance(
discardable_shared_memory_manager_.get());
GetConnector()->BindInterface(mojom::kBrowserServiceName,
mojo::MakeRequest(&storage_partition_service_));
#if defined(OS_LINUX)
ChildProcess::current()->SetIOThreadPriority(base::ThreadPriority::DISPLAY);
ChildThreadImpl::current()->SetThreadPriority(
categorized_worker_pool_->background_worker_thread_id(),
base::ThreadPriority::BACKGROUND);
#endif
process_foregrounded_count_ = 0;
needs_to_record_first_active_paint_ = false;
was_backgrounded_time_ = base::TimeTicks::Min();
base::MemoryCoordinatorClientRegistry::GetInstance()->Register(this);
if (!command_line.HasSwitch(switches::kSingleProcess))
base::SequencedWorkerPool::EnableForProcess();
EVP_set_buggy_rsa_parser(
base::FeatureList::IsEnabled(features::kBuggyRSAParser));
GetConnector()->BindInterface(mojom::kBrowserServiceName,
mojo::MakeRequest(&frame_sink_provider_));
if (!is_gpu_compositing_disabled_) {
GetConnector()->BindInterface(
mojom::kBrowserServiceName,
mojo::MakeRequest(&compositing_mode_reporter_));
viz::mojom::CompositingModeWatcherPtr watcher_ptr;
compositing_mode_watcher_binding_.Bind(mojo::MakeRequest(&watcher_ptr));
compositing_mode_reporter_->AddCompositingModeWatcher(
std::move(watcher_ptr));
}
}
Commit Message: Roll src/third_party/boringssl/src 664e99a64..696c13bd6
https://boringssl.googlesource.com/boringssl/+log/664e99a6486c293728097c661332f92bf2d847c6..696c13bd6ab78011adfe7b775519c8b7cc82b604
BUG=778101
Change-Id: I8dda4f3db952597148e3c7937319584698d00e1c
Reviewed-on: https://chromium-review.googlesource.com/747941
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: David Benjamin <[email protected]>
Commit-Queue: Steven Valdez <[email protected]>
Cr-Commit-Position: refs/heads/master@{#513774}
CWE ID: CWE-310 | void RenderThreadImpl::Init(
const scoped_refptr<base::SingleThreadTaskRunner>& resource_task_queue) {
TRACE_EVENT0("startup", "RenderThreadImpl::Init");
base::trace_event::TraceLog::GetInstance()->SetThreadSortIndex(
base::PlatformThread::CurrentId(),
kTraceEventRendererMainThreadSortIndex);
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
blink::WebView::SetUseExternalPopupMenus(true);
#endif
lazy_tls.Pointer()->Set(this);
ChildProcess::current()->set_main_thread(this);
metrics::InitializeSingleSampleMetricsFactory(
base::BindRepeating(&CreateSingleSampleMetricsProvider,
message_loop()->task_runner(), GetConnector()));
gpu_ = ui::Gpu::Create(
GetConnector(),
IsRunningInMash() ? ui::mojom::kServiceName : mojom::kBrowserServiceName,
GetIOTaskRunner());
viz::mojom::SharedBitmapAllocationNotifierPtr
shared_bitmap_allocation_notifier_ptr;
GetConnector()->BindInterface(
mojom::kBrowserServiceName,
mojo::MakeRequest(&shared_bitmap_allocation_notifier_ptr));
shared_bitmap_manager_ = std::make_unique<viz::ClientSharedBitmapManager>(
viz::mojom::ThreadSafeSharedBitmapAllocationNotifierPtr::Create(
shared_bitmap_allocation_notifier_ptr.PassInterface(),
GetChannel()->ipc_task_runner_refptr()));
notification_dispatcher_ =
new NotificationDispatcher(thread_safe_sender());
AddFilter(notification_dispatcher_->GetFilter());
resource_dispatcher_.reset(new ResourceDispatcher(
this, message_loop()->task_runner()));
resource_message_filter_ =
new ChildResourceMessageFilter(resource_dispatcher_.get());
AddFilter(resource_message_filter_.get());
quota_message_filter_ =
new QuotaMessageFilter(thread_safe_sender());
quota_dispatcher_.reset(new QuotaDispatcher(thread_safe_sender(),
quota_message_filter_.get()));
AddFilter(quota_message_filter_->GetFilter());
auto registry = std::make_unique<service_manager::BinderRegistry>();
BlinkInterfaceRegistryImpl interface_registry(registry->GetWeakPtr());
InitializeWebKit(resource_task_queue, &interface_registry);
blink_initialized_time_ = base::TimeTicks::Now();
webkit_shared_timer_suspended_ = false;
widget_count_ = 0;
hidden_widget_count_ = 0;
idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
idle_notifications_to_skip_ = 0;
appcache_dispatcher_.reset(
new AppCacheDispatcher(Get(), new AppCacheFrontendImpl()));
dom_storage_dispatcher_.reset(new DomStorageDispatcher());
main_thread_indexed_db_dispatcher_.reset(new IndexedDBDispatcher());
main_thread_cache_storage_dispatcher_.reset(
new CacheStorageDispatcher(thread_safe_sender()));
file_system_dispatcher_.reset(new FileSystemDispatcher());
resource_dispatch_throttler_.reset(new ResourceDispatchThrottler(
static_cast<RenderThread*>(this), renderer_scheduler_.get(),
base::TimeDelta::FromSecondsD(kThrottledResourceRequestFlushPeriodS),
kMaxResourceRequestsPerFlushWhenThrottled));
resource_dispatcher_->set_message_sender(resource_dispatch_throttler_.get());
blob_message_filter_ = new BlobMessageFilter(GetFileThreadTaskRunner());
AddFilter(blob_message_filter_.get());
vc_manager_.reset(new VideoCaptureImplManager());
browser_plugin_manager_.reset(new BrowserPluginManager());
AddObserver(browser_plugin_manager_.get());
#if BUILDFLAG(ENABLE_WEBRTC)
peer_connection_tracker_.reset(new PeerConnectionTracker());
AddObserver(peer_connection_tracker_.get());
p2p_socket_dispatcher_ = new P2PSocketDispatcher(GetIOTaskRunner().get());
AddFilter(p2p_socket_dispatcher_.get());
peer_connection_factory_.reset(
new PeerConnectionDependencyFactory(p2p_socket_dispatcher_.get()));
aec_dump_message_filter_ = new AecDumpMessageFilter(
GetIOTaskRunner(), message_loop()->task_runner());
AddFilter(aec_dump_message_filter_.get());
#endif // BUILDFLAG(ENABLE_WEBRTC)
audio_input_message_filter_ = new AudioInputMessageFilter(GetIOTaskRunner());
AddFilter(audio_input_message_filter_.get());
scoped_refptr<AudioMessageFilter> audio_message_filter;
if (!base::FeatureList::IsEnabled(
features::kUseMojoAudioOutputStreamFactory)) {
audio_message_filter =
base::MakeRefCounted<AudioMessageFilter>(GetIOTaskRunner());
AddFilter(audio_message_filter.get());
}
audio_ipc_factory_.emplace(std::move(audio_message_filter),
GetIOTaskRunner());
midi_message_filter_ = new MidiMessageFilter(GetIOTaskRunner());
AddFilter(midi_message_filter_.get());
AddFilter((new CacheStorageMessageFilter(thread_safe_sender()))->GetFilter());
AddFilter((new ServiceWorkerContextMessageFilter())->GetFilter());
#if defined(USE_AURA)
if (IsRunningInMash()) {
CreateRenderWidgetWindowTreeClientFactory(GetServiceManagerConnection());
}
#endif
registry->AddInterface(base::Bind(&SharedWorkerFactoryImpl::Create),
base::ThreadTaskRunnerHandle::Get());
GetServiceManagerConnection()->AddConnectionFilter(
std::make_unique<SimpleConnectionFilter>(std::move(registry)));
{
auto registry_with_source_info =
std::make_unique<service_manager::BinderRegistryWithArgs<
const service_manager::BindSourceInfo&>>();
registry_with_source_info->AddInterface(
base::Bind(&CreateFrameFactory), base::ThreadTaskRunnerHandle::Get());
GetServiceManagerConnection()->AddConnectionFilter(
std::make_unique<SimpleConnectionFilterWithSourceInfo>(
std::move(registry_with_source_info)));
}
GetContentClient()->renderer()->RenderThreadStarted();
StartServiceManagerConnection();
GetAssociatedInterfaceRegistry()->AddInterface(
base::Bind(&RenderThreadImpl::OnRendererInterfaceRequest,
base::Unretained(this)));
InitSkiaEventTracer();
base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
skia::SkiaMemoryDumpProvider::GetInstance(), "Skia", nullptr);
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
#if defined(ENABLE_IPC_FUZZER)
if (command_line.HasSwitch(switches::kIpcDumpDirectory)) {
base::FilePath dump_directory =
command_line.GetSwitchValuePath(switches::kIpcDumpDirectory);
IPC::ChannelProxy::OutgoingMessageFilter* filter =
LoadExternalIPCDumper(dump_directory);
GetChannel()->set_outgoing_message_filter(filter);
}
#endif
cc::SetClientNameForMetrics("Renderer");
is_threaded_animation_enabled_ =
!command_line.HasSwitch(cc::switches::kDisableThreadedAnimation);
is_zero_copy_enabled_ = command_line.HasSwitch(switches::kEnableZeroCopy);
is_partial_raster_enabled_ =
!command_line.HasSwitch(switches::kDisablePartialRaster);
is_gpu_memory_buffer_compositor_resources_enabled_ = command_line.HasSwitch(
switches::kEnableGpuMemoryBufferCompositorResources);
#if defined(OS_MACOSX)
is_elastic_overscroll_enabled_ = true;
#else
is_elastic_overscroll_enabled_ = false;
#endif
std::string image_texture_target_string =
command_line.GetSwitchValueASCII(switches::kContentImageTextureTarget);
buffer_to_texture_target_map_ =
viz::StringToBufferToTextureTargetMap(image_texture_target_string);
if (command_line.HasSwitch(switches::kDisableLCDText)) {
is_lcd_text_enabled_ = false;
} else if (command_line.HasSwitch(switches::kEnableLCDText)) {
is_lcd_text_enabled_ = true;
} else {
#if defined(OS_ANDROID)
is_lcd_text_enabled_ = false;
#else
is_lcd_text_enabled_ = true;
#endif
}
if (command_line.HasSwitch(switches::kDisableGpuCompositing))
is_gpu_compositing_disabled_ = true;
is_gpu_rasterization_forced_ =
command_line.HasSwitch(switches::kForceGpuRasterization);
is_async_worker_context_enabled_ =
command_line.HasSwitch(switches::kEnableGpuAsyncWorkerContext);
if (command_line.HasSwitch(switches::kGpuRasterizationMSAASampleCount)) {
std::string string_value = command_line.GetSwitchValueASCII(
switches::kGpuRasterizationMSAASampleCount);
bool parsed_msaa_sample_count =
base::StringToInt(string_value, &gpu_rasterization_msaa_sample_count_);
DCHECK(parsed_msaa_sample_count) << string_value;
DCHECK_GE(gpu_rasterization_msaa_sample_count_, 0);
} else {
gpu_rasterization_msaa_sample_count_ = -1;
}
if (command_line.HasSwitch(switches::kDisableDistanceFieldText)) {
is_distance_field_text_enabled_ = false;
} else if (command_line.HasSwitch(switches::kEnableDistanceFieldText)) {
is_distance_field_text_enabled_ = true;
} else {
is_distance_field_text_enabled_ = false;
}
WebRuntimeFeatures::EnableCompositorImageAnimations(
command_line.HasSwitch(switches::kEnableCompositorImageAnimations));
media::InitializeMediaLibrary();
#if defined(OS_ANDROID)
if (!command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode) &&
media::MediaCodecUtil::IsMediaCodecAvailable()) {
media::EnablePlatformDecoderSupport();
}
#endif
memory_pressure_listener_.reset(new base::MemoryPressureListener(
base::Bind(&RenderThreadImpl::OnMemoryPressure, base::Unretained(this)),
base::Bind(&RenderThreadImpl::OnSyncMemoryPressure,
base::Unretained(this))));
if (base::FeatureList::IsEnabled(features::kMemoryCoordinator)) {
base::MemoryPressureListener::SetNotificationsSuppressed(true);
mojom::MemoryCoordinatorHandlePtr parent_coordinator;
GetConnector()->BindInterface(mojom::kBrowserServiceName,
mojo::MakeRequest(&parent_coordinator));
memory_coordinator_ = CreateChildMemoryCoordinator(
std::move(parent_coordinator), this);
}
int num_raster_threads = 0;
std::string string_value =
command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
bool parsed_num_raster_threads =
base::StringToInt(string_value, &num_raster_threads);
DCHECK(parsed_num_raster_threads) << string_value;
DCHECK_GT(num_raster_threads, 0);
categorized_worker_pool_->Start(num_raster_threads);
discardable_memory::mojom::DiscardableSharedMemoryManagerPtr manager_ptr;
if (IsRunningInMash()) {
#if defined(USE_AURA)
GetServiceManagerConnection()->GetConnector()->BindInterface(
ui::mojom::kServiceName, &manager_ptr);
#else
NOTREACHED();
#endif
} else {
ChildThread::Get()->GetConnector()->BindInterface(
mojom::kBrowserServiceName, mojo::MakeRequest(&manager_ptr));
}
discardable_shared_memory_manager_ = std::make_unique<
discardable_memory::ClientDiscardableSharedMemoryManager>(
std::move(manager_ptr), GetIOTaskRunner());
base::DiscardableMemoryAllocator::SetInstance(
discardable_shared_memory_manager_.get());
GetConnector()->BindInterface(mojom::kBrowserServiceName,
mojo::MakeRequest(&storage_partition_service_));
#if defined(OS_LINUX)
ChildProcess::current()->SetIOThreadPriority(base::ThreadPriority::DISPLAY);
ChildThreadImpl::current()->SetThreadPriority(
categorized_worker_pool_->background_worker_thread_id(),
base::ThreadPriority::BACKGROUND);
#endif
process_foregrounded_count_ = 0;
needs_to_record_first_active_paint_ = false;
was_backgrounded_time_ = base::TimeTicks::Min();
base::MemoryCoordinatorClientRegistry::GetInstance()->Register(this);
if (!command_line.HasSwitch(switches::kSingleProcess))
base::SequencedWorkerPool::EnableForProcess();
GetConnector()->BindInterface(mojom::kBrowserServiceName,
mojo::MakeRequest(&frame_sink_provider_));
if (!is_gpu_compositing_disabled_) {
GetConnector()->BindInterface(
mojom::kBrowserServiceName,
mojo::MakeRequest(&compositing_mode_reporter_));
viz::mojom::CompositingModeWatcherPtr watcher_ptr;
compositing_mode_watcher_binding_.Bind(mojo::MakeRequest(&watcher_ptr));
compositing_mode_reporter_->AddCompositingModeWatcher(
std::move(watcher_ptr));
}
}
| 172,934 |
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: explicit ConsoleCallbackFilter(
base::Callback<void(const base::string16&)> callback)
: callback_(callback) {}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#653137}
CWE ID: CWE-416 | explicit ConsoleCallbackFilter(
| 172,489 |
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 newseg(struct ipc_namespace *ns, struct ipc_params *params)
{
key_t key = params->key;
int shmflg = params->flg;
size_t size = params->u.size;
int error;
struct shmid_kernel *shp;
size_t numpages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
struct file *file;
char name[13];
int id;
vm_flags_t acctflag = 0;
if (size < SHMMIN || size > ns->shm_ctlmax)
return -EINVAL;
if (numpages << PAGE_SHIFT < size)
return -ENOSPC;
if (ns->shm_tot + numpages < ns->shm_tot ||
ns->shm_tot + numpages > ns->shm_ctlall)
return -ENOSPC;
shp = ipc_rcu_alloc(sizeof(*shp));
if (!shp)
return -ENOMEM;
shp->shm_perm.key = key;
shp->shm_perm.mode = (shmflg & S_IRWXUGO);
shp->mlock_user = NULL;
shp->shm_perm.security = NULL;
error = security_shm_alloc(shp);
if (error) {
ipc_rcu_putref(shp, ipc_rcu_free);
return error;
}
sprintf(name, "SYSV%08x", key);
if (shmflg & SHM_HUGETLB) {
struct hstate *hs;
size_t hugesize;
hs = hstate_sizelog((shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK);
if (!hs) {
error = -EINVAL;
goto no_file;
}
hugesize = ALIGN(size, huge_page_size(hs));
/* hugetlb_file_setup applies strict accounting */
if (shmflg & SHM_NORESERVE)
acctflag = VM_NORESERVE;
file = hugetlb_file_setup(name, hugesize, acctflag,
&shp->mlock_user, HUGETLB_SHMFS_INODE,
(shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK);
} else {
/*
* Do not allow no accounting for OVERCOMMIT_NEVER, even
* if it's asked for.
*/
if ((shmflg & SHM_NORESERVE) &&
sysctl_overcommit_memory != OVERCOMMIT_NEVER)
acctflag = VM_NORESERVE;
file = shmem_kernel_file_setup(name, size, acctflag);
}
error = PTR_ERR(file);
if (IS_ERR(file))
goto no_file;
id = ipc_addid(&shm_ids(ns), &shp->shm_perm, ns->shm_ctlmni);
if (id < 0) {
error = id;
goto no_id;
}
shp->shm_cprid = task_tgid_vnr(current);
shp->shm_lprid = 0;
shp->shm_atim = shp->shm_dtim = 0;
shp->shm_ctim = get_seconds();
shp->shm_segsz = size;
shp->shm_nattch = 0;
shp->shm_file = file;
shp->shm_creator = current;
list_add(&shp->shm_clist, ¤t->sysvshm.shm_clist);
/*
* shmid gets reported as "inode#" in /proc/pid/maps.
* proc-ps tools use this. Changing this will break them.
*/
file_inode(file)->i_ino = shp->shm_perm.id;
ns->shm_tot += numpages;
error = shp->shm_perm.id;
ipc_unlock_object(&shp->shm_perm);
rcu_read_unlock();
return error;
no_id:
if (is_file_hugepages(file) && shp->mlock_user)
user_shm_unlock(size, shp->mlock_user);
fput(file);
no_file:
ipc_rcu_putref(shp, shm_rcu_free);
return error;
}
Commit Message: Initialize msg/shm IPC objects before doing ipc_addid()
As reported by Dmitry Vyukov, we really shouldn't do ipc_addid() before
having initialized the IPC object state. Yes, we initialize the IPC
object in a locked state, but with all the lockless RCU lookup work,
that IPC object lock no longer means that the state cannot be seen.
We already did this for the IPC semaphore code (see commit e8577d1f0329:
"ipc/sem.c: fully initialize sem_array before making it visible") but we
clearly forgot about msg and shm.
Reported-by: Dmitry Vyukov <[email protected]>
Cc: Manfred Spraul <[email protected]>
Cc: Davidlohr Bueso <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362 | static int newseg(struct ipc_namespace *ns, struct ipc_params *params)
{
key_t key = params->key;
int shmflg = params->flg;
size_t size = params->u.size;
int error;
struct shmid_kernel *shp;
size_t numpages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
struct file *file;
char name[13];
int id;
vm_flags_t acctflag = 0;
if (size < SHMMIN || size > ns->shm_ctlmax)
return -EINVAL;
if (numpages << PAGE_SHIFT < size)
return -ENOSPC;
if (ns->shm_tot + numpages < ns->shm_tot ||
ns->shm_tot + numpages > ns->shm_ctlall)
return -ENOSPC;
shp = ipc_rcu_alloc(sizeof(*shp));
if (!shp)
return -ENOMEM;
shp->shm_perm.key = key;
shp->shm_perm.mode = (shmflg & S_IRWXUGO);
shp->mlock_user = NULL;
shp->shm_perm.security = NULL;
error = security_shm_alloc(shp);
if (error) {
ipc_rcu_putref(shp, ipc_rcu_free);
return error;
}
sprintf(name, "SYSV%08x", key);
if (shmflg & SHM_HUGETLB) {
struct hstate *hs;
size_t hugesize;
hs = hstate_sizelog((shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK);
if (!hs) {
error = -EINVAL;
goto no_file;
}
hugesize = ALIGN(size, huge_page_size(hs));
/* hugetlb_file_setup applies strict accounting */
if (shmflg & SHM_NORESERVE)
acctflag = VM_NORESERVE;
file = hugetlb_file_setup(name, hugesize, acctflag,
&shp->mlock_user, HUGETLB_SHMFS_INODE,
(shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK);
} else {
/*
* Do not allow no accounting for OVERCOMMIT_NEVER, even
* if it's asked for.
*/
if ((shmflg & SHM_NORESERVE) &&
sysctl_overcommit_memory != OVERCOMMIT_NEVER)
acctflag = VM_NORESERVE;
file = shmem_kernel_file_setup(name, size, acctflag);
}
error = PTR_ERR(file);
if (IS_ERR(file))
goto no_file;
shp->shm_cprid = task_tgid_vnr(current);
shp->shm_lprid = 0;
shp->shm_atim = shp->shm_dtim = 0;
shp->shm_ctim = get_seconds();
shp->shm_segsz = size;
shp->shm_nattch = 0;
shp->shm_file = file;
shp->shm_creator = current;
id = ipc_addid(&shm_ids(ns), &shp->shm_perm, ns->shm_ctlmni);
if (id < 0) {
error = id;
goto no_id;
}
list_add(&shp->shm_clist, ¤t->sysvshm.shm_clist);
/*
* shmid gets reported as "inode#" in /proc/pid/maps.
* proc-ps tools use this. Changing this will break them.
*/
file_inode(file)->i_ino = shp->shm_perm.id;
ns->shm_tot += numpages;
error = shp->shm_perm.id;
ipc_unlock_object(&shp->shm_perm);
rcu_read_unlock();
return error;
no_id:
if (is_file_hugepages(file) && shp->mlock_user)
user_shm_unlock(size, shp->mlock_user);
fput(file);
no_file:
ipc_rcu_putref(shp, shm_rcu_free);
return error;
}
| 166,579 |
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 ImageCapture::ResolveWithMediaTrackConstraints(
MediaTrackConstraints constraints,
ScriptPromiseResolver* resolver) {
DCHECK(resolver);
resolver->Resolve(constraints);
}
Commit Message: Convert MediaTrackConstraints to a ScriptValue
IDLDictionaries such as MediaTrackConstraints should not be stored on
the heap which would happen when binding one as a parameter to a
callback. This change converts the object to a ScriptValue ahead of
time. This is fine because the value will be passed to a
ScriptPromiseResolver that will converted it to a V8 value if it
isn't already.
Bug: 759457
Change-Id: I3009a0f7711cc264aeaae07a36c18a6db8c915c8
Reviewed-on: https://chromium-review.googlesource.com/701358
Reviewed-by: Kentaro Hara <[email protected]>
Commit-Queue: Reilly Grant <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507177}
CWE ID: CWE-416 | void ImageCapture::ResolveWithMediaTrackConstraints(
ScriptValue constraints,
ScriptPromiseResolver* resolver) {
DCHECK(resolver);
resolver->Resolve(constraints);
}
| 172,962 |
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: _PUBLIC_ bool ldap_encode(struct ldap_message *msg,
DATA_BLOB *result, TALLOC_CTX *mem_ctx)
{
struct asn1_data *data = asn1_init(mem_ctx);
int i, j;
if (!data) return false;
asn1_push_tag(data, ASN1_SEQUENCE(0));
asn1_write_Integer(data, msg->messageid);
switch (msg->type) {
case LDAP_TAG_BindRequest: {
struct ldap_BindRequest *r = &msg->r.BindRequest;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
asn1_write_Integer(data, r->version);
asn1_write_OctetString(data, r->dn,
(r->dn != NULL) ? strlen(r->dn) : 0);
switch (r->mechanism) {
case LDAP_AUTH_MECH_SIMPLE:
/* context, primitive */
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0));
asn1_write(data, r->creds.password,
strlen(r->creds.password));
asn1_pop_tag(data);
break;
case LDAP_AUTH_MECH_SASL:
/* context, constructed */
asn1_push_tag(data, ASN1_CONTEXT(3));
asn1_write_OctetString(data, r->creds.SASL.mechanism,
strlen(r->creds.SASL.mechanism));
if (r->creds.SASL.secblob) {
asn1_write_OctetString(data, r->creds.SASL.secblob->data,
r->creds.SASL.secblob->length);
}
asn1_pop_tag(data);
break;
default:
return false;
}
asn1_pop_tag(data);
break;
}
case LDAP_TAG_BindResponse: {
struct ldap_BindResponse *r = &msg->r.BindResponse;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
ldap_encode_response(data, &r->response);
if (r->SASL.secblob) {
asn1_write_ContextSimple(data, 7, r->SASL.secblob);
}
asn1_pop_tag(data);
break;
}
case LDAP_TAG_UnbindRequest: {
/* struct ldap_UnbindRequest *r = &msg->r.UnbindRequest; */
asn1_push_tag(data, ASN1_APPLICATION_SIMPLE(msg->type));
asn1_pop_tag(data);
break;
}
case LDAP_TAG_SearchRequest: {
struct ldap_SearchRequest *r = &msg->r.SearchRequest;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
asn1_write_OctetString(data, r->basedn, strlen(r->basedn));
asn1_write_enumerated(data, r->scope);
asn1_write_enumerated(data, r->deref);
asn1_write_Integer(data, r->sizelimit);
asn1_write_Integer(data, r->timelimit);
asn1_write_BOOLEAN(data, r->attributesonly);
if (!ldap_push_filter(data, r->tree)) {
return false;
}
asn1_push_tag(data, ASN1_SEQUENCE(0));
for (i=0; i<r->num_attributes; i++) {
asn1_write_OctetString(data, r->attributes[i],
strlen(r->attributes[i]));
}
asn1_pop_tag(data);
asn1_pop_tag(data);
break;
}
case LDAP_TAG_SearchResultEntry: {
struct ldap_SearchResEntry *r = &msg->r.SearchResultEntry;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
asn1_write_OctetString(data, r->dn, strlen(r->dn));
asn1_push_tag(data, ASN1_SEQUENCE(0));
for (i=0; i<r->num_attributes; i++) {
struct ldb_message_element *attr = &r->attributes[i];
asn1_push_tag(data, ASN1_SEQUENCE(0));
asn1_write_OctetString(data, attr->name,
strlen(attr->name));
asn1_push_tag(data, ASN1_SEQUENCE(1));
for (j=0; j<attr->num_values; j++) {
asn1_write_OctetString(data,
attr->values[j].data,
attr->values[j].length);
}
asn1_pop_tag(data);
asn1_pop_tag(data);
}
asn1_pop_tag(data);
asn1_pop_tag(data);
break;
}
case LDAP_TAG_SearchResultDone: {
struct ldap_Result *r = &msg->r.SearchResultDone;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
ldap_encode_response(data, r);
asn1_pop_tag(data);
break;
}
case LDAP_TAG_ModifyRequest: {
struct ldap_ModifyRequest *r = &msg->r.ModifyRequest;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
asn1_write_OctetString(data, r->dn, strlen(r->dn));
asn1_push_tag(data, ASN1_SEQUENCE(0));
for (i=0; i<r->num_mods; i++) {
struct ldb_message_element *attrib = &r->mods[i].attrib;
asn1_push_tag(data, ASN1_SEQUENCE(0));
asn1_write_enumerated(data, r->mods[i].type);
asn1_push_tag(data, ASN1_SEQUENCE(0));
asn1_write_OctetString(data, attrib->name,
strlen(attrib->name));
asn1_push_tag(data, ASN1_SET);
for (j=0; j<attrib->num_values; j++) {
asn1_write_OctetString(data,
attrib->values[j].data,
attrib->values[j].length);
}
asn1_pop_tag(data);
asn1_pop_tag(data);
asn1_pop_tag(data);
}
asn1_pop_tag(data);
asn1_pop_tag(data);
break;
}
case LDAP_TAG_ModifyResponse: {
struct ldap_Result *r = &msg->r.ModifyResponse;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
ldap_encode_response(data, r);
asn1_pop_tag(data);
break;
}
case LDAP_TAG_AddRequest: {
struct ldap_AddRequest *r = &msg->r.AddRequest;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
asn1_write_OctetString(data, r->dn, strlen(r->dn));
asn1_push_tag(data, ASN1_SEQUENCE(0));
for (i=0; i<r->num_attributes; i++) {
struct ldb_message_element *attrib = &r->attributes[i];
asn1_push_tag(data, ASN1_SEQUENCE(0));
asn1_write_OctetString(data, attrib->name,
strlen(attrib->name));
asn1_push_tag(data, ASN1_SET);
for (j=0; j<r->attributes[i].num_values; j++) {
asn1_write_OctetString(data,
attrib->values[j].data,
attrib->values[j].length);
}
asn1_pop_tag(data);
asn1_pop_tag(data);
}
asn1_pop_tag(data);
asn1_pop_tag(data);
break;
}
case LDAP_TAG_AddResponse: {
struct ldap_Result *r = &msg->r.AddResponse;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
ldap_encode_response(data, r);
asn1_pop_tag(data);
break;
}
case LDAP_TAG_DelRequest: {
struct ldap_DelRequest *r = &msg->r.DelRequest;
asn1_push_tag(data, ASN1_APPLICATION_SIMPLE(msg->type));
asn1_write(data, r->dn, strlen(r->dn));
asn1_pop_tag(data);
break;
}
case LDAP_TAG_DelResponse: {
struct ldap_Result *r = &msg->r.DelResponse;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
ldap_encode_response(data, r);
asn1_pop_tag(data);
break;
}
case LDAP_TAG_ModifyDNRequest: {
struct ldap_ModifyDNRequest *r = &msg->r.ModifyDNRequest;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
asn1_write_OctetString(data, r->dn, strlen(r->dn));
asn1_write_OctetString(data, r->newrdn, strlen(r->newrdn));
asn1_write_BOOLEAN(data, r->deleteolddn);
if (r->newsuperior) {
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0));
asn1_write(data, r->newsuperior,
strlen(r->newsuperior));
asn1_pop_tag(data);
}
asn1_pop_tag(data);
break;
}
case LDAP_TAG_ModifyDNResponse: {
struct ldap_Result *r = &msg->r.ModifyDNResponse;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
ldap_encode_response(data, r);
asn1_pop_tag(data);
break;
}
case LDAP_TAG_CompareRequest: {
struct ldap_CompareRequest *r = &msg->r.CompareRequest;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
asn1_write_OctetString(data, r->dn, strlen(r->dn));
asn1_push_tag(data, ASN1_SEQUENCE(0));
asn1_write_OctetString(data, r->attribute,
strlen(r->attribute));
asn1_write_OctetString(data, r->value.data,
r->value.length);
asn1_pop_tag(data);
asn1_pop_tag(data);
break;
}
case LDAP_TAG_CompareResponse: {
struct ldap_Result *r = &msg->r.ModifyDNResponse;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
ldap_encode_response(data, r);
asn1_pop_tag(data);
break;
}
case LDAP_TAG_AbandonRequest: {
struct ldap_AbandonRequest *r = &msg->r.AbandonRequest;
asn1_push_tag(data, ASN1_APPLICATION_SIMPLE(msg->type));
asn1_write_implicit_Integer(data, r->messageid);
asn1_pop_tag(data);
break;
}
case LDAP_TAG_SearchResultReference: {
struct ldap_SearchResRef *r = &msg->r.SearchResultReference;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
asn1_write_OctetString(data, r->referral, strlen(r->referral));
asn1_pop_tag(data);
break;
}
case LDAP_TAG_ExtendedRequest: {
struct ldap_ExtendedRequest *r = &msg->r.ExtendedRequest;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0));
asn1_write(data, r->oid, strlen(r->oid));
asn1_pop_tag(data);
if (r->value) {
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1));
asn1_write(data, r->value->data, r->value->length);
asn1_pop_tag(data);
}
asn1_pop_tag(data);
break;
}
case LDAP_TAG_ExtendedResponse: {
struct ldap_ExtendedResponse *r = &msg->r.ExtendedResponse;
asn1_push_tag(data, ASN1_APPLICATION(msg->type));
ldap_encode_response(data, &r->response);
if (r->oid) {
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(10));
asn1_write(data, r->oid, strlen(r->oid));
asn1_pop_tag(data);
}
if (r->value) {
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(11));
asn1_write(data, r->value->data, r->value->length);
asn1_pop_tag(data);
}
asn1_pop_tag(data);
break;
}
default:
return false;
}
if (msg->controls != NULL) {
asn1_push_tag(data, ASN1_CONTEXT(0));
for (i = 0; msg->controls[i] != NULL; i++) {
if (!ldap_encode_control(mem_ctx, data,
msg->controls[i])) {
msg->controls[i])) {
DEBUG(0,("Unable to encode control %s\n",
msg->controls[i]->oid));
return false;
}
}
asn1_pop_tag(data);
}
asn1_pop_tag(data);
if (data->has_error) {
asn1_free(data);
return false;
}
*result = data_blob_talloc(mem_ctx, data->data, data->length);
asn1_free(data);
return true;
}
static const char *blob2string_talloc(TALLOC_CTX *mem_ctx,
char *result = talloc_array(mem_ctx, char, blob.length+1);
memcpy(result, blob.data, blob.length);
result[blob.length] = '\0';
return result;
}
Commit Message:
CWE ID: CWE-399 | _PUBLIC_ bool ldap_encode(struct ldap_message *msg,
DATA_BLOB *result, TALLOC_CTX *mem_ctx)
{
struct asn1_data *data = asn1_init(mem_ctx);
int i, j;
if (!data) return false;
if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err;
if (!asn1_write_Integer(data, msg->messageid)) goto err;
switch (msg->type) {
case LDAP_TAG_BindRequest: {
struct ldap_BindRequest *r = &msg->r.BindRequest;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!asn1_write_Integer(data, r->version)) goto err;
if (!asn1_write_OctetString(data, r->dn,
(r->dn != NULL) ? strlen(r->dn) : 0)) goto err;
switch (r->mechanism) {
case LDAP_AUTH_MECH_SIMPLE:
/* context, primitive */
if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0))) goto err;
if (!asn1_write(data, r->creds.password,
strlen(r->creds.password))) goto err;
if (!asn1_pop_tag(data)) goto err;
break;
case LDAP_AUTH_MECH_SASL:
/* context, constructed */
if (!asn1_push_tag(data, ASN1_CONTEXT(3))) goto err;
if (!asn1_write_OctetString(data, r->creds.SASL.mechanism,
strlen(r->creds.SASL.mechanism))) goto err;
if (r->creds.SASL.secblob) {
if (!asn1_write_OctetString(data, r->creds.SASL.secblob->data,
r->creds.SASL.secblob->length)) goto err;
}
if (!asn1_pop_tag(data)) goto err;
break;
default:
goto err;
}
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_BindResponse: {
struct ldap_BindResponse *r = &msg->r.BindResponse;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!ldap_encode_response(data, &r->response)) goto err;
if (r->SASL.secblob) {
if (!asn1_write_ContextSimple(data, 7, r->SASL.secblob)) goto err;
}
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_UnbindRequest: {
/* struct ldap_UnbindRequest *r = &msg->r.UnbindRequest; */
if (!asn1_push_tag(data, ASN1_APPLICATION_SIMPLE(msg->type))) goto err;
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_SearchRequest: {
struct ldap_SearchRequest *r = &msg->r.SearchRequest;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!asn1_write_OctetString(data, r->basedn, strlen(r->basedn))) goto err;
if (!asn1_write_enumerated(data, r->scope)) goto err;
if (!asn1_write_enumerated(data, r->deref)) goto err;
if (!asn1_write_Integer(data, r->sizelimit)) goto err;
if (!asn1_write_Integer(data, r->timelimit)) goto err;
if (!asn1_write_BOOLEAN(data, r->attributesonly)) goto err;
if (!ldap_push_filter(data, r->tree)) {
goto err;
}
if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err;
for (i=0; i<r->num_attributes; i++) {
if (!asn1_write_OctetString(data, r->attributes[i],
strlen(r->attributes[i]))) goto err;
}
if (!asn1_pop_tag(data)) goto err;
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_SearchResultEntry: {
struct ldap_SearchResEntry *r = &msg->r.SearchResultEntry;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!asn1_write_OctetString(data, r->dn, strlen(r->dn))) goto err;
if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err;
for (i=0; i<r->num_attributes; i++) {
struct ldb_message_element *attr = &r->attributes[i];
if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err;
if (!asn1_write_OctetString(data, attr->name,
strlen(attr->name))) goto err;
if (!asn1_push_tag(data, ASN1_SEQUENCE(1))) goto err;
for (j=0; j<attr->num_values; j++) {
if (!asn1_write_OctetString(data,
attr->values[j].data,
attr->values[j].length)) goto err;
}
if (!asn1_pop_tag(data)) goto err;
if (!asn1_pop_tag(data)) goto err;
}
if (!asn1_pop_tag(data)) goto err;
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_SearchResultDone: {
struct ldap_Result *r = &msg->r.SearchResultDone;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!ldap_encode_response(data, r)) goto err;
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_ModifyRequest: {
struct ldap_ModifyRequest *r = &msg->r.ModifyRequest;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!asn1_write_OctetString(data, r->dn, strlen(r->dn))) goto err;
if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err;
for (i=0; i<r->num_mods; i++) {
struct ldb_message_element *attrib = &r->mods[i].attrib;
if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err;
if (!asn1_write_enumerated(data, r->mods[i].type)) goto err;
if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err;
if (!asn1_write_OctetString(data, attrib->name,
strlen(attrib->name))) goto err;
if (!asn1_push_tag(data, ASN1_SET)) goto err;
for (j=0; j<attrib->num_values; j++) {
if (!asn1_write_OctetString(data,
attrib->values[j].data,
attrib->values[j].length)) goto err;
}
if (!asn1_pop_tag(data)) goto err;
if (!asn1_pop_tag(data)) goto err;
if (!asn1_pop_tag(data)) goto err;
}
if (!asn1_pop_tag(data)) goto err;
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_ModifyResponse: {
struct ldap_Result *r = &msg->r.ModifyResponse;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!ldap_encode_response(data, r)) goto err;
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_AddRequest: {
struct ldap_AddRequest *r = &msg->r.AddRequest;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!asn1_write_OctetString(data, r->dn, strlen(r->dn))) goto err;
if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err;
for (i=0; i<r->num_attributes; i++) {
struct ldb_message_element *attrib = &r->attributes[i];
if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err;
if (!asn1_write_OctetString(data, attrib->name,
strlen(attrib->name))) goto err;
if (!asn1_push_tag(data, ASN1_SET)) goto err;
for (j=0; j<r->attributes[i].num_values; j++) {
if (!asn1_write_OctetString(data,
attrib->values[j].data,
attrib->values[j].length)) goto err;
}
if (!asn1_pop_tag(data)) goto err;
if (!asn1_pop_tag(data)) goto err;
}
if (!asn1_pop_tag(data)) goto err;
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_AddResponse: {
struct ldap_Result *r = &msg->r.AddResponse;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!ldap_encode_response(data, r)) goto err;
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_DelRequest: {
struct ldap_DelRequest *r = &msg->r.DelRequest;
if (!asn1_push_tag(data, ASN1_APPLICATION_SIMPLE(msg->type))) goto err;
if (!asn1_write(data, r->dn, strlen(r->dn))) goto err;
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_DelResponse: {
struct ldap_Result *r = &msg->r.DelResponse;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!ldap_encode_response(data, r)) goto err;
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_ModifyDNRequest: {
struct ldap_ModifyDNRequest *r = &msg->r.ModifyDNRequest;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!asn1_write_OctetString(data, r->dn, strlen(r->dn))) goto err;
if (!asn1_write_OctetString(data, r->newrdn, strlen(r->newrdn))) goto err;
if (!asn1_write_BOOLEAN(data, r->deleteolddn)) goto err;
if (r->newsuperior) {
if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0))) goto err;
if (!asn1_write(data, r->newsuperior,
strlen(r->newsuperior))) goto err;
if (!asn1_pop_tag(data)) goto err;
}
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_ModifyDNResponse: {
struct ldap_Result *r = &msg->r.ModifyDNResponse;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!ldap_encode_response(data, r)) goto err;
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_CompareRequest: {
struct ldap_CompareRequest *r = &msg->r.CompareRequest;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!asn1_write_OctetString(data, r->dn, strlen(r->dn))) goto err;
if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err;
if (!asn1_write_OctetString(data, r->attribute,
strlen(r->attribute))) goto err;
if (!asn1_write_OctetString(data, r->value.data,
r->value.length)) goto err;
if (!asn1_pop_tag(data)) goto err;
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_CompareResponse: {
struct ldap_Result *r = &msg->r.ModifyDNResponse;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!ldap_encode_response(data, r)) goto err;
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_AbandonRequest: {
struct ldap_AbandonRequest *r = &msg->r.AbandonRequest;
if (!asn1_push_tag(data, ASN1_APPLICATION_SIMPLE(msg->type))) goto err;
if (!asn1_write_implicit_Integer(data, r->messageid)) goto err;
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_SearchResultReference: {
struct ldap_SearchResRef *r = &msg->r.SearchResultReference;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!asn1_write_OctetString(data, r->referral, strlen(r->referral))) goto err;
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_ExtendedRequest: {
struct ldap_ExtendedRequest *r = &msg->r.ExtendedRequest;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0))) goto err;
if (!asn1_write(data, r->oid, strlen(r->oid))) goto err;
if (!asn1_pop_tag(data)) goto err;
if (r->value) {
if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1))) goto err;
if (!asn1_write(data, r->value->data, r->value->length)) goto err;
if (!asn1_pop_tag(data)) goto err;
}
if (!asn1_pop_tag(data)) goto err;
break;
}
case LDAP_TAG_ExtendedResponse: {
struct ldap_ExtendedResponse *r = &msg->r.ExtendedResponse;
if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err;
if (!ldap_encode_response(data, &r->response)) goto err;
if (r->oid) {
if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(10))) goto err;
if (!asn1_write(data, r->oid, strlen(r->oid))) goto err;
if (!asn1_pop_tag(data)) goto err;
}
if (r->value) {
if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(11))) goto err;
if (!asn1_write(data, r->value->data, r->value->length)) goto err;
if (!asn1_pop_tag(data)) goto err;
}
if (!asn1_pop_tag(data)) goto err;
break;
}
default:
goto err;
}
if (msg->controls != NULL) {
if (!asn1_push_tag(data, ASN1_CONTEXT(0))) goto err;
for (i = 0; msg->controls[i] != NULL; i++) {
if (!ldap_encode_control(mem_ctx, data,
msg->controls[i])) {
msg->controls[i])) {
DEBUG(0,("Unable to encode control %s\n",
msg->controls[i]->oid));
goto err;
}
}
if (!asn1_pop_tag(data)) goto err;
}
if (!asn1_pop_tag(data)) goto err;
*result = data_blob_talloc(mem_ctx, data->data, data->length);
asn1_free(data);
return true;
err:
asn1_free(data);
return false;
}
static const char *blob2string_talloc(TALLOC_CTX *mem_ctx,
char *result = talloc_array(mem_ctx, char, blob.length+1);
memcpy(result, blob.data, blob.length);
result[blob.length] = '\0';
return result;
}
| 164,592 |
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: GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * rem_host, * rem_port, * protocol;
int opt=0;
/*int proto=0;*/
unsigned short iport, rport;
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return;
}
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
protocol = GetValueFromNameValueList(&data, "Protocol");
rport = (unsigned short)atoi(rem_port);
iport = (unsigned short)atoi(int_port);
/*proto = atoi(protocol);*/
syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol);
/* TODO */
r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
opt, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -5: /* Protocol not supported */
SoapError(h, 705, "ProtocolNotSupported");
break;
default:
SoapError(h, 501, "ActionFailed");
}
ClearNameValueList(&data);
}
Commit Message: GetOutboundPinholeTimeout: check args
CWE ID: CWE-476 | GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * rem_host, * rem_port, * protocol;
int opt=0;
/*int proto=0;*/
unsigned short iport, rport;
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return;
}
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
protocol = GetValueFromNameValueList(&data, "Protocol");
if (!int_port || !ext_port || !protocol)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
rport = (unsigned short)atoi(rem_port);
iport = (unsigned short)atoi(int_port);
/*proto = atoi(protocol);*/
syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol);
/* TODO */
r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
opt, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -5: /* Protocol not supported */
SoapError(h, 705, "ProtocolNotSupported");
break;
default:
SoapError(h, 501, "ActionFailed");
}
ClearNameValueList(&data);
}
| 169,667 |
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: cifs_mount(struct super_block *sb, struct cifs_sb_info *cifs_sb,
char *mount_data_global, const char *devname)
{
int rc;
int xid;
struct smb_vol *volume_info;
struct cifsSesInfo *pSesInfo;
struct cifsTconInfo *tcon;
struct TCP_Server_Info *srvTcp;
char *full_path;
char *mount_data = mount_data_global;
struct tcon_link *tlink;
#ifdef CONFIG_CIFS_DFS_UPCALL
struct dfs_info3_param *referrals = NULL;
unsigned int num_referrals = 0;
int referral_walks_count = 0;
try_mount_again:
#endif
rc = 0;
tcon = NULL;
pSesInfo = NULL;
srvTcp = NULL;
full_path = NULL;
tlink = NULL;
xid = GetXid();
volume_info = kzalloc(sizeof(struct smb_vol), GFP_KERNEL);
if (!volume_info) {
rc = -ENOMEM;
goto out;
}
if (cifs_parse_mount_options(mount_data, devname, volume_info)) {
rc = -EINVAL;
goto out;
}
if (volume_info->nullauth) {
cFYI(1, "null user");
volume_info->username = "";
} else if (volume_info->username) {
/* BB fixme parse for domain name here */
cFYI(1, "Username: %s", volume_info->username);
} else {
cifserror("No username specified");
/* In userspace mount helper we can get user name from alternate
locations such as env variables and files on disk */
rc = -EINVAL;
goto out;
}
/* this is needed for ASCII cp to Unicode converts */
if (volume_info->iocharset == NULL) {
/* load_nls_default cannot return null */
volume_info->local_nls = load_nls_default();
} else {
volume_info->local_nls = load_nls(volume_info->iocharset);
if (volume_info->local_nls == NULL) {
cERROR(1, "CIFS mount error: iocharset %s not found",
volume_info->iocharset);
rc = -ELIBACC;
goto out;
}
}
cifs_sb->local_nls = volume_info->local_nls;
/* get a reference to a tcp session */
srvTcp = cifs_get_tcp_session(volume_info);
if (IS_ERR(srvTcp)) {
rc = PTR_ERR(srvTcp);
goto out;
}
/* get a reference to a SMB session */
pSesInfo = cifs_get_smb_ses(srvTcp, volume_info);
if (IS_ERR(pSesInfo)) {
rc = PTR_ERR(pSesInfo);
pSesInfo = NULL;
goto mount_fail_check;
}
setup_cifs_sb(volume_info, cifs_sb);
if (pSesInfo->capabilities & CAP_LARGE_FILES)
sb->s_maxbytes = MAX_LFS_FILESIZE;
else
sb->s_maxbytes = MAX_NON_LFS;
/* BB FIXME fix time_gran to be larger for LANMAN sessions */
sb->s_time_gran = 100;
/* search for existing tcon to this server share */
tcon = cifs_get_tcon(pSesInfo, volume_info);
if (IS_ERR(tcon)) {
rc = PTR_ERR(tcon);
tcon = NULL;
goto remote_path_check;
}
/* do not care if following two calls succeed - informational */
if (!tcon->ipc) {
CIFSSMBQFSDeviceInfo(xid, tcon);
CIFSSMBQFSAttributeInfo(xid, tcon);
}
/* tell server which Unix caps we support */
if (tcon->ses->capabilities & CAP_UNIX)
/* reset of caps checks mount to see if unix extensions
disabled for just this mount */
reset_cifs_unix_caps(xid, tcon, sb, volume_info);
else
tcon->unix_ext = 0; /* server does not support them */
/* convert forward to back slashes in prepath here if needed */
if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS) == 0)
convert_delimiter(cifs_sb->prepath, CIFS_DIR_SEP(cifs_sb));
if ((tcon->unix_ext == 0) && (cifs_sb->rsize > (1024 * 127))) {
cifs_sb->rsize = 1024 * 127;
cFYI(DBG2, "no very large read support, rsize now 127K");
}
if (!(tcon->ses->capabilities & CAP_LARGE_WRITE_X))
cifs_sb->wsize = min(cifs_sb->wsize,
(tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE));
if (!(tcon->ses->capabilities & CAP_LARGE_READ_X))
cifs_sb->rsize = min(cifs_sb->rsize,
(tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE));
remote_path_check:
/* check if a whole path (including prepath) is not remote */
if (!rc && cifs_sb->prepathlen && tcon) {
/* build_path_to_root works only when we have a valid tcon */
full_path = cifs_build_path_to_root(cifs_sb, tcon);
if (full_path == NULL) {
rc = -ENOMEM;
goto mount_fail_check;
}
rc = is_path_accessible(xid, tcon, cifs_sb, full_path);
if (rc != 0 && rc != -EREMOTE) {
kfree(full_path);
goto mount_fail_check;
}
kfree(full_path);
}
/* get referral if needed */
if (rc == -EREMOTE) {
#ifdef CONFIG_CIFS_DFS_UPCALL
if (referral_walks_count > MAX_NESTED_LINKS) {
/*
* BB: when we implement proper loop detection,
* we will remove this check. But now we need it
* to prevent an indefinite loop if 'DFS tree' is
* misconfigured (i.e. has loops).
*/
rc = -ELOOP;
goto mount_fail_check;
}
/* convert forward to back slashes in prepath here if needed */
if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS) == 0)
convert_delimiter(cifs_sb->prepath,
CIFS_DIR_SEP(cifs_sb));
full_path = build_unc_path_to_root(volume_info, cifs_sb);
if (IS_ERR(full_path)) {
rc = PTR_ERR(full_path);
goto mount_fail_check;
}
cFYI(1, "Getting referral for: %s", full_path);
rc = get_dfs_path(xid, pSesInfo , full_path + 1,
cifs_sb->local_nls, &num_referrals, &referrals,
cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR);
if (!rc && num_referrals > 0) {
char *fake_devname = NULL;
if (mount_data != mount_data_global)
kfree(mount_data);
mount_data = cifs_compose_mount_options(
cifs_sb->mountdata, full_path + 1,
referrals, &fake_devname);
free_dfs_info_array(referrals, num_referrals);
kfree(fake_devname);
kfree(full_path);
if (IS_ERR(mount_data)) {
rc = PTR_ERR(mount_data);
mount_data = NULL;
goto mount_fail_check;
}
if (tcon)
cifs_put_tcon(tcon);
else if (pSesInfo)
cifs_put_smb_ses(pSesInfo);
cleanup_volume_info(&volume_info);
referral_walks_count++;
FreeXid(xid);
goto try_mount_again;
}
#else /* No DFS support, return error on mount */
rc = -EOPNOTSUPP;
#endif
}
if (rc)
goto mount_fail_check;
/* now, hang the tcon off of the superblock */
tlink = kzalloc(sizeof *tlink, GFP_KERNEL);
if (tlink == NULL) {
rc = -ENOMEM;
goto mount_fail_check;
}
tlink->tl_uid = pSesInfo->linux_uid;
tlink->tl_tcon = tcon;
tlink->tl_time = jiffies;
set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
cifs_sb->master_tlink = tlink;
spin_lock(&cifs_sb->tlink_tree_lock);
tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
spin_unlock(&cifs_sb->tlink_tree_lock);
queue_delayed_work(system_nrt_wq, &cifs_sb->prune_tlinks,
TLINK_IDLE_EXPIRE);
mount_fail_check:
/* on error free sesinfo and tcon struct if needed */
if (rc) {
if (mount_data != mount_data_global)
kfree(mount_data);
/* If find_unc succeeded then rc == 0 so we can not end */
/* up accidentally freeing someone elses tcon struct */
if (tcon)
cifs_put_tcon(tcon);
else if (pSesInfo)
cifs_put_smb_ses(pSesInfo);
else
cifs_put_tcp_session(srvTcp);
goto out;
}
/* volume_info->password is freed above when existing session found
(in which case it is not needed anymore) but when new sesion is created
the password ptr is put in the new session structure (in which case the
password will be freed at unmount time) */
out:
/* zero out password before freeing */
cleanup_volume_info(&volume_info);
FreeXid(xid);
return rc;
}
Commit Message: cifs: always do is_path_accessible check in cifs_mount
Currently, we skip doing the is_path_accessible check in cifs_mount if
there is no prefixpath. I have a report of at least one server however
that allows a TREE_CONNECT to a share that has a DFS referral at its
root. The reporter in this case was using a UNC that had no prefixpath,
so the is_path_accessible check was not triggered and the box later hit
a BUG() because we were chasing a DFS referral on the root dentry for
the mount.
This patch fixes this by removing the check for a zero-length
prefixpath. That should make the is_path_accessible check be done in
this situation and should allow the client to chase the DFS referral at
mount time instead.
Cc: [email protected]
Reported-and-Tested-by: Yogesh Sharma <[email protected]>
Signed-off-by: Jeff Layton <[email protected]>
Signed-off-by: Steve French <[email protected]>
CWE ID: CWE-20 | cifs_mount(struct super_block *sb, struct cifs_sb_info *cifs_sb,
char *mount_data_global, const char *devname)
{
int rc;
int xid;
struct smb_vol *volume_info;
struct cifsSesInfo *pSesInfo;
struct cifsTconInfo *tcon;
struct TCP_Server_Info *srvTcp;
char *full_path;
char *mount_data = mount_data_global;
struct tcon_link *tlink;
#ifdef CONFIG_CIFS_DFS_UPCALL
struct dfs_info3_param *referrals = NULL;
unsigned int num_referrals = 0;
int referral_walks_count = 0;
try_mount_again:
#endif
rc = 0;
tcon = NULL;
pSesInfo = NULL;
srvTcp = NULL;
full_path = NULL;
tlink = NULL;
xid = GetXid();
volume_info = kzalloc(sizeof(struct smb_vol), GFP_KERNEL);
if (!volume_info) {
rc = -ENOMEM;
goto out;
}
if (cifs_parse_mount_options(mount_data, devname, volume_info)) {
rc = -EINVAL;
goto out;
}
if (volume_info->nullauth) {
cFYI(1, "null user");
volume_info->username = "";
} else if (volume_info->username) {
/* BB fixme parse for domain name here */
cFYI(1, "Username: %s", volume_info->username);
} else {
cifserror("No username specified");
/* In userspace mount helper we can get user name from alternate
locations such as env variables and files on disk */
rc = -EINVAL;
goto out;
}
/* this is needed for ASCII cp to Unicode converts */
if (volume_info->iocharset == NULL) {
/* load_nls_default cannot return null */
volume_info->local_nls = load_nls_default();
} else {
volume_info->local_nls = load_nls(volume_info->iocharset);
if (volume_info->local_nls == NULL) {
cERROR(1, "CIFS mount error: iocharset %s not found",
volume_info->iocharset);
rc = -ELIBACC;
goto out;
}
}
cifs_sb->local_nls = volume_info->local_nls;
/* get a reference to a tcp session */
srvTcp = cifs_get_tcp_session(volume_info);
if (IS_ERR(srvTcp)) {
rc = PTR_ERR(srvTcp);
goto out;
}
/* get a reference to a SMB session */
pSesInfo = cifs_get_smb_ses(srvTcp, volume_info);
if (IS_ERR(pSesInfo)) {
rc = PTR_ERR(pSesInfo);
pSesInfo = NULL;
goto mount_fail_check;
}
setup_cifs_sb(volume_info, cifs_sb);
if (pSesInfo->capabilities & CAP_LARGE_FILES)
sb->s_maxbytes = MAX_LFS_FILESIZE;
else
sb->s_maxbytes = MAX_NON_LFS;
/* BB FIXME fix time_gran to be larger for LANMAN sessions */
sb->s_time_gran = 100;
/* search for existing tcon to this server share */
tcon = cifs_get_tcon(pSesInfo, volume_info);
if (IS_ERR(tcon)) {
rc = PTR_ERR(tcon);
tcon = NULL;
goto remote_path_check;
}
/* do not care if following two calls succeed - informational */
if (!tcon->ipc) {
CIFSSMBQFSDeviceInfo(xid, tcon);
CIFSSMBQFSAttributeInfo(xid, tcon);
}
/* tell server which Unix caps we support */
if (tcon->ses->capabilities & CAP_UNIX)
/* reset of caps checks mount to see if unix extensions
disabled for just this mount */
reset_cifs_unix_caps(xid, tcon, sb, volume_info);
else
tcon->unix_ext = 0; /* server does not support them */
/* convert forward to back slashes in prepath here if needed */
if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS) == 0)
convert_delimiter(cifs_sb->prepath, CIFS_DIR_SEP(cifs_sb));
if ((tcon->unix_ext == 0) && (cifs_sb->rsize > (1024 * 127))) {
cifs_sb->rsize = 1024 * 127;
cFYI(DBG2, "no very large read support, rsize now 127K");
}
if (!(tcon->ses->capabilities & CAP_LARGE_WRITE_X))
cifs_sb->wsize = min(cifs_sb->wsize,
(tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE));
if (!(tcon->ses->capabilities & CAP_LARGE_READ_X))
cifs_sb->rsize = min(cifs_sb->rsize,
(tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE));
remote_path_check:
/* check if a whole path (including prepath) is not remote */
if (!rc && tcon) {
/* build_path_to_root works only when we have a valid tcon */
full_path = cifs_build_path_to_root(cifs_sb, tcon);
if (full_path == NULL) {
rc = -ENOMEM;
goto mount_fail_check;
}
rc = is_path_accessible(xid, tcon, cifs_sb, full_path);
if (rc != 0 && rc != -EREMOTE) {
kfree(full_path);
goto mount_fail_check;
}
kfree(full_path);
}
/* get referral if needed */
if (rc == -EREMOTE) {
#ifdef CONFIG_CIFS_DFS_UPCALL
if (referral_walks_count > MAX_NESTED_LINKS) {
/*
* BB: when we implement proper loop detection,
* we will remove this check. But now we need it
* to prevent an indefinite loop if 'DFS tree' is
* misconfigured (i.e. has loops).
*/
rc = -ELOOP;
goto mount_fail_check;
}
/* convert forward to back slashes in prepath here if needed */
if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS) == 0)
convert_delimiter(cifs_sb->prepath,
CIFS_DIR_SEP(cifs_sb));
full_path = build_unc_path_to_root(volume_info, cifs_sb);
if (IS_ERR(full_path)) {
rc = PTR_ERR(full_path);
goto mount_fail_check;
}
cFYI(1, "Getting referral for: %s", full_path);
rc = get_dfs_path(xid, pSesInfo , full_path + 1,
cifs_sb->local_nls, &num_referrals, &referrals,
cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR);
if (!rc && num_referrals > 0) {
char *fake_devname = NULL;
if (mount_data != mount_data_global)
kfree(mount_data);
mount_data = cifs_compose_mount_options(
cifs_sb->mountdata, full_path + 1,
referrals, &fake_devname);
free_dfs_info_array(referrals, num_referrals);
kfree(fake_devname);
kfree(full_path);
if (IS_ERR(mount_data)) {
rc = PTR_ERR(mount_data);
mount_data = NULL;
goto mount_fail_check;
}
if (tcon)
cifs_put_tcon(tcon);
else if (pSesInfo)
cifs_put_smb_ses(pSesInfo);
cleanup_volume_info(&volume_info);
referral_walks_count++;
FreeXid(xid);
goto try_mount_again;
}
#else /* No DFS support, return error on mount */
rc = -EOPNOTSUPP;
#endif
}
if (rc)
goto mount_fail_check;
/* now, hang the tcon off of the superblock */
tlink = kzalloc(sizeof *tlink, GFP_KERNEL);
if (tlink == NULL) {
rc = -ENOMEM;
goto mount_fail_check;
}
tlink->tl_uid = pSesInfo->linux_uid;
tlink->tl_tcon = tcon;
tlink->tl_time = jiffies;
set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
cifs_sb->master_tlink = tlink;
spin_lock(&cifs_sb->tlink_tree_lock);
tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
spin_unlock(&cifs_sb->tlink_tree_lock);
queue_delayed_work(system_nrt_wq, &cifs_sb->prune_tlinks,
TLINK_IDLE_EXPIRE);
mount_fail_check:
/* on error free sesinfo and tcon struct if needed */
if (rc) {
if (mount_data != mount_data_global)
kfree(mount_data);
/* If find_unc succeeded then rc == 0 so we can not end */
/* up accidentally freeing someone elses tcon struct */
if (tcon)
cifs_put_tcon(tcon);
else if (pSesInfo)
cifs_put_smb_ses(pSesInfo);
else
cifs_put_tcp_session(srvTcp);
goto out;
}
/* volume_info->password is freed above when existing session found
(in which case it is not needed anymore) but when new sesion is created
the password ptr is put in the new session structure (in which case the
password will be freed at unmount time) */
out:
/* zero out password before freeing */
cleanup_volume_info(&volume_info);
FreeXid(xid);
return rc;
}
| 165,745 |
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 tomoyo_mount_acl(struct tomoyo_request_info *r, char *dev_name,
struct path *dir, char *type, unsigned long flags)
{
struct path path;
struct file_system_type *fstype = NULL;
const char *requested_type = NULL;
const char *requested_dir_name = NULL;
const char *requested_dev_name = NULL;
struct tomoyo_path_info rtype;
struct tomoyo_path_info rdev;
struct tomoyo_path_info rdir;
int need_dev = 0;
int error = -ENOMEM;
/* Get fstype. */
requested_type = tomoyo_encode(type);
if (!requested_type)
goto out;
rtype.name = requested_type;
tomoyo_fill_path_info(&rtype);
/* Get mount point. */
requested_dir_name = tomoyo_realpath_from_path(dir);
if (!requested_dir_name) {
error = -ENOMEM;
goto out;
}
rdir.name = requested_dir_name;
tomoyo_fill_path_info(&rdir);
/* Compare fs name. */
if (!strcmp(type, TOMOYO_MOUNT_REMOUNT_KEYWORD)) {
/* dev_name is ignored. */
} else if (!strcmp(type, TOMOYO_MOUNT_MAKE_UNBINDABLE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_PRIVATE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_SLAVE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_SHARED_KEYWORD)) {
/* dev_name is ignored. */
} else if (!strcmp(type, TOMOYO_MOUNT_BIND_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MOVE_KEYWORD)) {
need_dev = -1; /* dev_name is a directory */
} else {
fstype = get_fs_type(type);
if (!fstype) {
error = -ENODEV;
goto out;
}
if (fstype->fs_flags & FS_REQUIRES_DEV)
/* dev_name is a block device file. */
need_dev = 1;
}
if (need_dev) {
/* Get mount point or device file. */
if (kern_path(dev_name, LOOKUP_FOLLOW, &path)) {
error = -ENOENT;
goto out;
}
requested_dev_name = tomoyo_realpath_from_path(&path);
path_put(&path);
if (!requested_dev_name) {
error = -ENOENT;
goto out;
}
} else {
/* Map dev_name to "<NULL>" if no dev_name given. */
if (!dev_name)
dev_name = "<NULL>";
requested_dev_name = tomoyo_encode(dev_name);
if (!requested_dev_name) {
error = -ENOMEM;
goto out;
}
}
rdev.name = requested_dev_name;
tomoyo_fill_path_info(&rdev);
r->param_type = TOMOYO_TYPE_MOUNT_ACL;
r->param.mount.need_dev = need_dev;
r->param.mount.dev = &rdev;
r->param.mount.dir = &rdir;
r->param.mount.type = &rtype;
r->param.mount.flags = flags;
do {
tomoyo_check_acl(r, tomoyo_check_mount_acl);
error = tomoyo_audit_mount_log(r);
} while (error == TOMOYO_RETRY_REQUEST);
out:
kfree(requested_dev_name);
kfree(requested_dir_name);
if (fstype)
put_filesystem(fstype);
kfree(requested_type);
return error;
}
Commit Message: TOMOYO: Fix oops in tomoyo_mount_acl().
In tomoyo_mount_acl() since 2.6.36, kern_path() was called without checking
dev_name != NULL. As a result, an unprivileged user can trigger oops by issuing
mount(NULL, "/", "ext3", 0, NULL) request.
Fix this by checking dev_name != NULL before calling kern_path(dev_name).
Signed-off-by: Tetsuo Handa <[email protected]>
Cc: [email protected]
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-20 | static int tomoyo_mount_acl(struct tomoyo_request_info *r, char *dev_name,
struct path *dir, char *type, unsigned long flags)
{
struct path path;
struct file_system_type *fstype = NULL;
const char *requested_type = NULL;
const char *requested_dir_name = NULL;
const char *requested_dev_name = NULL;
struct tomoyo_path_info rtype;
struct tomoyo_path_info rdev;
struct tomoyo_path_info rdir;
int need_dev = 0;
int error = -ENOMEM;
/* Get fstype. */
requested_type = tomoyo_encode(type);
if (!requested_type)
goto out;
rtype.name = requested_type;
tomoyo_fill_path_info(&rtype);
/* Get mount point. */
requested_dir_name = tomoyo_realpath_from_path(dir);
if (!requested_dir_name) {
error = -ENOMEM;
goto out;
}
rdir.name = requested_dir_name;
tomoyo_fill_path_info(&rdir);
/* Compare fs name. */
if (!strcmp(type, TOMOYO_MOUNT_REMOUNT_KEYWORD)) {
/* dev_name is ignored. */
} else if (!strcmp(type, TOMOYO_MOUNT_MAKE_UNBINDABLE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_PRIVATE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_SLAVE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_SHARED_KEYWORD)) {
/* dev_name is ignored. */
} else if (!strcmp(type, TOMOYO_MOUNT_BIND_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MOVE_KEYWORD)) {
need_dev = -1; /* dev_name is a directory */
} else {
fstype = get_fs_type(type);
if (!fstype) {
error = -ENODEV;
goto out;
}
if (fstype->fs_flags & FS_REQUIRES_DEV)
/* dev_name is a block device file. */
need_dev = 1;
}
if (need_dev) {
/* Get mount point or device file. */
if (!dev_name || kern_path(dev_name, LOOKUP_FOLLOW, &path)) {
error = -ENOENT;
goto out;
}
requested_dev_name = tomoyo_realpath_from_path(&path);
path_put(&path);
if (!requested_dev_name) {
error = -ENOENT;
goto out;
}
} else {
/* Map dev_name to "<NULL>" if no dev_name given. */
if (!dev_name)
dev_name = "<NULL>";
requested_dev_name = tomoyo_encode(dev_name);
if (!requested_dev_name) {
error = -ENOMEM;
goto out;
}
}
rdev.name = requested_dev_name;
tomoyo_fill_path_info(&rdev);
r->param_type = TOMOYO_TYPE_MOUNT_ACL;
r->param.mount.need_dev = need_dev;
r->param.mount.dev = &rdev;
r->param.mount.dir = &rdir;
r->param.mount.type = &rtype;
r->param.mount.flags = flags;
do {
tomoyo_check_acl(r, tomoyo_check_mount_acl);
error = tomoyo_audit_mount_log(r);
} while (error == TOMOYO_RETRY_REQUEST);
out:
kfree(requested_dev_name);
kfree(requested_dir_name);
if (fstype)
put_filesystem(fstype);
kfree(requested_type);
return error;
}
| 165,856 |
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 put_filp(struct file *file)
{
if (atomic_long_dec_and_test(&file->f_count)) {
security_file_free(file);
file_sb_list_del(file);
file_free(file);
}
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | void put_filp(struct file *file)
{
if (atomic_long_dec_and_test(&file->f_count)) {
security_file_free(file);
file_free(file);
}
}
| 166,804 |
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: AcceleratedStaticBitmapImage::AcceleratedStaticBitmapImage(
sk_sp<SkImage> image,
base::WeakPtr<WebGraphicsContext3DProviderWrapper>&&
context_provider_wrapper)
: paint_image_content_id_(cc::PaintImage::GetNextContentId()) {
CHECK(image && image->isTextureBacked());
texture_holder_ = std::make_unique<SkiaTextureHolder>(
std::move(image), std::move(context_provider_wrapper));
thread_checker_.DetachFromThread();
}
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 | AcceleratedStaticBitmapImage::AcceleratedStaticBitmapImage(
sk_sp<SkImage> image,
base::WeakPtr<WebGraphicsContext3DProviderWrapper>&&
context_provider_wrapper)
: paint_image_content_id_(cc::PaintImage::GetNextContentId()) {
CHECK(image && image->isTextureBacked());
texture_holder_ = std::make_unique<SkiaTextureHolder>(
std::move(image), std::move(context_provider_wrapper));
}
| 172,588 |
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: bdfReadCharacters(FontFilePtr file, FontPtr pFont, bdfFileState *pState,
int bit, int byte, int glyph, int scan)
{
unsigned char *line;
register CharInfoPtr ci;
int i,
ndx,
nchars,
nignored;
unsigned int char_row, char_col;
int numEncodedGlyphs = 0;
CharInfoPtr *bdfEncoding[256];
BitmapFontPtr bitmapFont;
BitmapExtraPtr bitmapExtra;
CARD32 *bitmapsSizes;
unsigned char lineBuf[BDFLINELEN];
int nencoding;
bitmapFont = (BitmapFontPtr) pFont->fontPrivate;
bitmapExtra = (BitmapExtraPtr) bitmapFont->bitmapExtra;
if (bitmapExtra) {
bitmapsSizes = bitmapExtra->bitmapsSizes;
for (i = 0; i < GLYPHPADOPTIONS; i++)
bitmapsSizes[i] = 0;
} else
bitmapsSizes = NULL;
bzero(bdfEncoding, sizeof(bdfEncoding));
bitmapFont->metrics = NULL;
ndx = 0;
line = bdfGetLine(file, lineBuf, BDFLINELEN);
if ((!line) || (sscanf((char *) line, "CHARS %d", &nchars) != 1)) {
bdfError("bad 'CHARS' in bdf file\n");
return (FALSE);
}
if (nchars < 1) {
bdfError("invalid number of CHARS in BDF file\n");
return (FALSE);
}
if (nchars > INT32_MAX / sizeof(CharInfoRec)) {
bdfError("Couldn't allocate pCI (%d*%d)\n", nchars,
(int) sizeof(CharInfoRec));
goto BAILOUT;
}
ci = calloc(nchars, sizeof(CharInfoRec));
if (!ci) {
bdfError("Couldn't allocate pCI (%d*%d)\n", nchars,
(int) sizeof(CharInfoRec));
goto BAILOUT;
}
bitmapFont->metrics = ci;
if (bitmapExtra) {
bitmapExtra->glyphNames = malloc(nchars * sizeof(Atom));
if (!bitmapExtra->glyphNames) {
bdfError("Couldn't allocate glyphNames (%d*%d)\n",
nchars, (int) sizeof(Atom));
goto BAILOUT;
}
}
if (bitmapExtra) {
bitmapExtra->sWidths = malloc(nchars * sizeof(int));
if (!bitmapExtra->sWidths) {
bdfError("Couldn't allocate sWidth (%d *%d)\n",
nchars, (int) sizeof(int));
return FALSE;
}
}
line = bdfGetLine(file, lineBuf, BDFLINELEN);
pFont->info.firstRow = 256;
pFont->info.lastRow = 0;
pFont->info.firstCol = 256;
pFont->info.lastCol = 0;
nignored = 0;
for (ndx = 0; (ndx < nchars) && (line) && (bdfIsPrefix(line, "STARTCHAR"));) {
int t;
int wx; /* x component of width */
int wy; /* y component of width */
int bw; /* bounding-box width */
int bh; /* bounding-box height */
int bl; /* bounding-box left */
int bb; /* bounding-box bottom */
int enc,
enc2; /* encoding */
unsigned char *p; /* temp pointer into line */
char charName[100];
int ignore;
if (sscanf((char *) line, "STARTCHAR %s", charName) != 1) {
bdfError("bad character name in BDF file\n");
goto BAILOUT; /* bottom of function, free and return error */
}
if (bitmapExtra)
bitmapExtra->glyphNames[ndx] = bdfForceMakeAtom(charName, NULL);
line = bdfGetLine(file, lineBuf, BDFLINELEN);
if (!line || (t = sscanf((char *) line, "ENCODING %d %d", &enc, &enc2)) < 1) {
bdfError("bad 'ENCODING' in BDF file\n");
goto BAILOUT;
}
if (enc < -1 || (t == 2 && enc2 < -1)) {
bdfError("bad ENCODING value");
goto BAILOUT;
}
if (t == 2 && enc == -1)
enc = enc2;
ignore = 0;
if (enc == -1) {
if (!bitmapExtra) {
nignored++;
ignore = 1;
}
} else if (enc > MAXENCODING) {
bdfError("char '%s' has encoding too large (%d)\n",
charName, enc);
} else {
char_row = (enc >> 8) & 0xFF;
char_col = enc & 0xFF;
if (char_row < pFont->info.firstRow)
pFont->info.firstRow = char_row;
if (char_row > pFont->info.lastRow)
pFont->info.lastRow = char_row;
if (char_col < pFont->info.firstCol)
pFont->info.firstCol = char_col;
if (char_col > pFont->info.lastCol)
pFont->info.lastCol = char_col;
if (bdfEncoding[char_row] == (CharInfoPtr *) NULL) {
bdfEncoding[char_row] = malloc(256 * sizeof(CharInfoPtr));
if (!bdfEncoding[char_row]) {
bdfError("Couldn't allocate row %d of encoding (%d*%d)\n",
char_row, INDICES, (int) sizeof(CharInfoPtr));
goto BAILOUT;
}
for (i = 0; i < 256; i++)
bdfEncoding[char_row][i] = (CharInfoPtr) NULL;
}
if (bdfEncoding[char_row] != NULL) {
bdfEncoding[char_row][char_col] = ci;
numEncodedGlyphs++;
}
}
line = bdfGetLine(file, lineBuf, BDFLINELEN);
if ((!line) || (sscanf((char *) line, "SWIDTH %d %d", &wx, &wy) != 2)) {
bdfError("bad 'SWIDTH'\n");
goto BAILOUT;
}
if (wy != 0) {
bdfError("SWIDTH y value must be zero\n");
goto BAILOUT;
}
if (bitmapExtra)
bitmapExtra->sWidths[ndx] = wx;
/* 5/31/89 (ef) -- we should be able to ditch the character and recover */
/* from all of these. */
line = bdfGetLine(file, lineBuf, BDFLINELEN);
if ((!line) || (sscanf((char *) line, "DWIDTH %d %d", &wx, &wy) != 2)) {
bdfError("bad 'DWIDTH'\n");
goto BAILOUT;
}
if (wy != 0) {
bdfError("DWIDTH y value must be zero\n");
goto BAILOUT;
}
line = bdfGetLine(file, lineBuf, BDFLINELEN);
if ((!line) || (sscanf((char *) line, "BBX %d %d %d %d", &bw, &bh, &bl, &bb) != 4)) {
bdfError("bad 'BBX'\n");
goto BAILOUT;
}
if ((bh < 0) || (bw < 0)) {
bdfError("character '%s' has a negative sized bitmap, %dx%d\n",
charName, bw, bh);
goto BAILOUT;
}
line = bdfGetLine(file, lineBuf, BDFLINELEN);
if ((line) && (bdfIsPrefix(line, "ATTRIBUTES"))) {
for (p = line + strlen("ATTRIBUTES ");
(*p == ' ') || (*p == '\t');
p++)
/* empty for loop */ ;
ci->metrics.attributes = (bdfHexByte(p) << 8) + bdfHexByte(p + 2);
line = bdfGetLine(file, lineBuf, BDFLINELEN);
} else
ci->metrics.attributes = 0;
if (!line || !bdfIsPrefix(line, "BITMAP")) {
bdfError("missing 'BITMAP'\n");
goto BAILOUT;
}
/* collect data for generated properties */
if ((strlen(charName) == 1)) {
if ((charName[0] >= '0') && (charName[0] <= '9')) {
pState->digitWidths += wx;
pState->digitCount++;
} else if (charName[0] == 'x') {
pState->exHeight = (bh + bb) <= 0 ? bh : bh + bb;
}
}
if (!ignore) {
ci->metrics.leftSideBearing = bl;
ci->metrics.rightSideBearing = bl + bw;
ci->metrics.ascent = bh + bb;
ci->metrics.descent = -bb;
ci->metrics.characterWidth = wx;
ci->bits = NULL;
bdfReadBitmap(ci, file, bit, byte, glyph, scan, bitmapsSizes);
ci++;
ndx++;
} else
bdfSkipBitmap(file, bh);
line = bdfGetLine(file, lineBuf, BDFLINELEN); /* get STARTCHAR or
* ENDFONT */
}
if (ndx + nignored != nchars) {
bdfError("%d too few characters\n", nchars - (ndx + nignored));
goto BAILOUT;
}
nchars = ndx;
bitmapFont->num_chars = nchars;
if ((line) && (bdfIsPrefix(line, "STARTCHAR"))) {
bdfError("more characters than specified\n");
goto BAILOUT;
}
if ((!line) || (!bdfIsPrefix(line, "ENDFONT"))) {
bdfError("missing 'ENDFONT'\n");
goto BAILOUT;
}
if (numEncodedGlyphs == 0)
bdfWarning("No characters with valid encodings\n");
nencoding = (pFont->info.lastRow - pFont->info.firstRow + 1) *
(pFont->info.lastCol - pFont->info.firstCol + 1);
bitmapFont->encoding = calloc(NUM_SEGMENTS(nencoding),sizeof(CharInfoPtr*));
if (!bitmapFont->encoding) {
bdfError("Couldn't allocate ppCI (%d,%d)\n",
NUM_SEGMENTS(nencoding),
(int) sizeof(CharInfoPtr*));
goto BAILOUT;
}
pFont->info.allExist = TRUE;
i = 0;
for (char_row = pFont->info.firstRow;
char_row <= pFont->info.lastRow;
char_row++) {
if (bdfEncoding[char_row] == (CharInfoPtr *) NULL) {
pFont->info.allExist = FALSE;
i += pFont->info.lastCol - pFont->info.firstCol + 1;
} else {
for (char_col = pFont->info.firstCol;
char_col <= pFont->info.lastCol;
char_col++) {
if (!bdfEncoding[char_row][char_col])
pFont->info.allExist = FALSE;
else {
if (!bitmapFont->encoding[SEGMENT_MAJOR(i)]) {
bitmapFont->encoding[SEGMENT_MAJOR(i)]=
calloc(BITMAP_FONT_SEGMENT_SIZE,
sizeof(CharInfoPtr));
if (!bitmapFont->encoding[SEGMENT_MAJOR(i)])
goto BAILOUT;
}
ACCESSENCODINGL(bitmapFont->encoding,i) =
bdfEncoding[char_row][char_col];
}
i++;
}
}
}
for (i = 0; i < 256; i++)
if (bdfEncoding[i])
free(bdfEncoding[i]);
return (TRUE);
BAILOUT:
for (i = 0; i < 256; i++)
if (bdfEncoding[i])
free(bdfEncoding[i]);
/* bdfFreeFontBits will clean up the rest */
return (FALSE);
}
Commit Message:
CWE ID: CWE-119 | bdfReadCharacters(FontFilePtr file, FontPtr pFont, bdfFileState *pState,
int bit, int byte, int glyph, int scan)
{
unsigned char *line;
register CharInfoPtr ci;
int i,
ndx,
nchars,
nignored;
unsigned int char_row, char_col;
int numEncodedGlyphs = 0;
CharInfoPtr *bdfEncoding[256];
BitmapFontPtr bitmapFont;
BitmapExtraPtr bitmapExtra;
CARD32 *bitmapsSizes;
unsigned char lineBuf[BDFLINELEN];
int nencoding;
bitmapFont = (BitmapFontPtr) pFont->fontPrivate;
bitmapExtra = (BitmapExtraPtr) bitmapFont->bitmapExtra;
if (bitmapExtra) {
bitmapsSizes = bitmapExtra->bitmapsSizes;
for (i = 0; i < GLYPHPADOPTIONS; i++)
bitmapsSizes[i] = 0;
} else
bitmapsSizes = NULL;
bzero(bdfEncoding, sizeof(bdfEncoding));
bitmapFont->metrics = NULL;
ndx = 0;
line = bdfGetLine(file, lineBuf, BDFLINELEN);
if ((!line) || (sscanf((char *) line, "CHARS %d", &nchars) != 1)) {
bdfError("bad 'CHARS' in bdf file\n");
return (FALSE);
}
if (nchars < 1) {
bdfError("invalid number of CHARS in BDF file\n");
return (FALSE);
}
if (nchars > INT32_MAX / sizeof(CharInfoRec)) {
bdfError("Couldn't allocate pCI (%d*%d)\n", nchars,
(int) sizeof(CharInfoRec));
goto BAILOUT;
}
ci = calloc(nchars, sizeof(CharInfoRec));
if (!ci) {
bdfError("Couldn't allocate pCI (%d*%d)\n", nchars,
(int) sizeof(CharInfoRec));
goto BAILOUT;
}
bitmapFont->metrics = ci;
if (bitmapExtra) {
bitmapExtra->glyphNames = malloc(nchars * sizeof(Atom));
if (!bitmapExtra->glyphNames) {
bdfError("Couldn't allocate glyphNames (%d*%d)\n",
nchars, (int) sizeof(Atom));
goto BAILOUT;
}
}
if (bitmapExtra) {
bitmapExtra->sWidths = malloc(nchars * sizeof(int));
if (!bitmapExtra->sWidths) {
bdfError("Couldn't allocate sWidth (%d *%d)\n",
nchars, (int) sizeof(int));
return FALSE;
}
}
line = bdfGetLine(file, lineBuf, BDFLINELEN);
pFont->info.firstRow = 256;
pFont->info.lastRow = 0;
pFont->info.firstCol = 256;
pFont->info.lastCol = 0;
nignored = 0;
for (ndx = 0; (ndx < nchars) && (line) && (bdfIsPrefix(line, "STARTCHAR"));) {
int t;
int wx; /* x component of width */
int wy; /* y component of width */
int bw; /* bounding-box width */
int bh; /* bounding-box height */
int bl; /* bounding-box left */
int bb; /* bounding-box bottom */
int enc,
enc2; /* encoding */
unsigned char *p; /* temp pointer into line */
char charName[100];
int ignore;
if (sscanf((char *) line, "STARTCHAR %99s", charName) != 1) {
bdfError("bad character name in BDF file\n");
goto BAILOUT; /* bottom of function, free and return error */
}
if (bitmapExtra)
bitmapExtra->glyphNames[ndx] = bdfForceMakeAtom(charName, NULL);
line = bdfGetLine(file, lineBuf, BDFLINELEN);
if (!line || (t = sscanf((char *) line, "ENCODING %d %d", &enc, &enc2)) < 1) {
bdfError("bad 'ENCODING' in BDF file\n");
goto BAILOUT;
}
if (enc < -1 || (t == 2 && enc2 < -1)) {
bdfError("bad ENCODING value");
goto BAILOUT;
}
if (t == 2 && enc == -1)
enc = enc2;
ignore = 0;
if (enc == -1) {
if (!bitmapExtra) {
nignored++;
ignore = 1;
}
} else if (enc > MAXENCODING) {
bdfError("char '%s' has encoding too large (%d)\n",
charName, enc);
} else {
char_row = (enc >> 8) & 0xFF;
char_col = enc & 0xFF;
if (char_row < pFont->info.firstRow)
pFont->info.firstRow = char_row;
if (char_row > pFont->info.lastRow)
pFont->info.lastRow = char_row;
if (char_col < pFont->info.firstCol)
pFont->info.firstCol = char_col;
if (char_col > pFont->info.lastCol)
pFont->info.lastCol = char_col;
if (bdfEncoding[char_row] == (CharInfoPtr *) NULL) {
bdfEncoding[char_row] = malloc(256 * sizeof(CharInfoPtr));
if (!bdfEncoding[char_row]) {
bdfError("Couldn't allocate row %d of encoding (%d*%d)\n",
char_row, INDICES, (int) sizeof(CharInfoPtr));
goto BAILOUT;
}
for (i = 0; i < 256; i++)
bdfEncoding[char_row][i] = (CharInfoPtr) NULL;
}
if (bdfEncoding[char_row] != NULL) {
bdfEncoding[char_row][char_col] = ci;
numEncodedGlyphs++;
}
}
line = bdfGetLine(file, lineBuf, BDFLINELEN);
if ((!line) || (sscanf((char *) line, "SWIDTH %d %d", &wx, &wy) != 2)) {
bdfError("bad 'SWIDTH'\n");
goto BAILOUT;
}
if (wy != 0) {
bdfError("SWIDTH y value must be zero\n");
goto BAILOUT;
}
if (bitmapExtra)
bitmapExtra->sWidths[ndx] = wx;
/* 5/31/89 (ef) -- we should be able to ditch the character and recover */
/* from all of these. */
line = bdfGetLine(file, lineBuf, BDFLINELEN);
if ((!line) || (sscanf((char *) line, "DWIDTH %d %d", &wx, &wy) != 2)) {
bdfError("bad 'DWIDTH'\n");
goto BAILOUT;
}
if (wy != 0) {
bdfError("DWIDTH y value must be zero\n");
goto BAILOUT;
}
line = bdfGetLine(file, lineBuf, BDFLINELEN);
if ((!line) || (sscanf((char *) line, "BBX %d %d %d %d", &bw, &bh, &bl, &bb) != 4)) {
bdfError("bad 'BBX'\n");
goto BAILOUT;
}
if ((bh < 0) || (bw < 0)) {
bdfError("character '%s' has a negative sized bitmap, %dx%d\n",
charName, bw, bh);
goto BAILOUT;
}
line = bdfGetLine(file, lineBuf, BDFLINELEN);
if ((line) && (bdfIsPrefix(line, "ATTRIBUTES"))) {
for (p = line + strlen("ATTRIBUTES ");
(*p == ' ') || (*p == '\t');
p++)
/* empty for loop */ ;
ci->metrics.attributes = (bdfHexByte(p) << 8) + bdfHexByte(p + 2);
line = bdfGetLine(file, lineBuf, BDFLINELEN);
} else
ci->metrics.attributes = 0;
if (!line || !bdfIsPrefix(line, "BITMAP")) {
bdfError("missing 'BITMAP'\n");
goto BAILOUT;
}
/* collect data for generated properties */
if ((strlen(charName) == 1)) {
if ((charName[0] >= '0') && (charName[0] <= '9')) {
pState->digitWidths += wx;
pState->digitCount++;
} else if (charName[0] == 'x') {
pState->exHeight = (bh + bb) <= 0 ? bh : bh + bb;
}
}
if (!ignore) {
ci->metrics.leftSideBearing = bl;
ci->metrics.rightSideBearing = bl + bw;
ci->metrics.ascent = bh + bb;
ci->metrics.descent = -bb;
ci->metrics.characterWidth = wx;
ci->bits = NULL;
bdfReadBitmap(ci, file, bit, byte, glyph, scan, bitmapsSizes);
ci++;
ndx++;
} else
bdfSkipBitmap(file, bh);
line = bdfGetLine(file, lineBuf, BDFLINELEN); /* get STARTCHAR or
* ENDFONT */
}
if (ndx + nignored != nchars) {
bdfError("%d too few characters\n", nchars - (ndx + nignored));
goto BAILOUT;
}
nchars = ndx;
bitmapFont->num_chars = nchars;
if ((line) && (bdfIsPrefix(line, "STARTCHAR"))) {
bdfError("more characters than specified\n");
goto BAILOUT;
}
if ((!line) || (!bdfIsPrefix(line, "ENDFONT"))) {
bdfError("missing 'ENDFONT'\n");
goto BAILOUT;
}
if (numEncodedGlyphs == 0)
bdfWarning("No characters with valid encodings\n");
nencoding = (pFont->info.lastRow - pFont->info.firstRow + 1) *
(pFont->info.lastCol - pFont->info.firstCol + 1);
bitmapFont->encoding = calloc(NUM_SEGMENTS(nencoding),sizeof(CharInfoPtr*));
if (!bitmapFont->encoding) {
bdfError("Couldn't allocate ppCI (%d,%d)\n",
NUM_SEGMENTS(nencoding),
(int) sizeof(CharInfoPtr*));
goto BAILOUT;
}
pFont->info.allExist = TRUE;
i = 0;
for (char_row = pFont->info.firstRow;
char_row <= pFont->info.lastRow;
char_row++) {
if (bdfEncoding[char_row] == (CharInfoPtr *) NULL) {
pFont->info.allExist = FALSE;
i += pFont->info.lastCol - pFont->info.firstCol + 1;
} else {
for (char_col = pFont->info.firstCol;
char_col <= pFont->info.lastCol;
char_col++) {
if (!bdfEncoding[char_row][char_col])
pFont->info.allExist = FALSE;
else {
if (!bitmapFont->encoding[SEGMENT_MAJOR(i)]) {
bitmapFont->encoding[SEGMENT_MAJOR(i)]=
calloc(BITMAP_FONT_SEGMENT_SIZE,
sizeof(CharInfoPtr));
if (!bitmapFont->encoding[SEGMENT_MAJOR(i)])
goto BAILOUT;
}
ACCESSENCODINGL(bitmapFont->encoding,i) =
bdfEncoding[char_row][char_col];
}
i++;
}
}
}
for (i = 0; i < 256; i++)
if (bdfEncoding[i])
free(bdfEncoding[i]);
return (TRUE);
BAILOUT:
for (i = 0; i < 256; i++)
if (bdfEncoding[i])
free(bdfEncoding[i]);
/* bdfFreeFontBits will clean up the rest */
return (FALSE);
}
| 165,333 |
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 locationReplaceableAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
TestNode* imp = WTF::getPtr(proxyImp->locationReplaceable());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHref(cppValue);
}
Commit Message: document.location bindings fix
BUG=352374
[email protected]
Review URL: https://codereview.chromium.org/196343011
git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | static void locationReplaceableAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationReplaceable());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHref(cppValue);
}
| 171,686 |
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 jsTestCustomNamedGetterPrototypeFunctionAnotherFunction(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestCustomNamedGetter::s_info))
return throwVMTypeError(exec);
JSTestCustomNamedGetter* castedThis = jsCast<JSTestCustomNamedGetter*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestCustomNamedGetter::s_info);
TestCustomNamedGetter* impl = static_cast<TestCustomNamedGetter*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
const String& str(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->anotherFunction(str);
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 jsTestCustomNamedGetterPrototypeFunctionAnotherFunction(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestCustomNamedGetter::s_info))
return throwVMTypeError(exec);
JSTestCustomNamedGetter* castedThis = jsCast<JSTestCustomNamedGetter*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestCustomNamedGetter::s_info);
TestCustomNamedGetter* impl = static_cast<TestCustomNamedGetter*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
const String& str(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->anotherFunction(str);
return JSValue::encode(jsUndefined());
}
| 170,569 |
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 jsTestObjPrototypeFunctionConvert2(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() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
b* (tob(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->convert2();
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 jsTestObjPrototypeFunctionConvert2(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() < 1)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
b* (tob(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->convert2();
return JSValue::encode(jsUndefined());
}
| 170,584 |
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_sig_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG)));
return NULL;
}
| 167,793 |
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 RunTestsInFile(const std::string& filename,
const std::string& pdf_filename) {
extensions::ResultCatcher catcher;
GURL url(embedded_test_server()->GetURL("/pdf/" + pdf_filename));
ASSERT_TRUE(LoadPdf(url));
content::WebContents* contents =
browser()->tab_strip_model()->GetActiveWebContents();
content::BrowserPluginGuestManager* guest_manager =
contents->GetBrowserContext()->GetGuestManager();
content::WebContents* guest_contents =
guest_manager->GetFullPageGuest(contents);
ASSERT_TRUE(guest_contents);
base::FilePath test_data_dir;
PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir);
test_data_dir = test_data_dir.Append(FILE_PATH_LITERAL("pdf"));
base::FilePath test_util_path = test_data_dir.AppendASCII("test_util.js");
std::string test_util_js;
ASSERT_TRUE(base::ReadFileToString(test_util_path, &test_util_js));
base::FilePath test_file_path = test_data_dir.AppendASCII(filename);
std::string test_js;
ASSERT_TRUE(base::ReadFileToString(test_file_path, &test_js));
test_util_js.append(test_js);
ASSERT_TRUE(content::ExecuteScript(guest_contents, test_util_js));
if (!catcher.GetNextResult())
FAIL() << catcher.message();
}
Commit Message: This patch implements a mechanism for more granular link URL permissions (filtering on scheme/host). This fixes the bug that allowed PDFs to have working links to any "chrome://" URLs.
BUG=528505,226927
Review URL: https://codereview.chromium.org/1362433002
Cr-Commit-Position: refs/heads/master@{#351705}
CWE ID: CWE-264 | void RunTestsInFile(const std::string& filename,
const std::string& pdf_filename) {
extensions::ResultCatcher catcher;
GURL url(embedded_test_server()->GetURL("/pdf/" + pdf_filename));
content::WebContents* guest_contents = LoadPdfGetGuestContents(url);
ASSERT_TRUE(guest_contents);
base::FilePath test_data_dir;
PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir);
test_data_dir = test_data_dir.Append(FILE_PATH_LITERAL("pdf"));
base::FilePath test_util_path = test_data_dir.AppendASCII("test_util.js");
std::string test_util_js;
ASSERT_TRUE(base::ReadFileToString(test_util_path, &test_util_js));
base::FilePath test_file_path = test_data_dir.AppendASCII(filename);
std::string test_js;
ASSERT_TRUE(base::ReadFileToString(test_file_path, &test_js));
test_util_js.append(test_js);
ASSERT_TRUE(content::ExecuteScript(guest_contents, test_util_js));
if (!catcher.GetNextResult())
FAIL() << catcher.message();
}
| 171,774 |
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: irc_ctcp_dcc_filename_without_quotes (const char *filename)
{
int length;
length = strlen (filename);
if (length > 0)
{
if ((filename[0] == '\"') && (filename[length - 1] == '\"'))
return weechat_strndup (filename + 1, length - 2);
}
return strdup (filename);
}
Commit Message: irc: fix parsing of DCC filename
CWE ID: CWE-119 | irc_ctcp_dcc_filename_without_quotes (const char *filename)
{
int length;
length = strlen (filename);
if (length > 1)
{
if ((filename[0] == '\"') && (filename[length - 1] == '\"'))
return weechat_strndup (filename + 1, length - 2);
}
return strdup (filename);
}
| 168,206 |
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 FrameImpl::GoBack() {
NOTIMPLEMENTED();
}
Commit Message: [fuchsia] Implement browser tests for WebRunner Context service.
Tests may interact with the WebRunner FIDL services and the underlying
browser objects for end to end testing of service and browser
functionality.
* Add a browser test launcher main() for WebRunner.
* Add some simple navigation tests.
* Wire up GoBack()/GoForward() FIDL calls.
* Add embedded test server resources and initialization logic.
* Add missing deletion & notification calls to BrowserContext dtor.
* Use FIDL events for navigation state changes.
* Bug fixes:
** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(),
so that they may use the MessageLoop during teardown.
** Fix Frame dtor to allow for null WindowTreeHosts (headless case)
** Fix std::move logic in Frame ctor which lead to no WebContents
observer being registered.
Bug: 871594
Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac
Reviewed-on: https://chromium-review.googlesource.com/1164539
Commit-Queue: Kevin Marshall <[email protected]>
Reviewed-by: Wez <[email protected]>
Reviewed-by: Fabrice de Gans-Riberi <[email protected]>
Reviewed-by: Scott Violet <[email protected]>
Cr-Commit-Position: refs/heads/master@{#584155}
CWE ID: CWE-264 | void FrameImpl::GoBack() {
if (web_contents_->GetController().CanGoBack())
web_contents_->GetController().GoBack();
}
| 172,153 |
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 devmem_is_allowed(unsigned long pagenr)
{
if (pagenr < 256)
return 1;
if (iomem_is_exclusive(pagenr << PAGE_SHIFT))
return 0;
if (!page_is_ram(pagenr))
return 1;
return 0;
}
Commit Message: mm: Tighten x86 /dev/mem with zeroing reads
Under CONFIG_STRICT_DEVMEM, reading System RAM through /dev/mem is
disallowed. However, on x86, the first 1MB was always allowed for BIOS
and similar things, regardless of it actually being System RAM. It was
possible for heap to end up getting allocated in low 1MB RAM, and then
read by things like x86info or dd, which would trip hardened usercopy:
usercopy: kernel memory exposure attempt detected from ffff880000090000 (dma-kmalloc-256) (4096 bytes)
This changes the x86 exception for the low 1MB by reading back zeros for
System RAM areas instead of blindly allowing them. More work is needed to
extend this to mmap, but currently mmap doesn't go through usercopy, so
hardened usercopy won't Oops the kernel.
Reported-by: Tommi Rantala <[email protected]>
Tested-by: Tommi Rantala <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
CWE ID: CWE-732 | int devmem_is_allowed(unsigned long pagenr)
{
if (page_is_ram(pagenr)) {
/*
* For disallowed memory regions in the low 1MB range,
* request that the page be shown as all zeros.
*/
if (pagenr < 256)
return 2;
return 0;
}
/*
* This must follow RAM test, since System RAM is considered a
* restricted resource under CONFIG_STRICT_IOMEM.
*/
if (iomem_is_exclusive(pagenr << PAGE_SHIFT)) {
/* Low 1MB bypasses iomem restrictions. */
if (pagenr < 256)
return 1;
return 0;
}
return 1;
}
| 168,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: raptor_rss_parse_start(raptor_parser *rdf_parser)
{
raptor_uri *uri = rdf_parser->base_uri;
raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context;
int n;
/* base URI required for RSS */
if(!uri)
return 1;
for(n = 0; n < RAPTOR_RSS_NAMESPACES_SIZE; n++)
rss_parser->nspaces_seen[n] = 'N';
/* Optionally forbid internal network and file requests in the XML parser */
raptor_sax2_set_option(rss_parser->sax2,
RAPTOR_OPTION_NO_NET, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET));
raptor_sax2_set_option(rss_parser->sax2,
RAPTOR_OPTION_NO_FILE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE));
if(rdf_parser->uri_filter)
raptor_sax2_set_uri_filter(rss_parser->sax2, rdf_parser->uri_filter,
rdf_parser->uri_filter_user_data);
raptor_sax2_parse_start(rss_parser->sax2, uri);
return 0;
}
Commit Message: CVE-2012-0037
Enforce entity loading policy in raptor_libxml_resolveEntity
and raptor_libxml_getEntity by checking for file URIs and network URIs.
Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for
turning on loading of XML external entity loading, disabled by default.
This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and
aliases) and rdfa.
CWE ID: CWE-200 | raptor_rss_parse_start(raptor_parser *rdf_parser)
{
raptor_uri *uri = rdf_parser->base_uri;
raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context;
int n;
/* base URI required for RSS */
if(!uri)
return 1;
for(n = 0; n < RAPTOR_RSS_NAMESPACES_SIZE; n++)
rss_parser->nspaces_seen[n] = 'N';
/* Optionally forbid internal network and file requests in the XML parser */
raptor_sax2_set_option(rss_parser->sax2,
RAPTOR_OPTION_NO_NET, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET));
raptor_sax2_set_option(rss_parser->sax2,
RAPTOR_OPTION_NO_FILE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE));
raptor_sax2_set_option(rss_parser->sax2,
RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES));
if(rdf_parser->uri_filter)
raptor_sax2_set_uri_filter(rss_parser->sax2, rdf_parser->uri_filter,
rdf_parser->uri_filter_user_data);
raptor_sax2_parse_start(rss_parser->sax2, uri);
return 0;
}
| 165,661 |
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 PluginModule::InitAsProxiedNaCl(
scoped_ptr<PluginDelegate::OutOfProcessProxy> out_of_process_proxy,
PP_Instance instance) {
nacl_ipc_proxy_ = true;
InitAsProxied(out_of_process_proxy.release());
out_of_process_proxy_->AddInstance(instance);
PluginInstance* plugin_instance = host_globals->GetInstance(instance);
if (!plugin_instance)
return;
plugin_instance->ResetAsProxied();
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void PluginModule::InitAsProxiedNaCl(
PluginDelegate::OutOfProcessProxy* out_of_process_proxy,
PP_Instance instance) {
InitAsProxied(out_of_process_proxy);
out_of_process_proxy_->AddInstance(instance);
PluginInstance* plugin_instance = host_globals->GetInstance(instance);
if (!plugin_instance)
return;
plugin_instance->ResetAsProxied();
}
| 170,745 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
int blk_size = buff_size, order;
gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
struct sg_device *sdp = sfp->parentdp;
if (blk_size < 0)
return -EFAULT;
if (0 == blk_size)
++blk_size; /* don't know why */
/* round request up to next highest SG_SECTOR_SZ byte boundary */
blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: buff_size=%d, blk_size=%d\n",
buff_size, blk_size));
/* N.B. ret_sz carried into this block ... */
mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
if (sdp->device->host->unchecked_isa_dma)
gfp_mask |= GFP_DMA;
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
gfp_mask |= __GFP_ZERO;
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
num = (rem_sz > scatter_elem_sz_prev) ?
scatter_elem_sz_prev : rem_sz;
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
scatter_elem_sz = ret_sz;
scatter_elem_sz_prev = ret_sz;
}
}
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
} /* end of for loop */
schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
k, rem_sz));
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
return 0;
out:
for (i = 0; i < k; i++)
__free_pages(schp->pages[i], order);
if (--order >= 0)
goto retry;
return -ENOMEM;
}
Commit Message: scsi: sg: allocate with __GFP_ZERO in sg_build_indirect()
This shall help avoid copying uninitialized memory to the userspace when
calling ioctl(fd, SG_IO) with an empty command.
Reported-by: [email protected]
Cc: [email protected]
Signed-off-by: Alexander Potapenko <[email protected]>
Acked-by: Douglas Gilbert <[email protected]>
Reviewed-by: Johannes Thumshirn <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID: | sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
int blk_size = buff_size, order;
gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
struct sg_device *sdp = sfp->parentdp;
if (blk_size < 0)
return -EFAULT;
if (0 == blk_size)
++blk_size; /* don't know why */
/* round request up to next highest SG_SECTOR_SZ byte boundary */
blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: buff_size=%d, blk_size=%d\n",
buff_size, blk_size));
/* N.B. ret_sz carried into this block ... */
mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
if (sdp->device->host->unchecked_isa_dma)
gfp_mask |= GFP_DMA;
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
gfp_mask |= __GFP_ZERO;
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
num = (rem_sz > scatter_elem_sz_prev) ?
scatter_elem_sz_prev : rem_sz;
schp->pages[k] = alloc_pages(gfp_mask | __GFP_ZERO, order);
if (!schp->pages[k])
goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
scatter_elem_sz = ret_sz;
scatter_elem_sz_prev = ret_sz;
}
}
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
} /* end of for loop */
schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
k, rem_sz));
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
return 0;
out:
for (i = 0; i < k; i++)
__free_pages(schp->pages[i], order);
if (--order >= 0)
goto retry;
return -ENOMEM;
}
| 168,942 |
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: swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint16* wp = (uint16*) cp0;
tmsize_t wc = cc / 2;
horDiff16(tif, cp0, cc);
TIFFSwabArrayOfShort(wp, wc);
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119 | swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint16* wp = (uint16*) cp0;
tmsize_t wc = cc / 2;
if( !horDiff16(tif, cp0, cc) )
return 0;
TIFFSwabArrayOfShort(wp, wc);
return 1;
}
| 166,890 |
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 MediaStreamDispatcherHost::StopStreamDevice(const std::string& device_id,
int32_t session_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
media_stream_manager_->StopStreamDevice(render_process_id_, render_frame_id_,
device_id, session_id);
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189 | void MediaStreamDispatcherHost::StopStreamDevice(const std::string& device_id,
int32_t session_id) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
media_stream_manager_->StopStreamDevice(render_process_id_, render_frame_id_,
requester_id_, device_id, session_id);
}
| 173,097 |
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_entry_size_and_hooks(struct ip6t_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct ip6t_entry) >= limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size
Otherwise this function may read data beyond the ruleset blob.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119 | check_entry_size_and_hooks(struct ip6t_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct ip6t_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
| 167,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: gss_complete_auth_token (OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
gss_buffer_t input_message_buffer)
{
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
if (context_handle == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (mech != NULL) {
if (mech->gss_complete_auth_token != NULL) {
status = mech->gss_complete_auth_token(minor_status,
ctx->internal_ctx_id,
input_message_buffer);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else
status = GSS_S_COMPLETE;
} else
status = GSS_S_BAD_MECH;
return status;
}
Commit Message: Preserve GSS context on init/accept failure
After gss_init_sec_context() or gss_accept_sec_context() has created a
context, don't delete the mechglue context on failures from subsequent
calls, even if the mechanism deletes the mech-specific context (which
is allowed by RFC 2744 but not preferred). Check for union contexts
with no mechanism context in each GSS function which accepts a
gss_ctx_id_t.
CVE-2017-11462:
RFC 2744 permits a GSS-API implementation to delete an existing
security context on a second or subsequent call to
gss_init_sec_context() or gss_accept_sec_context() if the call results
in an error. This API behavior has been found to be dangerous,
leading to the possibility of memory errors in some callers. For
safety, GSS-API implementations should instead preserve existing
security contexts on error until the caller deletes them.
All versions of MIT krb5 prior to this change may delete acceptor
contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through
1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on
error.
ticket: 8598 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-415 | gss_complete_auth_token (OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
gss_buffer_t input_message_buffer)
{
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
if (context_handle == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
mech = gssint_get_mechanism (ctx->mech_type);
if (mech != NULL) {
if (mech->gss_complete_auth_token != NULL) {
status = mech->gss_complete_auth_token(minor_status,
ctx->internal_ctx_id,
input_message_buffer);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else
status = GSS_S_COMPLETE;
} else
status = GSS_S_BAD_MECH;
return status;
}
| 168,012 |
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: pidfile_write(const char *pid_file, int pid)
{
FILE *pidfile = NULL;
int pidfd = creat(pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (pidfd != -1) pidfile = fdopen(pidfd, "w");
if (!pidfile) {
log_message(LOG_INFO, "pidfile_write : Cannot open %s pidfile",
pid_file);
return 0;
}
fprintf(pidfile, "%d\n", pid);
fclose(pidfile);
return 1;
}
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-59 | pidfile_write(const char *pid_file, int pid)
{
FILE *pidfile = NULL;
int pidfd = open(pid_file, O_NOFOLLOW | O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (pidfd != -1) pidfile = fdopen(pidfd, "w");
if (!pidfile) {
log_message(LOG_INFO, "pidfile_write : Cannot open %s pidfile",
pid_file);
return 0;
}
fprintf(pidfile, "%d\n", pid);
fclose(pidfile);
return 1;
}
| 168,986 |
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 MemBackendImpl::DoomEntriesBetween(Time initial_time,
Time end_time,
const CompletionCallback& callback) {
if (end_time.is_null())
end_time = Time::Max();
DCHECK_GE(end_time, initial_time);
base::LinkNode<MemEntryImpl>* node = lru_list_.head();
while (node != lru_list_.end() && node->value()->GetLastUsed() < initial_time)
node = node->next();
while (node != lru_list_.end() && node->value()->GetLastUsed() < end_time) {
MemEntryImpl* to_doom = node->value();
node = node->next();
to_doom->Doom();
}
return net::OK;
}
Commit Message: [MemCache] Fix bug while iterating LRU list in range doom
This is exact same thing as https://chromium-review.googlesource.com/c/chromium/src/+/987919
but on explicit mass-erase rather than eviction.
Thanks to nedwilliamson@ (on gmail) for the report and testcase.
Bug: 831963
Change-Id: I96a46700c1f058f7feebe038bcf983dc40eb7102
Reviewed-on: https://chromium-review.googlesource.com/1014023
Commit-Queue: Maks Orlovich <[email protected]>
Reviewed-by: Josh Karlin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#551205}
CWE ID: CWE-416 | int MemBackendImpl::DoomEntriesBetween(Time initial_time,
Time end_time,
const CompletionCallback& callback) {
if (end_time.is_null())
end_time = Time::Max();
DCHECK_GE(end_time, initial_time);
base::LinkNode<MemEntryImpl>* node = lru_list_.head();
while (node != lru_list_.end() && node->value()->GetLastUsed() < initial_time)
node = node->next();
while (node != lru_list_.end() && node->value()->GetLastUsed() < end_time) {
MemEntryImpl* to_doom = node->value();
node = NextSkippingChildren(lru_list_, node);
to_doom->Doom();
}
return net::OK;
}
| 173,257 |
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 ssl_set_client_disabled(SSL *s)
{
CERT *c = s->cert;
c->mask_a = 0;
c->mask_k = 0;
/* Don't allow TLS 1.2 only ciphers if we don't suppport them */
if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s))
c->mask_ssl = SSL_TLSV1_2;
else
c->mask_ssl = 0;
ssl_set_sig_mask(&c->mask_a, s, SSL_SECOP_SIGALG_MASK);
/* Disable static DH if we don't include any appropriate
* signature algorithms.
*/
if (c->mask_a & SSL_aRSA)
c->mask_k |= SSL_kDHr|SSL_kECDHr;
if (c->mask_a & SSL_aDSS)
c->mask_k |= SSL_kDHd;
if (c->mask_a & SSL_aECDSA)
c->mask_k |= SSL_kECDHe;
#ifndef OPENSSL_NO_KRB5
if (!kssl_tgt_is_available(s->kssl_ctx))
{
c->mask_a |= SSL_aKRB5;
c->mask_k |= SSL_kKRB5;
}
#endif
#ifndef OPENSSL_NO_PSK
/* with PSK there must be client callback set */
if (!s->psk_client_callback)
{
c->mask_a |= SSL_aPSK;
c->mask_k |= SSL_kPSK;
}
#endif /* OPENSSL_NO_PSK */
c->valid = 1;
}
Commit Message:
CWE ID: | void ssl_set_client_disabled(SSL *s)
{
CERT *c = s->cert;
c->mask_a = 0;
c->mask_k = 0;
/* Don't allow TLS 1.2 only ciphers if we don't suppport them */
if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s))
c->mask_ssl = SSL_TLSV1_2;
else
c->mask_ssl = 0;
ssl_set_sig_mask(&c->mask_a, s, SSL_SECOP_SIGALG_MASK);
/* Disable static DH if we don't include any appropriate
* signature algorithms.
*/
if (c->mask_a & SSL_aRSA)
c->mask_k |= SSL_kDHr|SSL_kECDHr;
if (c->mask_a & SSL_aDSS)
c->mask_k |= SSL_kDHd;
if (c->mask_a & SSL_aECDSA)
c->mask_k |= SSL_kECDHe;
#ifndef OPENSSL_NO_KRB5
if (!kssl_tgt_is_available(s->kssl_ctx))
{
c->mask_a |= SSL_aKRB5;
c->mask_k |= SSL_kKRB5;
}
#endif
#ifndef OPENSSL_NO_PSK
/* with PSK there must be client callback set */
if (!s->psk_client_callback)
{
c->mask_a |= SSL_aPSK;
c->mask_k |= SSL_kPSK;
}
#endif /* OPENSSL_NO_PSK */
#ifndef OPENSSL_NO_SRP
if (!(s->srp_ctx.srp_Mask & SSL_kSRP))
{
c->mask_a |= SSL_aSRP;
c->mask_k |= SSL_kSRP;
}
#endif
c->valid = 1;
}
| 165,023 |
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 SoftMPEG4::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while (!inQueue.empty() && outQueue.size() == kNumOutputBuffers) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
if (inHeader == NULL) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
continue;
}
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader =
port->mBuffers.editItemAt(mNumSamplesOutput & 1).mHeader;
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
++mInputBufferCount;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
return;
}
uint8_t *bitstream = inHeader->pBuffer + inHeader->nOffset;
uint32_t *start_code = (uint32_t *)bitstream;
bool volHeader = *start_code == 0xB0010000;
if (volHeader) {
PVCleanUpVideoDecoder(mHandle);
mInitialized = false;
}
if (!mInitialized) {
uint8_t *vol_data[1];
int32_t vol_size = 0;
vol_data[0] = NULL;
if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) || volHeader) {
vol_data[0] = bitstream;
vol_size = inHeader->nFilledLen;
}
MP4DecodingMode mode =
(mMode == MODE_MPEG4) ? MPEG4_MODE : H263_MODE;
Bool success = PVInitVideoDecoder(
mHandle, vol_data, &vol_size, 1,
outputBufferWidth(), outputBufferHeight(), mode);
if (!success) {
ALOGW("PVInitVideoDecoder failed. Unsupported content?");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle);
if (mode != actualMode) {
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
PVSetPostProcType((VideoDecControls *) mHandle, 0);
bool hasFrameData = false;
if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
} else if (volHeader) {
hasFrameData = true;
}
mInitialized = true;
if (mode == MPEG4_MODE && handlePortSettingsChange()) {
return;
}
if (!hasFrameData) {
continue;
}
}
if (!mFramesConfigured) {
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(1).mHeader;
PVSetReferenceYUV(mHandle, outHeader->pBuffer);
mFramesConfigured = true;
}
uint32_t useExtTimestamp = (inHeader->nOffset == 0);
uint32_t timestamp = 0xFFFFFFFF;
if (useExtTimestamp) {
mPvToOmxTimeMap.add(mPvTime, inHeader->nTimeStamp);
timestamp = mPvTime;
mPvTime++;
}
int32_t bufferSize = inHeader->nFilledLen;
int32_t tmp = bufferSize;
OMX_U32 frameSize = (mWidth * mHeight * 3) / 2;
if (outHeader->nAllocLen < frameSize) {
android_errorWriteLog(0x534e4554, "27833616");
ALOGE("Insufficient output buffer size");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
if (PVDecodeVideoFrame(
mHandle, &bitstream, ×tamp, &tmp,
&useExtTimestamp,
outHeader->pBuffer) != PV_TRUE) {
ALOGE("failed to decode video frame.");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
if (handlePortSettingsChange()) {
return;
}
outHeader->nTimeStamp = mPvToOmxTimeMap.valueFor(timestamp);
mPvToOmxTimeMap.removeItem(timestamp);
inHeader->nOffset += bufferSize;
inHeader->nFilledLen = 0;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
} else {
outHeader->nFlags = 0;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
++mInputBufferCount;
outHeader->nOffset = 0;
outHeader->nFilledLen = frameSize;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
++mNumSamplesOutput;
}
}
Commit Message: SoftMPEG4: Check the buffer size before writing the reference frame.
Also prevent overflow in SoftMPEG4 and division by zero in SoftMPEG4Encoder.
Bug: 30033990
Change-Id: I7701f5fc54c2670587d122330e5dc851f64ed3c2
(cherry picked from commit 695123195034402ca76169b195069c28c30342d3)
CWE ID: CWE-264 | void SoftMPEG4::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while (!inQueue.empty() && outQueue.size() == kNumOutputBuffers) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
if (inHeader == NULL) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
continue;
}
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader =
port->mBuffers.editItemAt(mNumSamplesOutput & 1).mHeader;
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
++mInputBufferCount;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
return;
}
uint8_t *bitstream = inHeader->pBuffer + inHeader->nOffset;
uint32_t *start_code = (uint32_t *)bitstream;
bool volHeader = *start_code == 0xB0010000;
if (volHeader) {
PVCleanUpVideoDecoder(mHandle);
mInitialized = false;
}
if (!mInitialized) {
uint8_t *vol_data[1];
int32_t vol_size = 0;
vol_data[0] = NULL;
if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) || volHeader) {
vol_data[0] = bitstream;
vol_size = inHeader->nFilledLen;
}
MP4DecodingMode mode =
(mMode == MODE_MPEG4) ? MPEG4_MODE : H263_MODE;
Bool success = PVInitVideoDecoder(
mHandle, vol_data, &vol_size, 1,
outputBufferWidth(), outputBufferHeight(), mode);
if (!success) {
ALOGW("PVInitVideoDecoder failed. Unsupported content?");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle);
if (mode != actualMode) {
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
PVSetPostProcType((VideoDecControls *) mHandle, 0);
bool hasFrameData = false;
if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
} else if (volHeader) {
hasFrameData = true;
}
mInitialized = true;
if (mode == MPEG4_MODE && handlePortSettingsChange()) {
return;
}
if (!hasFrameData) {
continue;
}
}
if (!mFramesConfigured) {
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(1).mHeader;
OMX_U32 yFrameSize = sizeof(uint8) * mHandle->size;
if ((outHeader->nAllocLen < yFrameSize) ||
(outHeader->nAllocLen - yFrameSize < yFrameSize / 2)) {
ALOGE("Too small output buffer for reference frame: %zu bytes",
outHeader->nAllocLen);
android_errorWriteLog(0x534e4554, "30033990");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
PVSetReferenceYUV(mHandle, outHeader->pBuffer);
mFramesConfigured = true;
}
uint32_t useExtTimestamp = (inHeader->nOffset == 0);
uint32_t timestamp = 0xFFFFFFFF;
if (useExtTimestamp) {
mPvToOmxTimeMap.add(mPvTime, inHeader->nTimeStamp);
timestamp = mPvTime;
mPvTime++;
}
int32_t bufferSize = inHeader->nFilledLen;
int32_t tmp = bufferSize;
OMX_U32 frameSize;
OMX_U64 yFrameSize = (OMX_U64)mWidth * (OMX_U64)mHeight;
if (yFrameSize > ((OMX_U64)UINT32_MAX / 3) * 2) {
ALOGE("Frame size too large");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
frameSize = (OMX_U32)(yFrameSize + (yFrameSize / 2));
if (outHeader->nAllocLen < frameSize) {
android_errorWriteLog(0x534e4554, "27833616");
ALOGE("Insufficient output buffer size");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
if (PVDecodeVideoFrame(
mHandle, &bitstream, ×tamp, &tmp,
&useExtTimestamp,
outHeader->pBuffer) != PV_TRUE) {
ALOGE("failed to decode video frame.");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
if (handlePortSettingsChange()) {
return;
}
outHeader->nTimeStamp = mPvToOmxTimeMap.valueFor(timestamp);
mPvToOmxTimeMap.removeItem(timestamp);
inHeader->nOffset += bufferSize;
inHeader->nFilledLen = 0;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
} else {
outHeader->nFlags = 0;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
++mInputBufferCount;
outHeader->nOffset = 0;
outHeader->nFilledLen = frameSize;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
++mNumSamplesOutput;
}
}
| 173,401 |
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 __init trap_init(void)
{
int i;
#ifdef CONFIG_EISA
void __iomem *p = early_ioremap(0x0FFFD9, 4);
if (readl(p) == 'E' + ('I'<<8) + ('S'<<16) + ('A'<<24))
EISA_bus = 1;
early_iounmap(p, 4);
#endif
set_intr_gate(X86_TRAP_DE, divide_error);
set_intr_gate_ist(X86_TRAP_NMI, &nmi, NMI_STACK);
/* int4 can be called from all */
set_system_intr_gate(X86_TRAP_OF, &overflow);
set_intr_gate(X86_TRAP_BR, bounds);
set_intr_gate(X86_TRAP_UD, invalid_op);
set_intr_gate(X86_TRAP_NM, device_not_available);
#ifdef CONFIG_X86_32
set_task_gate(X86_TRAP_DF, GDT_ENTRY_DOUBLEFAULT_TSS);
#else
set_intr_gate_ist(X86_TRAP_DF, &double_fault, DOUBLEFAULT_STACK);
#endif
set_intr_gate(X86_TRAP_OLD_MF, coprocessor_segment_overrun);
set_intr_gate(X86_TRAP_TS, invalid_TSS);
set_intr_gate(X86_TRAP_NP, segment_not_present);
set_intr_gate_ist(X86_TRAP_SS, &stack_segment, STACKFAULT_STACK);
set_intr_gate(X86_TRAP_GP, general_protection);
set_intr_gate(X86_TRAP_SPURIOUS, spurious_interrupt_bug);
set_intr_gate(X86_TRAP_MF, coprocessor_error);
set_intr_gate(X86_TRAP_AC, alignment_check);
#ifdef CONFIG_X86_MCE
set_intr_gate_ist(X86_TRAP_MC, &machine_check, MCE_STACK);
#endif
set_intr_gate(X86_TRAP_XF, simd_coprocessor_error);
/* Reserve all the builtin and the syscall vector: */
for (i = 0; i < FIRST_EXTERNAL_VECTOR; i++)
set_bit(i, used_vectors);
#ifdef CONFIG_IA32_EMULATION
set_system_intr_gate(IA32_SYSCALL_VECTOR, ia32_syscall);
set_bit(IA32_SYSCALL_VECTOR, used_vectors);
#endif
#ifdef CONFIG_X86_32
set_system_trap_gate(SYSCALL_VECTOR, &system_call);
set_bit(SYSCALL_VECTOR, used_vectors);
#endif
/*
* Set the IDT descriptor to a fixed read-only location, so that the
* "sidt" instruction will not leak the location of the kernel, and
* to defend the IDT against arbitrary memory write vulnerabilities.
* It will be reloaded in cpu_init() */
__set_fixmap(FIX_RO_IDT, __pa_symbol(idt_table), PAGE_KERNEL_RO);
idt_descr.address = fix_to_virt(FIX_RO_IDT);
/*
* Should be a barrier for any external CPU state:
*/
cpu_init();
x86_init.irqs.trap_init();
#ifdef CONFIG_X86_64
memcpy(&debug_idt_table, &idt_table, IDT_ENTRIES * 16);
set_nmi_gate(X86_TRAP_DB, &debug);
set_nmi_gate(X86_TRAP_BP, &int3);
#endif
}
Commit Message: x86_64, traps: Stop using IST for #SS
On a 32-bit kernel, this has no effect, since there are no IST stacks.
On a 64-bit kernel, #SS can only happen in user code, on a failed iret
to user space, a canonical violation on access via RSP or RBP, or a
genuine stack segment violation in 32-bit kernel code. The first two
cases don't need IST, and the latter two cases are unlikely fatal bugs,
and promoting them to double faults would be fine.
This fixes a bug in which the espfix64 code mishandles a stack segment
violation.
This saves 4k of memory per CPU and a tiny bit of code.
Signed-off-by: Andy Lutomirski <[email protected]>
Reviewed-by: Thomas Gleixner <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | void __init trap_init(void)
{
int i;
#ifdef CONFIG_EISA
void __iomem *p = early_ioremap(0x0FFFD9, 4);
if (readl(p) == 'E' + ('I'<<8) + ('S'<<16) + ('A'<<24))
EISA_bus = 1;
early_iounmap(p, 4);
#endif
set_intr_gate(X86_TRAP_DE, divide_error);
set_intr_gate_ist(X86_TRAP_NMI, &nmi, NMI_STACK);
/* int4 can be called from all */
set_system_intr_gate(X86_TRAP_OF, &overflow);
set_intr_gate(X86_TRAP_BR, bounds);
set_intr_gate(X86_TRAP_UD, invalid_op);
set_intr_gate(X86_TRAP_NM, device_not_available);
#ifdef CONFIG_X86_32
set_task_gate(X86_TRAP_DF, GDT_ENTRY_DOUBLEFAULT_TSS);
#else
set_intr_gate_ist(X86_TRAP_DF, &double_fault, DOUBLEFAULT_STACK);
#endif
set_intr_gate(X86_TRAP_OLD_MF, coprocessor_segment_overrun);
set_intr_gate(X86_TRAP_TS, invalid_TSS);
set_intr_gate(X86_TRAP_NP, segment_not_present);
set_intr_gate(X86_TRAP_SS, stack_segment);
set_intr_gate(X86_TRAP_GP, general_protection);
set_intr_gate(X86_TRAP_SPURIOUS, spurious_interrupt_bug);
set_intr_gate(X86_TRAP_MF, coprocessor_error);
set_intr_gate(X86_TRAP_AC, alignment_check);
#ifdef CONFIG_X86_MCE
set_intr_gate_ist(X86_TRAP_MC, &machine_check, MCE_STACK);
#endif
set_intr_gate(X86_TRAP_XF, simd_coprocessor_error);
/* Reserve all the builtin and the syscall vector: */
for (i = 0; i < FIRST_EXTERNAL_VECTOR; i++)
set_bit(i, used_vectors);
#ifdef CONFIG_IA32_EMULATION
set_system_intr_gate(IA32_SYSCALL_VECTOR, ia32_syscall);
set_bit(IA32_SYSCALL_VECTOR, used_vectors);
#endif
#ifdef CONFIG_X86_32
set_system_trap_gate(SYSCALL_VECTOR, &system_call);
set_bit(SYSCALL_VECTOR, used_vectors);
#endif
/*
* Set the IDT descriptor to a fixed read-only location, so that the
* "sidt" instruction will not leak the location of the kernel, and
* to defend the IDT against arbitrary memory write vulnerabilities.
* It will be reloaded in cpu_init() */
__set_fixmap(FIX_RO_IDT, __pa_symbol(idt_table), PAGE_KERNEL_RO);
idt_descr.address = fix_to_virt(FIX_RO_IDT);
/*
* Should be a barrier for any external CPU state:
*/
cpu_init();
x86_init.irqs.trap_init();
#ifdef CONFIG_X86_64
memcpy(&debug_idt_table, &idt_table, IDT_ENTRIES * 16);
set_nmi_gate(X86_TRAP_DB, &debug);
set_nmi_gate(X86_TRAP_BP, &int3);
#endif
}
| 166,239 |
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: BufferMeta(const sp<IMemory> &mem, bool is_backup = false)
: mMem(mem),
mIsBackup(is_backup) {
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119 | BufferMeta(const sp<IMemory> &mem, bool is_backup = false)
BufferMeta(const sp<IMemory> &mem, OMX_U32 portIndex, bool is_backup = false)
: mMem(mem),
mIsBackup(is_backup),
mPortIndex(portIndex) {
}
| 173,521 |
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: content::DownloadFile* MockDownloadFileFactory::CreateFile(
DownloadCreateInfo* info,
scoped_ptr<content::ByteStreamReader> stream,
content::DownloadManager* download_manager,
bool calculate_hash,
const net::BoundNetLog& bound_net_log) {
DCHECK(files_.end() == files_.find(info->download_id));
MockDownloadFile* created_file = new MockDownloadFile();
files_[info->download_id] = created_file;
ON_CALL(*created_file, GetDownloadManager())
.WillByDefault(Return(download_manager));
EXPECT_CALL(*created_file, Initialize());
return created_file;
}
Commit Message: Refactors to simplify rename pathway in DownloadFileManager.
This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted
due to CrOS failure) with the completion logic moved to after the
auto-opening. The tests that test the auto-opening (for web store install)
were waiting for download completion to check install, and hence were
failing when completion was moved earlier.
Doing this right would probably require another state (OPENED).
BUG=123998
BUG-134930
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10701040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | content::DownloadFile* MockDownloadFileFactory::CreateFile(
DownloadCreateInfo* info,
scoped_ptr<content::ByteStreamReader> stream,
content::DownloadManager* download_manager,
bool calculate_hash,
const net::BoundNetLog& bound_net_log) {
DCHECK(files_.end() == files_.find(info->download_id));
MockDownloadFile* created_file = new StrictMock<MockDownloadFile>();
files_[info->download_id] = created_file;
ON_CALL(*created_file, GetDownloadManager())
.WillByDefault(Return(download_manager));
EXPECT_CALL(*created_file, Initialize());
return created_file;
}
| 170,880 |
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 DefragTrackerInit(DefragTracker *dt, Packet *p)
{
/* copy address */
COPY_ADDRESS(&p->src, &dt->src_addr);
COPY_ADDRESS(&p->dst, &dt->dst_addr);
if (PKT_IS_IPV4(p)) {
dt->id = (int32_t)IPV4_GET_IPID(p);
dt->af = AF_INET;
} else {
dt->id = (int32_t)IPV6_EXTHDR_GET_FH_ID(p);
dt->af = AF_INET6;
}
dt->vlan_id[0] = p->vlan_id[0];
dt->vlan_id[1] = p->vlan_id[1];
dt->policy = DefragGetOsPolicy(p);
dt->host_timeout = DefragPolicyGetHostTimeout(p);
dt->remove = 0;
dt->seen_last = 0;
TAILQ_INIT(&dt->frags);
(void) DefragTrackerIncrUsecnt(dt);
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358 | static void DefragTrackerInit(DefragTracker *dt, Packet *p)
{
/* copy address */
COPY_ADDRESS(&p->src, &dt->src_addr);
COPY_ADDRESS(&p->dst, &dt->dst_addr);
if (PKT_IS_IPV4(p)) {
dt->id = (int32_t)IPV4_GET_IPID(p);
dt->af = AF_INET;
} else {
dt->id = (int32_t)IPV6_EXTHDR_GET_FH_ID(p);
dt->af = AF_INET6;
}
dt->proto = IP_GET_IPPROTO(p);
dt->vlan_id[0] = p->vlan_id[0];
dt->vlan_id[1] = p->vlan_id[1];
dt->policy = DefragGetOsPolicy(p);
dt->host_timeout = DefragPolicyGetHostTimeout(p);
dt->remove = 0;
dt->seen_last = 0;
TAILQ_INIT(&dt->frags);
(void) DefragTrackerIncrUsecnt(dt);
}
| 168,293 |
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: MediaRecorderHandler::~MediaRecorderHandler() {
DCHECK(main_render_thread_checker_.CalledOnValidThread());
if (client_)
client_->WriteData(
nullptr, 0u, true,
(TimeTicks::Now() - TimeTicks::UnixEpoch()).InMillisecondsF());
}
Commit Message: Check context is attached before creating MediaRecorder
Bug: 896736
Change-Id: I3ccfd2188fb15704af14c8af050e0a5667855d34
Reviewed-on: https://chromium-review.googlesource.com/c/1324231
Commit-Queue: Emircan Uysaler <[email protected]>
Reviewed-by: Miguel Casas <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606242}
CWE ID: CWE-119 | MediaRecorderHandler::~MediaRecorderHandler() {
DCHECK(main_render_thread_checker_.CalledOnValidThread());
if (client_) {
client_->WriteData(
nullptr, 0u, true,
(TimeTicks::Now() - TimeTicks::UnixEpoch()).InMillisecondsF());
}
}
| 172,604 |
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 GetNetworkList(NetworkInterfaceList* networks, int policy) {
int s = socket(AF_INET, SOCK_DGRAM, 0);
if (s <= 0) {
PLOG(ERROR) << "socket";
return false;
}
uint32_t num_ifs = 0;
if (ioctl_netc_get_num_ifs(s, &num_ifs) < 0) {
PLOG(ERROR) << "ioctl_netc_get_num_ifs";
PCHECK(close(s) == 0);
return false;
}
for (uint32_t i = 0; i < num_ifs; ++i) {
netc_if_info_t interface;
if (ioctl_netc_get_if_info_at(s, &i, &interface) < 0) {
PLOG(WARNING) << "ioctl_netc_get_if_info_at";
continue;
}
if (internal::IsLoopbackOrUnspecifiedAddress(
reinterpret_cast<sockaddr*>(&(interface.addr)))) {
continue;
}
IPEndPoint address;
if (!address.FromSockAddr(reinterpret_cast<sockaddr*>(&(interface.addr)),
sizeof(interface.addr))) {
DLOG(WARNING) << "ioctl_netc_get_if_info returned invalid address.";
continue;
}
int prefix_length = 0;
IPEndPoint netmask;
if (netmask.FromSockAddr(reinterpret_cast<sockaddr*>(&(interface.netmask)),
sizeof(interface.netmask))) {
prefix_length = MaskPrefixLength(netmask.address());
}
int attributes = 0;
networks->push_back(
NetworkInterface(interface.name, interface.name, interface.index,
NetworkChangeNotifier::CONNECTION_UNKNOWN,
address.address(), prefix_length, attributes));
}
PCHECK(close(s) == 0);
return true;
}
Commit Message: Reland "[Fuchsia] Use Netstack FIDL interface to get network interfaces."
This is a reland of b29fc269716e556be6b4e999bb4b24332cc43c6e
Original change's description:
> [Fuchsia] Use Netstack FIDL interface to get network interfaces.
>
> 1. Updated FILD GN template to generate and compile tables file, FIDL
> generated code was failing to link without them.
> 2. Updated GetNetworkList() for Fuchsia to FIDL API instead of ioctl().
>
> Bug: 831384
> Change-Id: Ib90303a5110a465ea5f2bad787a7b63a2bf13f61
> Reviewed-on: https://chromium-review.googlesource.com/1023124
> Commit-Queue: Sergey Ulanov <[email protected]>
> Reviewed-by: James Robinson <[email protected]>
> Reviewed-by: Matt Menke <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554868}
[email protected]
Bug: 831384
Change-Id: Iabb29661680b835b947b2780d169e204fd5e2559
Reviewed-on: https://chromium-review.googlesource.com/1036484
Commit-Queue: Sergey Ulanov <[email protected]>
Reviewed-by: Kevin Marshall <[email protected]>
Cr-Commit-Position: refs/heads/master@{#554946}
CWE ID: CWE-119 | bool GetNetworkList(NetworkInterfaceList* networks, int policy) {
IPAddress NetAddressToIPAddress(const netstack::NetAddress& addr) {
if (addr.ipv4) {
return IPAddress(addr.ipv4->addr.data(), addr.ipv4->addr.count());
}
if (addr.ipv6) {
return IPAddress(addr.ipv6->addr.data(), addr.ipv6->addr.count());
}
return IPAddress();
}
bool GetNetworkList(NetworkInterfaceList* networks, int policy) {
netstack::NetstackSyncPtr netstack =
base::fuchsia::ComponentContext::GetDefault()
->ConnectToServiceSync<netstack::Netstack>();
fidl::VectorPtr<netstack::NetInterface> interfaces;
if (!netstack->GetInterfaces(&interfaces))
return false;
for (auto& interface : interfaces.get()) {
// Check if the interface is up.
if (!(interface.flags & netstack::NetInterfaceFlagUp))
continue;
// Skip loopback.
if (interface.features & netstack::interfaceFeatureLoopback)
continue;
NetworkChangeNotifier::ConnectionType connection_type =
(interface.features & netstack::interfaceFeatureWlan)
? NetworkChangeNotifier::CONNECTION_WIFI
: NetworkChangeNotifier::CONNECTION_UNKNOWN;
// addresses. Currently Netstack doesn't provide this information.
int attributes = 0;
networks->push_back(NetworkInterface(
*interface.name, *interface.name, interface.id, connection_type,
NetAddressToIPAddress(interface.addr),
MaskPrefixLength(NetAddressToIPAddress(interface.netmask)),
attributes));
}
return true;
}
| 171,752 |
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 SelectionController::SetNonDirectionalSelectionIfNeeded(
const SelectionInFlatTree& passed_selection,
TextGranularity granularity,
EndPointsAdjustmentMode endpoints_adjustment_mode,
HandleVisibility handle_visibility) {
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets();
const VisibleSelectionInFlatTree& new_selection =
CreateVisibleSelection(passed_selection);
const PositionInFlatTree& base_position =
original_base_in_flat_tree_.GetPosition();
const VisiblePositionInFlatTree& original_base =
base_position.IsConnected() ? CreateVisiblePosition(base_position)
: VisiblePositionInFlatTree();
const VisiblePositionInFlatTree& base =
original_base.IsNotNull() ? original_base
: CreateVisiblePosition(new_selection.Base());
const VisiblePositionInFlatTree& extent =
CreateVisiblePosition(new_selection.Extent());
const SelectionInFlatTree& adjusted_selection =
endpoints_adjustment_mode == kAdjustEndpointsAtBidiBoundary
? AdjustEndpointsAtBidiBoundary(base, extent)
: SelectionInFlatTree::Builder()
.SetBaseAndExtent(base.DeepEquivalent(),
extent.DeepEquivalent())
.Build();
SelectionInFlatTree::Builder builder(new_selection.AsSelection());
if (adjusted_selection.Base() != base.DeepEquivalent() ||
adjusted_selection.Extent() != extent.DeepEquivalent()) {
original_base_in_flat_tree_ = base.ToPositionWithAffinity();
SetContext(&GetDocument());
builder.SetBaseAndExtent(adjusted_selection.Base(),
adjusted_selection.Extent());
} else if (original_base.IsNotNull()) {
if (CreateVisiblePosition(
Selection().ComputeVisibleSelectionInFlatTree().Base())
.DeepEquivalent() ==
CreateVisiblePosition(new_selection.Base()).DeepEquivalent()) {
builder.SetBaseAndExtent(original_base.DeepEquivalent(),
new_selection.Extent());
}
original_base_in_flat_tree_ = PositionInFlatTreeWithAffinity();
}
builder.SetIsHandleVisible(handle_visibility == HandleVisibility::kVisible);
const SelectionInFlatTree& selection_in_flat_tree = builder.Build();
if (Selection().ComputeVisibleSelectionInFlatTree() ==
CreateVisibleSelection(selection_in_flat_tree) &&
Selection().IsHandleVisible() == selection_in_flat_tree.IsHandleVisible())
return;
Selection().SetSelection(
ConvertToSelectionInDOMTree(selection_in_flat_tree),
SetSelectionData::Builder()
.SetShouldCloseTyping(true)
.SetShouldClearTypingStyle(true)
.SetCursorAlignOnScroll(CursorAlignOnScroll::kIfNeeded)
.SetGranularity(granularity)
.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 SelectionController::SetNonDirectionalSelectionIfNeeded(
const SelectionInFlatTree& passed_selection,
TextGranularity granularity,
EndPointsAdjustmentMode endpoints_adjustment_mode,
HandleVisibility handle_visibility) {
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets();
const VisibleSelectionInFlatTree& new_selection =
CreateVisibleSelection(passed_selection);
const PositionInFlatTree& base_position =
original_base_in_flat_tree_.GetPosition();
const VisiblePositionInFlatTree& original_base =
base_position.IsConnected() ? CreateVisiblePosition(base_position)
: VisiblePositionInFlatTree();
const VisiblePositionInFlatTree& base =
original_base.IsNotNull() ? original_base
: CreateVisiblePosition(new_selection.Base());
const VisiblePositionInFlatTree& extent =
CreateVisiblePosition(new_selection.Extent());
const SelectionInFlatTree& adjusted_selection =
endpoints_adjustment_mode == kAdjustEndpointsAtBidiBoundary
? AdjustEndpointsAtBidiBoundary(base, extent)
: SelectionInFlatTree::Builder()
.SetBaseAndExtent(base.DeepEquivalent(),
extent.DeepEquivalent())
.Build();
SelectionInFlatTree::Builder builder(new_selection.AsSelection());
if (adjusted_selection.Base() != base.DeepEquivalent() ||
adjusted_selection.Extent() != extent.DeepEquivalent()) {
original_base_in_flat_tree_ = base.ToPositionWithAffinity();
SetContext(&GetDocument());
builder.SetBaseAndExtent(adjusted_selection.Base(),
adjusted_selection.Extent());
} else if (original_base.IsNotNull()) {
if (CreateVisiblePosition(
Selection().ComputeVisibleSelectionInFlatTree().Base())
.DeepEquivalent() ==
CreateVisiblePosition(new_selection.Base()).DeepEquivalent()) {
builder.SetBaseAndExtent(original_base.DeepEquivalent(),
new_selection.Extent());
}
original_base_in_flat_tree_ = PositionInFlatTreeWithAffinity();
}
const SelectionInFlatTree& selection_in_flat_tree = builder.Build();
const bool should_show_handle =
handle_visibility == HandleVisibility::kVisible;
if (Selection().ComputeVisibleSelectionInFlatTree() ==
CreateVisibleSelection(selection_in_flat_tree) &&
Selection().IsHandleVisible() == should_show_handle)
return;
Selection().SetSelection(
ConvertToSelectionInDOMTree(selection_in_flat_tree),
SetSelectionData::Builder()
.SetShouldCloseTyping(true)
.SetShouldClearTypingStyle(true)
.SetCursorAlignOnScroll(CursorAlignOnScroll::kIfNeeded)
.SetGranularity(granularity)
.SetShouldShowHandle(should_show_handle)
.Build());
}
| 171,763 |
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: SPL_METHOD(DirectoryIterator, getFilename)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_STRING(intern->u.dir.entry.d_name, 1);
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(DirectoryIterator, getFilename)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_STRING(intern->u.dir.entry.d_name, 1);
}
| 167,033 |
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 DownloadController::StartAndroidDownload(
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
bool must_download, const DownloadInfo& info) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
WebContents* web_contents = wc_getter.Run();
if (!web_contents) {
LOG(ERROR) << "Download failed on URL:" << info.url.spec();
return;
}
AcquireFileAccessPermission(
web_contents,
base::Bind(&DownloadController::StartAndroidDownloadInternal,
base::Unretained(this), wc_getter, must_download, info));
}
Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack
The only exception is OMA DRM download.
And it only applies to context menu download interception.
Clean up the remaining unused code now.
BUG=647755
Review-Url: https://codereview.chromium.org/2371773003
Cr-Commit-Position: refs/heads/master@{#421332}
CWE ID: CWE-254 | void DownloadController::StartAndroidDownload(
| 171,883 |
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 cJSON_AddItemToObject( cJSON *object, const char *string, cJSON *item )
{
if ( ! item )
return;
if ( item->string )
cJSON_free( item->string );
item->string = cJSON_strdup( string );
cJSON_AddItemToArray( object, item );
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | void cJSON_AddItemToObject( cJSON *object, const char *string, cJSON *item )
| 167,268 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.