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: AppCacheUpdateJob::~AppCacheUpdateJob() {
if (service_)
service_->RemoveObserver(this);
if (internal_state_ != COMPLETED)
Cancel();
DCHECK(!manifest_fetcher_);
DCHECK(pending_url_fetches_.empty());
DCHECK(!inprogress_cache_.get());
DCHECK(pending_master_entries_.empty());
DCHECK(master_entry_fetches_.empty());
if (group_)
group_->SetUpdateAppCacheStatus(AppCacheGroup::IDLE);
}
Commit Message: AppCache: fix a browser crashing bug that can happen during updates.
BUG=558589
Review URL: https://codereview.chromium.org/1463463003
Cr-Commit-Position: refs/heads/master@{#360967}
CWE ID: | AppCacheUpdateJob::~AppCacheUpdateJob() {
if (service_)
service_->RemoveObserver(this);
if (internal_state_ != COMPLETED)
Cancel();
DCHECK(!inprogress_cache_.get());
DCHECK(pending_master_entries_.empty());
// The job must not outlive any of its fetchers.
CHECK(!manifest_fetcher_);
CHECK(pending_url_fetches_.empty());
CHECK(master_entry_fetches_.empty());
if (group_)
group_->SetUpdateAppCacheStatus(AppCacheGroup::IDLE);
}
| 171,734 |
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: const char* WinPKIErrorString(void)
{
static char error_string[64];
DWORD error_code = GetLastError();
if ((error_code >> 16) != 0x8009)
return WindowsErrorString();
switch (error_code) {
case NTE_BAD_UID:
return "Bad UID.";
case CRYPT_E_MSG_ERROR:
return "An error occurred while performing an operation on a cryptographic message.";
case CRYPT_E_UNKNOWN_ALGO:
return "Unknown cryptographic algorithm.";
case CRYPT_E_INVALID_MSG_TYPE:
return "Invalid cryptographic message type.";
case CRYPT_E_HASH_VALUE:
return "The hash value is not correct";
case CRYPT_E_ISSUER_SERIALNUMBER:
return "Invalid issuer and/or serial number.";
case CRYPT_E_BAD_LEN:
return "The length specified for the output data was insufficient.";
case CRYPT_E_BAD_ENCODE:
return "An error occurred during encode or decode operation.";
case CRYPT_E_FILE_ERROR:
return "An error occurred while reading or writing to a file.";
case CRYPT_E_NOT_FOUND:
return "Cannot find object or property.";
case CRYPT_E_EXISTS:
return "The object or property already exists.";
case CRYPT_E_NO_PROVIDER:
return "No provider was specified for the store or object.";
case CRYPT_E_DELETED_PREV:
return "The previous certificate or CRL context was deleted.";
case CRYPT_E_NO_MATCH:
return "Cannot find the requested object.";
case CRYPT_E_UNEXPECTED_MSG_TYPE:
case CRYPT_E_NO_KEY_PROPERTY:
case CRYPT_E_NO_DECRYPT_CERT:
return "Private key or certificate issue";
case CRYPT_E_BAD_MSG:
return "Not a cryptographic message.";
case CRYPT_E_NO_SIGNER:
return "The signed cryptographic message does not have a signer for the specified signer index.";
case CRYPT_E_REVOKED:
return "The certificate is revoked.";
case CRYPT_E_NO_REVOCATION_DLL:
case CRYPT_E_NO_REVOCATION_CHECK:
case CRYPT_E_REVOCATION_OFFLINE:
case CRYPT_E_NOT_IN_REVOCATION_DATABASE:
return "Cannot check certificate revocation.";
case CRYPT_E_INVALID_NUMERIC_STRING:
case CRYPT_E_INVALID_PRINTABLE_STRING:
case CRYPT_E_INVALID_IA5_STRING:
case CRYPT_E_INVALID_X500_STRING:
case CRYPT_E_NOT_CHAR_STRING:
return "Invalid string.";
case CRYPT_E_SECURITY_SETTINGS:
return "The cryptographic operation failed due to a local security option setting.";
case CRYPT_E_NO_VERIFY_USAGE_CHECK:
case CRYPT_E_VERIFY_USAGE_OFFLINE:
return "Cannot complete usage check.";
case CRYPT_E_NO_TRUSTED_SIGNER:
return "None of the signers of the cryptographic message or certificate trust list is trusted.";
default:
static_sprintf(error_string, "Unknown PKI error 0x%08lX", error_code);
return error_string;
}
}
Commit Message: [pki] fix https://www.kb.cert.org/vuls/id/403768
* This commit effectively fixes https://www.kb.cert.org/vuls/id/403768 (CVE-2017-13083) as
it is described per its revision 11, which is the latest revision at the time of this commit,
by disabling Windows prompts, enacted during signature validation, that allow the user to
bypass the intended signature verification checks.
* It needs to be pointed out that the vulnerability ("allow(ing) the use of a self-signed
certificate"), which relies on the end-user actively ignoring a Windows prompt that tells
them that the update failed the signature validation whilst also advising against running it,
is being fully addressed, even as the update protocol remains HTTP.
* It also need to be pointed out that the extended delay (48 hours) between the time the
vulnerability was reported and the moment it is fixed in our codebase has to do with
the fact that the reporter chose to deviate from standard security practices by not
disclosing the details of the vulnerability with us, be it publicly or privately,
before creating the cert.org report. The only advance notification we received was a
generic note about the use of HTTP vs HTTPS, which, as have established, is not
immediately relevant to addressing the reported vulnerability.
* Closes #1009
* Note: The other vulnerability scenario described towards the end of #1009, which
doesn't have to do with the "lack of CA checking", will be addressed separately.
CWE ID: CWE-494 | const char* WinPKIErrorString(void)
{
static char error_string[64];
DWORD error_code = GetLastError();
if (((error_code >> 16) != 0x8009) && ((error_code >> 16) != 0x800B))
return WindowsErrorString();
switch (error_code) {
case NTE_BAD_UID:
return "Bad UID.";
case CRYPT_E_MSG_ERROR:
return "An error occurred while performing an operation on a cryptographic message.";
case CRYPT_E_UNKNOWN_ALGO:
return "Unknown cryptographic algorithm.";
case CRYPT_E_INVALID_MSG_TYPE:
return "Invalid cryptographic message type.";
case CRYPT_E_HASH_VALUE:
return "The hash value is not correct";
case CRYPT_E_ISSUER_SERIALNUMBER:
return "Invalid issuer and/or serial number.";
case CRYPT_E_BAD_LEN:
return "The length specified for the output data was insufficient.";
case CRYPT_E_BAD_ENCODE:
return "An error occurred during encode or decode operation.";
case CRYPT_E_FILE_ERROR:
return "An error occurred while reading or writing to a file.";
case CRYPT_E_NOT_FOUND:
return "Cannot find object or property.";
case CRYPT_E_EXISTS:
return "The object or property already exists.";
case CRYPT_E_NO_PROVIDER:
return "No provider was specified for the store or object.";
case CRYPT_E_DELETED_PREV:
return "The previous certificate or CRL context was deleted.";
case CRYPT_E_NO_MATCH:
return "Cannot find the requested object.";
case CRYPT_E_UNEXPECTED_MSG_TYPE:
case CRYPT_E_NO_KEY_PROPERTY:
case CRYPT_E_NO_DECRYPT_CERT:
return "Private key or certificate issue";
case CRYPT_E_BAD_MSG:
return "Not a cryptographic message.";
case CRYPT_E_NO_SIGNER:
return "The signed cryptographic message does not have a signer for the specified signer index.";
case CRYPT_E_REVOKED:
return "The certificate is revoked.";
case CRYPT_E_NO_REVOCATION_DLL:
case CRYPT_E_NO_REVOCATION_CHECK:
case CRYPT_E_REVOCATION_OFFLINE:
case CRYPT_E_NOT_IN_REVOCATION_DATABASE:
return "Cannot check certificate revocation.";
case CRYPT_E_INVALID_NUMERIC_STRING:
case CRYPT_E_INVALID_PRINTABLE_STRING:
case CRYPT_E_INVALID_IA5_STRING:
case CRYPT_E_INVALID_X500_STRING:
case CRYPT_E_NOT_CHAR_STRING:
return "Invalid string.";
case CRYPT_E_SECURITY_SETTINGS:
return "The cryptographic operation failed due to a local security option setting.";
case CRYPT_E_NO_VERIFY_USAGE_CHECK:
case CRYPT_E_VERIFY_USAGE_OFFLINE:
return "Cannot complete usage check.";
case CRYPT_E_NO_TRUSTED_SIGNER:
return "None of the signers of the cryptographic message or certificate trust list is trusted.";
case CERT_E_UNTRUSTEDROOT:
return "The root certificate is not trusted.";
case TRUST_E_NOSIGNATURE:
return "Not digitally signed.";
case TRUST_E_EXPLICIT_DISTRUST:
return "One of the certificates used was marked as untrusted by the user.";
default:
static_sprintf(error_string, "Unknown PKI error 0x%08lX", error_code);
return error_string;
}
}
| 167,816 |
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 Con_Dump_f( void ) {
int l, x, i;
short *line;
fileHandle_t f;
int bufferlen;
char *buffer;
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "usage: condump <filename>\n" );
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".txt" );
f = FS_FOpenFileWrite( filename );
if ( !f ) {
Com_Printf ("ERROR: couldn't open %s.\n", filename);
return;
}
Com_Printf ("Dumped console text to %s.\n", filename );
for ( l = con.current - con.totallines + 1 ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( x = 0 ; x < con.linewidth ; x++ )
if ( ( line[x] & 0xff ) != ' ' ) {
break;
}
if ( x != con.linewidth ) {
break;
}
}
#ifdef _WIN32
bufferlen = con.linewidth + 3 * sizeof ( char );
#else
bufferlen = con.linewidth + 2 * sizeof ( char );
#endif
buffer = Hunk_AllocateTempMemory( bufferlen );
buffer[bufferlen-1] = 0;
for ( ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( i = 0; i < con.linewidth; i++ )
buffer[i] = line[i] & 0xff;
for ( x = con.linewidth - 1 ; x >= 0 ; x-- )
{
if ( buffer[x] == ' ' ) {
buffer[x] = 0;
} else {
break;
}
}
#ifdef _WIN32
Q_strcat(buffer, bufferlen, "\r\n");
#else
Q_strcat(buffer, bufferlen, "\n");
#endif
FS_Write( buffer, strlen( buffer ), f );
}
Hunk_FreeTempMemory( buffer );
FS_FCloseFile( f );
}
Commit Message: All: Merge some file writing extension checks
CWE ID: CWE-269 | void Con_Dump_f( void ) {
int l, x, i;
short *line;
fileHandle_t f;
int bufferlen;
char *buffer;
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "usage: condump <filename>\n" );
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".txt" );
if (!COM_CompareExtension(filename, ".txt"))
{
Com_Printf("Con_Dump_f: Only the \".txt\" extension is supported by this command!\n");
return;
}
f = FS_FOpenFileWrite( filename );
if ( !f ) {
Com_Printf ("ERROR: couldn't open %s.\n", filename);
return;
}
Com_Printf ("Dumped console text to %s.\n", filename );
for ( l = con.current - con.totallines + 1 ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( x = 0 ; x < con.linewidth ; x++ )
if ( ( line[x] & 0xff ) != ' ' ) {
break;
}
if ( x != con.linewidth ) {
break;
}
}
#ifdef _WIN32
bufferlen = con.linewidth + 3 * sizeof ( char );
#else
bufferlen = con.linewidth + 2 * sizeof ( char );
#endif
buffer = Hunk_AllocateTempMemory( bufferlen );
buffer[bufferlen-1] = 0;
for ( ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( i = 0; i < con.linewidth; i++ )
buffer[i] = line[i] & 0xff;
for ( x = con.linewidth - 1 ; x >= 0 ; x-- )
{
if ( buffer[x] == ' ' ) {
buffer[x] = 0;
} else {
break;
}
}
#ifdef _WIN32
Q_strcat(buffer, bufferlen, "\r\n");
#else
Q_strcat(buffer, bufferlen, "\n");
#endif
FS_Write( buffer, strlen( buffer ), f );
}
Hunk_FreeTempMemory( buffer );
FS_FCloseFile( f );
}
| 170,079 |
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 *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
IndexPacket
index;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
number_planes_filled,
one,
offset,
pixel_info_length;
ssize_t
count,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=ReadBlobLSBShort(image);
image->page.y=ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->matte=flags & 0x04 ? MagickTrue : MagickFalse;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) ||
((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate RLE pixels.
*/
if (image->matte != MagickFalse)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
number_planes_filled=(number_planes % 2 == 0) ? number_planes :
number_planes+1;
if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*
number_planes_filled))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
number_planes_filled*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*number_planes_filled;
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->matte == MagickFalse)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
operand++;
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
p=pixels+offset;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (IsValidColormapIndex(image,*p & mask,&index,exception) ==
MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
if (IsValidColormapIndex(image,(size_t) (x*map_length+
(*p & mask)),&index,exception) == MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p);
image->colormap[i].green=ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->matte == MagickFalse)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*p++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelRed(q,image->colormap[(ssize_t) index].red);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelGreen(q,image->colormap[(ssize_t) index].green);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelBlue(q,image->colormap[(ssize_t) index].blue);
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelPacket *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: https://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=29710
CWE ID: CWE-119 | static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
IndexPacket
index;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
number_planes_filled,
one,
offset,
pixel_info_length;
ssize_t
count,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=ReadBlobLSBShort(image);
image->page.y=ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->matte=flags & 0x04 ? MagickTrue : MagickFalse;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) ||
((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate RLE pixels.
*/
if (image->matte != MagickFalse)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
number_planes_filled=(number_planes % 2 == 0) ? number_planes :
number_planes+1;
if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*
number_planes_filled))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
MagickMax(number_planes_filled,4)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*
MagickMax(number_planes_filled,4);
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->matte == MagickFalse)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
operand++;
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
p=pixels+offset;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (IsValidColormapIndex(image,*p & mask,&index,exception) ==
MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
if (IsValidColormapIndex(image,(size_t) (x*map_length+
(*p & mask)),&index,exception) == MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p);
image->colormap[i].green=ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->matte == MagickFalse)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*p++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelRed(q,image->colormap[(ssize_t) index].red);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelGreen(q,image->colormap[(ssize_t) index].green);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelBlue(q,image->colormap[(ssize_t) index].blue);
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelPacket *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,641 |
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 Navigate(NavigateParams* params) {
Browser* source_browser = params->browser;
if (source_browser)
params->initiating_profile = source_browser->profile();
DCHECK(params->initiating_profile);
if (!AdjustNavigateParamsForURL(params))
return;
#if BUILDFLAG(ENABLE_EXTENSIONS)
const extensions::Extension* extension =
extensions::ExtensionRegistry::Get(params->initiating_profile)->
enabled_extensions().GetExtensionOrAppByURL(params->url);
if (extension && extension->is_platform_app())
params->url = GURL(chrome::kExtensionInvalidRequestURL);
#endif
if (params->disposition == WindowOpenDisposition::NEW_POPUP &&
source_browser && source_browser->window()) {
params->disposition =
source_browser->window()->GetDispositionForPopupBounds(
params->window_bounds);
}
if (source_browser && source_browser->is_app() &&
params->disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB) {
params->disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB;
}
if (!params->source_contents && params->browser) {
params->source_contents =
params->browser->tab_strip_model()->GetActiveWebContents();
}
WebContents* contents_to_navigate_or_insert =
params->contents_to_insert.get();
if (params->switch_to_singleton_tab) {
DCHECK_EQ(params->disposition, WindowOpenDisposition::SINGLETON_TAB);
contents_to_navigate_or_insert = params->switch_to_singleton_tab;
}
int singleton_index;
std::tie(params->browser, singleton_index) =
GetBrowserAndTabForDisposition(*params);
if (!params->browser)
return;
if (singleton_index != -1) {
contents_to_navigate_or_insert =
params->browser->tab_strip_model()->GetWebContentsAt(singleton_index);
}
#if defined(OS_CHROMEOS)
if (source_browser && source_browser != params->browser) {
MultiUserWindowManager* manager = MultiUserWindowManager::GetInstance();
if (manager) {
aura::Window* src_window = source_browser->window()->GetNativeWindow();
aura::Window* new_window = params->browser->window()->GetNativeWindow();
const AccountId& src_account_id =
manager->GetUserPresentingWindow(src_window);
if (src_account_id != manager->GetUserPresentingWindow(new_window)) {
manager->ShowWindowForUser(new_window, src_account_id);
}
}
}
#endif
if (GetSourceProfile(params) != params->browser->profile()) {
params->opener = nullptr;
params->source_contents = nullptr;
params->source_site_instance = nullptr;
params->referrer = content::Referrer();
}
ScopedBrowserShower shower(params, &contents_to_navigate_or_insert);
std::unique_ptr<WebContents> contents_to_insert =
std::move(params->contents_to_insert);
NormalizeDisposition(params);
if (params->window_action == NavigateParams::NO_ACTION &&
source_browser != params->browser &&
params->browser->tab_strip_model()->empty()) {
params->window_action = NavigateParams::SHOW_WINDOW;
}
if (params->window_action == NavigateParams::SHOW_WINDOW &&
params->disposition == WindowOpenDisposition::NEW_POPUP &&
params->user_gesture == false) {
params->window_action = NavigateParams::SHOW_WINDOW_INACTIVE;
}
bool user_initiated =
params->transition & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_TYPED) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_AUTO_BOOKMARK) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_GENERATED) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_AUTO_TOPLEVEL) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_RELOAD) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_KEYWORD);
bool swapped_in_prerender = false;
if (!contents_to_navigate_or_insert) {
DCHECK(!params->url.is_empty());
if (params->disposition != WindowOpenDisposition::CURRENT_TAB) {
contents_to_insert = CreateTargetContents(*params, params->url);
contents_to_navigate_or_insert = contents_to_insert.get();
} else {
DCHECK(params->source_contents);
contents_to_navigate_or_insert = params->source_contents;
prerender::PrerenderManager::Params prerender_params(
params, params->source_contents);
swapped_in_prerender = SwapInPrerender(params->url, &prerender_params);
if (swapped_in_prerender)
contents_to_navigate_or_insert = prerender_params.replaced_contents;
}
if (user_initiated)
contents_to_navigate_or_insert->NavigatedByUser();
if (!swapped_in_prerender) {
if (!HandleNonNavigationAboutURL(params->url)) {
LoadURLInContents(contents_to_navigate_or_insert, params->url, params);
}
}
} else {
}
if (params->source_contents &&
(params->disposition == WindowOpenDisposition::NEW_FOREGROUND_TAB ||
params->disposition == WindowOpenDisposition::NEW_WINDOW) &&
(params->tabstrip_add_types & TabStripModel::ADD_INHERIT_OPENER))
params->source_contents->Focus();
if (params->source_contents == contents_to_navigate_or_insert ||
(swapped_in_prerender &&
params->disposition == WindowOpenDisposition::CURRENT_TAB)) {
params->browser->UpdateUIForNavigationInTab(
contents_to_navigate_or_insert, params->transition,
params->window_action, user_initiated);
} else if (singleton_index == -1) {
if (params->tabstrip_index != -1)
params->tabstrip_add_types |= TabStripModel::ADD_FORCE_INDEX;
DCHECK(contents_to_insert);
params->browser->tab_strip_model()->AddWebContents(
std::move(contents_to_insert), params->tabstrip_index,
params->transition, params->tabstrip_add_types);
}
if (singleton_index >= 0) {
if (params->disposition == WindowOpenDisposition::SWITCH_TO_TAB &&
params->browser != source_browser)
params->window_action = NavigateParams::SHOW_WINDOW;
if (contents_to_navigate_or_insert->IsCrashed()) {
contents_to_navigate_or_insert->GetController().Reload(
content::ReloadType::NORMAL, true);
} else if (params->path_behavior == NavigateParams::IGNORE_AND_NAVIGATE &&
contents_to_navigate_or_insert->GetURL() != params->url) {
LoadURLInContents(contents_to_navigate_or_insert, params->url, params);
}
if (params->source_contents != contents_to_navigate_or_insert) {
params->browser->tab_strip_model()->ActivateTabAt(singleton_index,
user_initiated);
if (params->disposition == WindowOpenDisposition::SWITCH_TO_TAB) {
if (params->source_contents->GetController().CanGoBack() ||
(params->source_contents->GetLastCommittedURL().spec() !=
chrome::kChromeUINewTabURL &&
params->source_contents->GetLastCommittedURL().spec() !=
chrome::kChromeSearchLocalNtpUrl &&
params->source_contents->GetLastCommittedURL().spec() !=
url::kAboutBlankURL))
params->source_contents->Focus();
else
params->source_contents->Close();
}
}
}
if (params->disposition != WindowOpenDisposition::CURRENT_TAB) {
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TAB_ADDED,
content::Source<content::WebContentsDelegate>(params->browser),
content::Details<WebContents>(contents_to_navigate_or_insert));
}
params->navigated_or_inserted_contents = contents_to_navigate_or_insert;
}
Commit Message: Mac: turn popups into new tabs while in fullscreen.
It's platform convention to show popups as new tabs while in
non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.)
This was implemented for Cocoa in a BrowserWindow override, but
it makes sense to just stick it into Browser and remove a ton
of override code put in just to support this.
BUG=858929, 868416
TEST=as in bugs
Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d
Reviewed-on: https://chromium-review.googlesource.com/1153455
Reviewed-by: Sidney San Martín <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#578755}
CWE ID: CWE-20 | void Navigate(NavigateParams* params) {
Browser* source_browser = params->browser;
if (source_browser)
params->initiating_profile = source_browser->profile();
DCHECK(params->initiating_profile);
if (!AdjustNavigateParamsForURL(params))
return;
#if BUILDFLAG(ENABLE_EXTENSIONS)
const extensions::Extension* extension =
extensions::ExtensionRegistry::Get(params->initiating_profile)->
enabled_extensions().GetExtensionOrAppByURL(params->url);
if (extension && extension->is_platform_app())
params->url = GURL(chrome::kExtensionInvalidRequestURL);
#endif
if (source_browser && source_browser->is_app() &&
params->disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB) {
params->disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB;
}
if (!params->source_contents && params->browser) {
params->source_contents =
params->browser->tab_strip_model()->GetActiveWebContents();
}
WebContents* contents_to_navigate_or_insert =
params->contents_to_insert.get();
if (params->switch_to_singleton_tab) {
DCHECK_EQ(params->disposition, WindowOpenDisposition::SINGLETON_TAB);
contents_to_navigate_or_insert = params->switch_to_singleton_tab;
}
int singleton_index;
std::tie(params->browser, singleton_index) =
GetBrowserAndTabForDisposition(*params);
if (!params->browser)
return;
if (singleton_index != -1) {
contents_to_navigate_or_insert =
params->browser->tab_strip_model()->GetWebContentsAt(singleton_index);
}
#if defined(OS_CHROMEOS)
if (source_browser && source_browser != params->browser) {
MultiUserWindowManager* manager = MultiUserWindowManager::GetInstance();
if (manager) {
aura::Window* src_window = source_browser->window()->GetNativeWindow();
aura::Window* new_window = params->browser->window()->GetNativeWindow();
const AccountId& src_account_id =
manager->GetUserPresentingWindow(src_window);
if (src_account_id != manager->GetUserPresentingWindow(new_window)) {
manager->ShowWindowForUser(new_window, src_account_id);
}
}
}
#endif
if (GetSourceProfile(params) != params->browser->profile()) {
params->opener = nullptr;
params->source_contents = nullptr;
params->source_site_instance = nullptr;
params->referrer = content::Referrer();
}
ScopedBrowserShower shower(params, &contents_to_navigate_or_insert);
std::unique_ptr<WebContents> contents_to_insert =
std::move(params->contents_to_insert);
NormalizeDisposition(params);
if (params->window_action == NavigateParams::NO_ACTION &&
source_browser != params->browser &&
params->browser->tab_strip_model()->empty()) {
params->window_action = NavigateParams::SHOW_WINDOW;
}
if (params->window_action == NavigateParams::SHOW_WINDOW &&
params->disposition == WindowOpenDisposition::NEW_POPUP &&
params->user_gesture == false) {
params->window_action = NavigateParams::SHOW_WINDOW_INACTIVE;
}
bool user_initiated =
params->transition & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_TYPED) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_AUTO_BOOKMARK) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_GENERATED) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_AUTO_TOPLEVEL) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_RELOAD) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_KEYWORD);
bool swapped_in_prerender = false;
if (!contents_to_navigate_or_insert) {
DCHECK(!params->url.is_empty());
if (params->disposition != WindowOpenDisposition::CURRENT_TAB) {
contents_to_insert = CreateTargetContents(*params, params->url);
contents_to_navigate_or_insert = contents_to_insert.get();
} else {
DCHECK(params->source_contents);
contents_to_navigate_or_insert = params->source_contents;
prerender::PrerenderManager::Params prerender_params(
params, params->source_contents);
swapped_in_prerender = SwapInPrerender(params->url, &prerender_params);
if (swapped_in_prerender)
contents_to_navigate_or_insert = prerender_params.replaced_contents;
}
if (user_initiated)
contents_to_navigate_or_insert->NavigatedByUser();
if (!swapped_in_prerender) {
if (!HandleNonNavigationAboutURL(params->url)) {
LoadURLInContents(contents_to_navigate_or_insert, params->url, params);
}
}
} else {
}
if (params->source_contents &&
(params->disposition == WindowOpenDisposition::NEW_FOREGROUND_TAB ||
params->disposition == WindowOpenDisposition::NEW_WINDOW) &&
(params->tabstrip_add_types & TabStripModel::ADD_INHERIT_OPENER))
params->source_contents->Focus();
if (params->source_contents == contents_to_navigate_or_insert ||
(swapped_in_prerender &&
params->disposition == WindowOpenDisposition::CURRENT_TAB)) {
params->browser->UpdateUIForNavigationInTab(
contents_to_navigate_or_insert, params->transition,
params->window_action, user_initiated);
} else if (singleton_index == -1) {
if (params->tabstrip_index != -1)
params->tabstrip_add_types |= TabStripModel::ADD_FORCE_INDEX;
DCHECK(contents_to_insert);
params->browser->tab_strip_model()->AddWebContents(
std::move(contents_to_insert), params->tabstrip_index,
params->transition, params->tabstrip_add_types);
}
if (singleton_index >= 0) {
if (params->disposition == WindowOpenDisposition::SWITCH_TO_TAB &&
params->browser != source_browser)
params->window_action = NavigateParams::SHOW_WINDOW;
if (contents_to_navigate_or_insert->IsCrashed()) {
contents_to_navigate_or_insert->GetController().Reload(
content::ReloadType::NORMAL, true);
} else if (params->path_behavior == NavigateParams::IGNORE_AND_NAVIGATE &&
contents_to_navigate_or_insert->GetURL() != params->url) {
LoadURLInContents(contents_to_navigate_or_insert, params->url, params);
}
if (params->source_contents != contents_to_navigate_or_insert) {
params->browser->tab_strip_model()->ActivateTabAt(singleton_index,
user_initiated);
if (params->disposition == WindowOpenDisposition::SWITCH_TO_TAB) {
if (params->source_contents->GetController().CanGoBack() ||
(params->source_contents->GetLastCommittedURL().spec() !=
chrome::kChromeUINewTabURL &&
params->source_contents->GetLastCommittedURL().spec() !=
chrome::kChromeSearchLocalNtpUrl &&
params->source_contents->GetLastCommittedURL().spec() !=
url::kAboutBlankURL))
params->source_contents->Focus();
else
params->source_contents->Close();
}
}
}
if (params->disposition != WindowOpenDisposition::CURRENT_TAB) {
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TAB_ADDED,
content::Source<content::WebContentsDelegate>(params->browser),
content::Details<WebContents>(contents_to_navigate_or_insert));
}
params->navigated_or_inserted_contents = contents_to_navigate_or_insert;
}
| 173,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 StorageHandler::GetUsageAndQuota(
const String& origin,
std::unique_ptr<GetUsageAndQuotaCallback> callback) {
if (!process_)
return callback->sendFailure(Response::InternalError());
GURL origin_url(origin);
if (!origin_url.is_valid()) {
return callback->sendFailure(
Response::Error(origin + " is not a valid URL"));
}
storage::QuotaManager* manager =
process_->GetStoragePartition()->GetQuotaManager();
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&GetUsageAndQuotaOnIOThread, base::RetainedRef(manager),
origin_url, base::Passed(std::move(callback))));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void StorageHandler::GetUsageAndQuota(
const String& origin,
std::unique_ptr<GetUsageAndQuotaCallback> callback) {
if (!storage_partition_)
return callback->sendFailure(Response::InternalError());
GURL origin_url(origin);
if (!origin_url.is_valid()) {
return callback->sendFailure(
Response::Error(origin + " is not a valid URL"));
}
storage::QuotaManager* manager = storage_partition_->GetQuotaManager();
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&GetUsageAndQuotaOnIOThread, base::RetainedRef(manager),
origin_url, base::Passed(std::move(callback))));
}
| 172,773 |
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: ~SessionRestoreImpl() {
STLDeleteElements(&windows_);
CHECK(profiles_getting_restored);
CHECK(profiles_getting_restored->find(profile_) !=
profiles_getting_restored->end());
profiles_getting_restored->erase(profile_);
if (profiles_getting_restored->empty()) {
delete profiles_getting_restored;
profiles_getting_restored = NULL;
}
g_browser_process->ReleaseModule();
}
Commit Message: Lands http://codereview.chromium.org/9316065/ for Marja. I reviewed
this, so I'm using TBR to land it.
Don't crash if multiple SessionRestoreImpl:s refer to the same
Profile.
It shouldn't ever happen but it seems to happen anyway.
BUG=111238
TEST=NONE
[email protected]
[email protected]
Review URL: https://chromiumcodereview.appspot.com/9343005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@120648 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | ~SessionRestoreImpl() {
STLDeleteElements(&windows_);
active_session_restorers->erase(this);
if (active_session_restorers->empty()) {
delete active_session_restorers;
active_session_restorers = NULL;
}
g_browser_process->ReleaseModule();
}
| 171,038 |
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 _dbus_printf_string_upper_bound (const char *format,
va_list args)
{
/* MSVCRT's vsnprintf semantics are a bit different */
char buf[1024];
int bufsize;
int len;
bufsize = sizeof (buf);
len = _vsnprintf (buf, bufsize - 1, format, args);
while (len == -1) /* try again */
{
p = malloc (bufsize);
if (p == NULL)
return -1;
if (p == NULL)
return -1;
len = _vsnprintf (p, bufsize - 1, format, args);
free (p);
}
* Returns the UTF-16 form of a UTF-8 string. The result should be
* freed with dbus_free() when no longer needed.
*
* @param str the UTF-8 string
* @param error return location for error code
*/
wchar_t *
_dbus_win_utf8_to_utf16 (const char *str,
DBusError *error)
{
DBusString s;
int n;
wchar_t *retval;
_dbus_string_init_const (&s, str);
if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
{
dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
return NULL;
}
n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
if (n == 0)
{
_dbus_win_set_error_from_win_error (error, GetLastError ());
return NULL;
}
retval = dbus_new (wchar_t, n);
if (!retval)
{
_DBUS_SET_OOM (error);
return NULL;
}
if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
{
dbus_free (retval);
dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
return NULL;
}
return retval;
}
/**
* Returns the UTF-8 form of a UTF-16 string. The result should be
* freed with dbus_free() when no longer needed.
*
* @param str the UTF-16 string
* @param error return location for error code
*/
char *
_dbus_win_utf16_to_utf8 (const wchar_t *str,
DBusError *error)
{
int n;
char *retval;
n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
if (n == 0)
{
_dbus_win_set_error_from_win_error (error, GetLastError ());
return NULL;
}
retval = dbus_malloc (n);
if (!retval)
{
_DBUS_SET_OOM (error);
return NULL;
}
if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
{
dbus_free (retval);
dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
return NULL;
}
return retval;
}
/************************************************************************
************************************************************************/
dbus_bool_t
_dbus_win_account_to_sid (const wchar_t *waccount,
void **ppsid,
DBusError *error)
{
dbus_bool_t retval = FALSE;
DWORD sid_length, wdomain_length;
SID_NAME_USE use;
wchar_t *wdomain;
*ppsid = NULL;
sid_length = 0;
wdomain_length = 0;
if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
NULL, &wdomain_length, &use) &&
GetLastError () != ERROR_INSUFFICIENT_BUFFER)
{
_dbus_win_set_error_from_win_error (error, GetLastError ());
return FALSE;
}
*ppsid = dbus_malloc (sid_length);
if (!*ppsid)
{
_DBUS_SET_OOM (error);
return FALSE;
}
wdomain = dbus_new (wchar_t, wdomain_length);
if (!wdomain)
{
_DBUS_SET_OOM (error);
goto out1;
}
if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
wdomain, &wdomain_length, &use))
{
_dbus_win_set_error_from_win_error (error, GetLastError ());
goto out2;
}
if (!IsValidSid ((PSID) *ppsid))
{
dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
goto out2;
}
retval = TRUE;
out2:
dbus_free (wdomain);
out1:
if (!retval)
{
dbus_free (*ppsid);
*ppsid = NULL;
}
return retval;
}
/** @} end of sysdeps-win */
Commit Message:
CWE ID: CWE-20 | int _dbus_printf_string_upper_bound (const char *format,
va_list args)
{
/* MSVCRT's vsnprintf semantics are a bit different */
char buf[1024];
int bufsize;
int len;
va_list args_copy;
bufsize = sizeof (buf);
DBUS_VA_COPY (args_copy, args);
len = _vsnprintf (buf, bufsize - 1, format, args_copy);
va_end (args_copy);
while (len == -1) /* try again */
{
p = malloc (bufsize);
if (p == NULL)
return -1;
if (p == NULL)
return -1;
DBUS_VA_COPY (args_copy, args);
len = _vsnprintf (p, bufsize - 1, format, args_copy);
va_end (args_copy);
free (p);
}
* Returns the UTF-16 form of a UTF-8 string. The result should be
* freed with dbus_free() when no longer needed.
*
* @param str the UTF-8 string
* @param error return location for error code
*/
wchar_t *
_dbus_win_utf8_to_utf16 (const char *str,
DBusError *error)
{
DBusString s;
int n;
wchar_t *retval;
_dbus_string_init_const (&s, str);
if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
{
dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
return NULL;
}
n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
if (n == 0)
{
_dbus_win_set_error_from_win_error (error, GetLastError ());
return NULL;
}
retval = dbus_new (wchar_t, n);
if (!retval)
{
_DBUS_SET_OOM (error);
return NULL;
}
if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
{
dbus_free (retval);
dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
return NULL;
}
return retval;
}
/**
* Returns the UTF-8 form of a UTF-16 string. The result should be
* freed with dbus_free() when no longer needed.
*
* @param str the UTF-16 string
* @param error return location for error code
*/
char *
_dbus_win_utf16_to_utf8 (const wchar_t *str,
DBusError *error)
{
int n;
char *retval;
n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
if (n == 0)
{
_dbus_win_set_error_from_win_error (error, GetLastError ());
return NULL;
}
retval = dbus_malloc (n);
if (!retval)
{
_DBUS_SET_OOM (error);
return NULL;
}
if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
{
dbus_free (retval);
dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
return NULL;
}
return retval;
}
/************************************************************************
************************************************************************/
dbus_bool_t
_dbus_win_account_to_sid (const wchar_t *waccount,
void **ppsid,
DBusError *error)
{
dbus_bool_t retval = FALSE;
DWORD sid_length, wdomain_length;
SID_NAME_USE use;
wchar_t *wdomain;
*ppsid = NULL;
sid_length = 0;
wdomain_length = 0;
if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
NULL, &wdomain_length, &use) &&
GetLastError () != ERROR_INSUFFICIENT_BUFFER)
{
_dbus_win_set_error_from_win_error (error, GetLastError ());
return FALSE;
}
*ppsid = dbus_malloc (sid_length);
if (!*ppsid)
{
_DBUS_SET_OOM (error);
return FALSE;
}
wdomain = dbus_new (wchar_t, wdomain_length);
if (!wdomain)
{
_DBUS_SET_OOM (error);
goto out1;
}
if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
wdomain, &wdomain_length, &use))
{
_dbus_win_set_error_from_win_error (error, GetLastError ());
goto out2;
}
if (!IsValidSid ((PSID) *ppsid))
{
dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
goto out2;
}
retval = TRUE;
out2:
dbus_free (wdomain);
out1:
if (!retval)
{
dbus_free (*ppsid);
*ppsid = NULL;
}
return retval;
}
/** @} end of sysdeps-win */
| 164,723 |
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: fp_set_per_packet_inf_from_conv(umts_fp_conversation_info_t *p_conv_data,
tvbuff_t *tvb, packet_info *pinfo,
proto_tree *tree _U_)
{
fp_info *fpi;
guint8 tfi, c_t;
int offset = 0, i=0, j=0, num_tbs, chan, tb_size, tb_bit_off;
gboolean is_control_frame;
umts_mac_info *macinf;
rlc_info *rlcinf;
guint8 fake_lchid=0;
gint *cur_val=NULL;
fpi = wmem_new0(wmem_file_scope(), fp_info);
p_add_proto_data(wmem_file_scope(), pinfo, proto_fp, 0, fpi);
fpi->iface_type = p_conv_data->iface_type;
fpi->division = p_conv_data->division;
fpi->release = 7; /* Set values greater then the checks performed */
fpi->release_year = 2006;
fpi->release_month = 12;
fpi->channel = p_conv_data->channel;
fpi->dch_crc_present = p_conv_data->dch_crc_present;
/*fpi->paging_indications;*/
fpi->link_type = FP_Link_Ethernet;
#if 0
/*Only do this the first run, signals that we need to reset the RLC fragtable*/
if (!pinfo->fd->flags.visited && p_conv_data->reset_frag ) {
fpi->reset_frag = p_conv_data->reset_frag;
p_conv_data->reset_frag = FALSE;
}
#endif
/* remember 'lower' UDP layer port information so we can later
* differentiate 'lower' UDP layer from 'user data' UDP layer */
fpi->srcport = pinfo->srcport;
fpi->destport = pinfo->destport;
fpi->com_context_id = p_conv_data->com_context_id;
if (pinfo->link_dir == P2P_DIR_UL) {
fpi->is_uplink = TRUE;
} else {
fpi->is_uplink = FALSE;
}
is_control_frame = tvb_get_guint8(tvb, offset) & 0x01;
switch (fpi->channel) {
case CHANNEL_HSDSCH: /* HS-DSCH - High Speed Downlink Shared Channel */
fpi->hsdsch_entity = p_conv_data->hsdsch_entity;
macinf = wmem_new0(wmem_file_scope(), umts_mac_info);
fpi->hsdsch_macflowd_id = p_conv_data->hsdsch_macdflow_id;
macinf->content[0] = hsdsch_macdflow_id_mac_content_map[p_conv_data->hsdsch_macdflow_id]; /*MAC_CONTENT_PS_DTCH;*/
macinf->lchid[0] = p_conv_data->hsdsch_macdflow_id;
/*macinf->content[0] = lchId_type_table[p_conv_data->edch_lchId[0]];*/
p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf);
rlcinf = wmem_new0(wmem_file_scope(), rlc_info);
/*Figure out RLC_MODE based on MACd-flow-ID, basically MACd-flow-ID = 0 then it's SRB0 == UM else AM*/
rlcinf->mode[0] = hsdsch_macdflow_id_rlc_map[p_conv_data->hsdsch_macdflow_id];
if (fpi->hsdsch_entity == hs /*&& !rlc_is_ciphered(pinfo)*/) {
for (i=0; i<MAX_NUM_HSDHSCH_MACDFLOW; i++) {
/*Figure out if this channel is multiplexed (signaled from RRC)*/
if ((cur_val=(gint *)g_tree_lookup(hsdsch_muxed_flows, GINT_TO_POINTER((gint)p_conv_data->hrnti))) != NULL) {
j = 1 << i;
fpi->hsdhsch_macfdlow_is_mux[i] = j & *cur_val;
} else {
fpi->hsdhsch_macfdlow_is_mux[i] = FALSE;
}
}
}
/* Make configurable ?(available in NBAP?) */
/* urnti[MAX_RLC_CHANS] */
/*
switch (p_conv_data->rlc_mode) {
case FP_RLC_TM:
rlcinf->mode[0] = RLC_TM;
break;
case FP_RLC_UM:
rlcinf->mode[0] = RLC_UM;
break;
case FP_RLC_AM:
rlcinf->mode[0] = RLC_AM;
break;
case FP_RLC_MODE_UNKNOWN:
default:
rlcinf->mode[0] = RLC_UNKNOWN_MODE;
break;
}*/
/* rbid[MAX_RLC_CHANS] */
/* For RLC re-assembly to work we urnti signaled from NBAP */
rlcinf->urnti[0] = fpi->com_context_id;
rlcinf->li_size[0] = RLC_LI_7BITS;
rlcinf->ciphered[0] = FALSE;
rlcinf->deciphered[0] = FALSE;
p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf);
return fpi;
case CHANNEL_EDCH:
/*Most configuration is now done in the actual dissecting function*/
macinf = wmem_new0(wmem_file_scope(), umts_mac_info);
rlcinf = wmem_new0(wmem_file_scope(), rlc_info);
fpi->no_ddi_entries = p_conv_data->no_ddi_entries;
for (i=0; i<fpi->no_ddi_entries; i++) {
fpi->edch_ddi[i] = p_conv_data->edch_ddi[i]; /*Set the DDI value*/
fpi->edch_macd_pdu_size[i] = p_conv_data->edch_macd_pdu_size[i]; /*Set the size*/
fpi->edch_lchId[i] = p_conv_data->edch_lchId[i]; /*Set the channel id for this entry*/
/*macinf->content[i] = lchId_type_table[p_conv_data->edch_lchId[i]]; */ /*Set the proper Content type for the mac layer.*/
/* rlcinf->mode[i] = lchId_rlc_map[p_conv_data->edch_lchId[i]];*/ /* Set RLC mode by lchid to RLC_MODE map in nbap.h */
}
fpi->edch_type = p_conv_data->edch_type;
/* macinf = wmem_new0(wmem_file_scope(), umts_mac_info);
macinf->content[0] = MAC_CONTENT_PS_DTCH;*/
p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf);
/* For RLC re-assembly to work we need a urnti signaled from NBAP */
rlcinf->urnti[0] = fpi->com_context_id;
/* rlcinf->mode[0] = RLC_AM;*/
rlcinf->li_size[0] = RLC_LI_7BITS;
rlcinf->ciphered[0] = FALSE;
rlcinf->deciphered[0] = FALSE;
p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf);
return fpi;
case CHANNEL_PCH:
fpi->paging_indications = p_conv_data->paging_indications;
fpi->num_chans = p_conv_data->num_dch_in_flow;
/* Set offset to point to first TFI
*/
if (is_control_frame) {
/* control frame, we're done */
return fpi;
}
/* Set offset to TFI */
offset = 3;
break;
case CHANNEL_DCH:
fpi->num_chans = p_conv_data->num_dch_in_flow;
if (is_control_frame) {
/* control frame, we're done */
return fpi;
}
rlcinf = wmem_new0(wmem_file_scope(), rlc_info);
macinf = wmem_new0(wmem_file_scope(), umts_mac_info);
offset = 2; /*To correctly read the tfi*/
fakes = 5; /* Reset fake counter. */
for (chan=0; chan < fpi->num_chans; chan++) { /*Iterate over the what channels*/
/*Iterate over the transport blocks*/
/*tfi = tvb_get_guint8(tvb, offset);*/
/*TFI is 5 bits according to 3GPP TS 25.321, paragraph 6.2.4.4*/
tfi = tvb_get_bits8(tvb, 3+offset*8, 5);
/*Figure out the number of tbs and size*/
num_tbs = (fpi->is_uplink) ? p_conv_data->fp_dch_channel_info[chan].ul_chan_num_tbs[tfi] : p_conv_data->fp_dch_channel_info[chan].dl_chan_num_tbs[tfi];
tb_size= (fpi->is_uplink) ? p_conv_data->fp_dch_channel_info[i].ul_chan_tf_size[tfi] : p_conv_data->fp_dch_channel_info[i].dl_chan_tf_size[tfi];
/*TODO: This stuff has to be reworked!*/
/*Generates a fake logical channel id for non multiplexed channel*/
if ( p_conv_data->dchs_in_flow_list[chan] != 31 && (p_conv_data->dchs_in_flow_list[chan] == 24 &&
tb_size != 340) ) {
fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]);
}
tb_bit_off = (2+p_conv_data->num_dch_in_flow)*8; /*Point to the C/T of first TB*/
/*Set configuration for individual blocks*/
for (j=0; j < num_tbs && j+chan < MAX_MAC_FRAMES; j++) {
/*Set transport channel id (useful for debugging)*/
macinf->trchid[j+chan] = p_conv_data->dchs_in_flow_list[chan];
/*Transport Channel m31 and 24 might be multiplexed!*/
if ( p_conv_data->dchs_in_flow_list[chan] == 31 || p_conv_data->dchs_in_flow_list[chan] == 24) {
/****** MUST FIGURE OUT IF THIS IS REALLY MULTIPLEXED OR NOT*******/
/*If Trchid == 31 and only on TB, we have no multiplexing*/
if (0/*p_conv_data->dchs_in_flow_list[chan] == 31 && num_tbs == 1*/) {
macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/
macinf->lchid[j+chan] = 1;
macinf->content[j+chan] = lchId_type_table[1]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/
rlcinf->mode[j+chan] = lchId_rlc_map[1]; /*Based RLC mode on logical channel id*/
}
/*Indicate we don't have multiplexing.*/
else if (p_conv_data->dchs_in_flow_list[chan] == 24 && tb_size != 340) {
macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/
/*g_warning("settin this for %d", pinfo->num);*/
macinf->lchid[j+chan] = fake_lchid;
macinf->fake_chid[j+chan] = TRUE;
macinf->content[j+chan] = MAC_CONTENT_PS_DTCH; /*lchId_type_table[fake_lchid];*/ /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/
rlcinf->mode[j+chan] = RLC_AM;/*lchId_rlc_map[fake_lchid];*/ /*Based RLC mode on logical channel id*/
}
/*We have multiplexing*/
else {
macinf->ctmux[j+chan] = TRUE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/
/* Peek at C/T, different RLC params for different logical channels */
/*C/T is 4 bits according to 3GPP TS 25.321, paragraph 9.2.1, from MAC header (not FP)*/
c_t = tvb_get_bits8(tvb, tb_bit_off/*(2+p_conv_data->num_dch_in_flow)*8*/, 4); /* c_t = tvb_get_guint8(tvb, offset);*/
macinf->lchid[j+chan] = c_t+1;
macinf->content[j+chan] = lchId_type_table[c_t+1]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/
rlcinf->mode[j+chan] = lchId_rlc_map[c_t+1]; /*Based RLC mode on logical channel id*/
}
} else {
fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]);
macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/
/*macinf->content[j+chan] = MAC_CONTENT_CS_DTCH;*/
macinf->content[j+chan] = lchId_type_table[fake_lchid];
rlcinf->mode[j+chan] = lchId_rlc_map[fake_lchid];
/*Generate virtual logical channel id*/
/************************/
/*TODO: Once proper lchid is always set, this has to be removed*/
macinf->fake_chid[j+chan] = TRUE;
macinf->lchid[j+chan] = fake_lchid; /*make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]);*/
/************************/
}
/*** Set rlc info ***/
rlcinf->urnti[j+chan] = p_conv_data->com_context_id;
rlcinf->li_size[j+chan] = RLC_LI_7BITS;
#if 0
/*If this entry exists, SECRUITY_MODE is completed (signled by RRC)*/
if ( rrc_ciph_inf && g_tree_lookup(rrc_ciph_inf, GINT_TO_POINTER((gint)p_conv_data->com_context_id)) != NULL ) {
rlcinf->ciphered[j+chan] = TRUE;
} else {
rlcinf->ciphered[j+chan] = FALSE;
}
#endif
rlcinf->ciphered[j+chan] = FALSE;
rlcinf->deciphered[j+chan] = FALSE;
rlcinf->rbid[j+chan] = macinf->lchid[j+chan];
/*Step over this TB and it's C/T flag.*/
tb_bit_off += tb_size+4;
}
offset++;
}
p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf);
p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf);
/* Set offset to point to first TFI
* the Number of TFI's = number of DCH's in the flow
*/
offset = 2;
break;
case CHANNEL_FACH_FDD:
fpi->num_chans = p_conv_data->num_dch_in_flow;
if (is_control_frame) {
/* control frame, we're done */
return fpi;
}
/* Set offset to point to first TFI
* the Number of TFI's = number of DCH's in the flow
*/
offset = 2;
/* Set MAC data */
macinf = wmem_new0(wmem_file_scope(), umts_mac_info);
macinf->ctmux[0] = 1;
macinf->content[0] = MAC_CONTENT_DCCH;
p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf);
/* Set RLC data */
rlcinf = wmem_new0(wmem_file_scope(), rlc_info);
/* Make configurable ?(avaliable in NBAP?) */
/* For RLC re-assembly to work we need to fake urnti */
rlcinf->urnti[0] = fpi->channel;
rlcinf->mode[0] = RLC_AM;
/* rbid[MAX_RLC_CHANS] */
rlcinf->li_size[0] = RLC_LI_7BITS;
rlcinf->ciphered[0] = FALSE;
rlcinf->deciphered[0] = FALSE;
p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf);
break;
case CHANNEL_RACH_FDD:
fpi->num_chans = p_conv_data->num_dch_in_flow;
if (is_control_frame) {
/* control frame, we're done */
return fpi;
}
/* Set offset to point to first TFI
* the Number of TFI's = number of DCH's in the flow
*/
offset = 2;
/* set MAC data */
macinf = wmem_new0(wmem_file_scope(), umts_mac_info);
rlcinf = wmem_new0(wmem_file_scope(), rlc_info);
for ( chan = 0; chan < fpi->num_chans; chan++ ) {
macinf->ctmux[chan] = 1;
macinf->content[chan] = MAC_CONTENT_DCCH;
rlcinf->urnti[chan] = fpi->com_context_id; /*Note that MAC probably will change this*/
}
p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf);
p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf);
break;
case CHANNEL_HSDSCH_COMMON:
rlcinf = wmem_new0(wmem_file_scope(), rlc_info);
macinf = wmem_new0(wmem_file_scope(), umts_mac_info);
p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf);
p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf);
break;
default:
expert_add_info(pinfo, NULL, &ei_fp_transport_channel_type_unknown);
return NULL;
}
/* Peek at the packet as the per packet info seems not to take the tfi into account */
for (i=0; i<fpi->num_chans; i++) {
tfi = tvb_get_guint8(tvb, offset);
/*TFI is 5 bits according to 3GPP TS 25.321, paragraph 6.2.4.4*/
/*tfi = tvb_get_bits8(tvb, offset*8, 5);*/
if (pinfo->link_dir == P2P_DIR_UL) {
fpi->chan_tf_size[i] = p_conv_data->fp_dch_channel_info[i].ul_chan_tf_size[tfi];
fpi->chan_num_tbs[i] = p_conv_data->fp_dch_channel_info[i].ul_chan_num_tbs[tfi];
} else {
fpi->chan_tf_size[i] = p_conv_data->fp_dch_channel_info[i].dl_chan_tf_size[tfi];
fpi->chan_num_tbs[i] = p_conv_data->fp_dch_channel_info[i].dl_chan_num_tbs[tfi];
}
offset++;
}
return fpi;
}
Commit Message: UMTS_FP: fix handling reserved C/T value
The spec puts the reserved value at 0xf but our internal table has 'unknown' at
0; since all the other values seem to be offset-by-one, just take the modulus
0xf to avoid running off the end of the table.
Bug: 12191
Change-Id: I83c8fb66797bbdee52a2246fb1eea6e37cbc7eb0
Reviewed-on: https://code.wireshark.org/review/15722
Reviewed-by: Evan Huus <[email protected]>
Petri-Dish: Evan Huus <[email protected]>
Tested-by: Petri Dish Buildbot <[email protected]>
Reviewed-by: Michael Mann <[email protected]>
CWE ID: CWE-20 | fp_set_per_packet_inf_from_conv(umts_fp_conversation_info_t *p_conv_data,
tvbuff_t *tvb, packet_info *pinfo,
proto_tree *tree _U_)
{
fp_info *fpi;
guint8 tfi, c_t;
int offset = 0, i=0, j=0, num_tbs, chan, tb_size, tb_bit_off;
gboolean is_control_frame;
umts_mac_info *macinf;
rlc_info *rlcinf;
guint8 fake_lchid=0;
gint *cur_val=NULL;
fpi = wmem_new0(wmem_file_scope(), fp_info);
p_add_proto_data(wmem_file_scope(), pinfo, proto_fp, 0, fpi);
fpi->iface_type = p_conv_data->iface_type;
fpi->division = p_conv_data->division;
fpi->release = 7; /* Set values greater then the checks performed */
fpi->release_year = 2006;
fpi->release_month = 12;
fpi->channel = p_conv_data->channel;
fpi->dch_crc_present = p_conv_data->dch_crc_present;
/*fpi->paging_indications;*/
fpi->link_type = FP_Link_Ethernet;
#if 0
/*Only do this the first run, signals that we need to reset the RLC fragtable*/
if (!pinfo->fd->flags.visited && p_conv_data->reset_frag ) {
fpi->reset_frag = p_conv_data->reset_frag;
p_conv_data->reset_frag = FALSE;
}
#endif
/* remember 'lower' UDP layer port information so we can later
* differentiate 'lower' UDP layer from 'user data' UDP layer */
fpi->srcport = pinfo->srcport;
fpi->destport = pinfo->destport;
fpi->com_context_id = p_conv_data->com_context_id;
if (pinfo->link_dir == P2P_DIR_UL) {
fpi->is_uplink = TRUE;
} else {
fpi->is_uplink = FALSE;
}
is_control_frame = tvb_get_guint8(tvb, offset) & 0x01;
switch (fpi->channel) {
case CHANNEL_HSDSCH: /* HS-DSCH - High Speed Downlink Shared Channel */
fpi->hsdsch_entity = p_conv_data->hsdsch_entity;
macinf = wmem_new0(wmem_file_scope(), umts_mac_info);
fpi->hsdsch_macflowd_id = p_conv_data->hsdsch_macdflow_id;
macinf->content[0] = hsdsch_macdflow_id_mac_content_map[p_conv_data->hsdsch_macdflow_id]; /*MAC_CONTENT_PS_DTCH;*/
macinf->lchid[0] = p_conv_data->hsdsch_macdflow_id;
/*macinf->content[0] = lchId_type_table[p_conv_data->edch_lchId[0]];*/
p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf);
rlcinf = wmem_new0(wmem_file_scope(), rlc_info);
/*Figure out RLC_MODE based on MACd-flow-ID, basically MACd-flow-ID = 0 then it's SRB0 == UM else AM*/
rlcinf->mode[0] = hsdsch_macdflow_id_rlc_map[p_conv_data->hsdsch_macdflow_id];
if (fpi->hsdsch_entity == hs /*&& !rlc_is_ciphered(pinfo)*/) {
for (i=0; i<MAX_NUM_HSDHSCH_MACDFLOW; i++) {
/*Figure out if this channel is multiplexed (signaled from RRC)*/
if ((cur_val=(gint *)g_tree_lookup(hsdsch_muxed_flows, GINT_TO_POINTER((gint)p_conv_data->hrnti))) != NULL) {
j = 1 << i;
fpi->hsdhsch_macfdlow_is_mux[i] = j & *cur_val;
} else {
fpi->hsdhsch_macfdlow_is_mux[i] = FALSE;
}
}
}
/* Make configurable ?(available in NBAP?) */
/* urnti[MAX_RLC_CHANS] */
/*
switch (p_conv_data->rlc_mode) {
case FP_RLC_TM:
rlcinf->mode[0] = RLC_TM;
break;
case FP_RLC_UM:
rlcinf->mode[0] = RLC_UM;
break;
case FP_RLC_AM:
rlcinf->mode[0] = RLC_AM;
break;
case FP_RLC_MODE_UNKNOWN:
default:
rlcinf->mode[0] = RLC_UNKNOWN_MODE;
break;
}*/
/* rbid[MAX_RLC_CHANS] */
/* For RLC re-assembly to work we urnti signaled from NBAP */
rlcinf->urnti[0] = fpi->com_context_id;
rlcinf->li_size[0] = RLC_LI_7BITS;
rlcinf->ciphered[0] = FALSE;
rlcinf->deciphered[0] = FALSE;
p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf);
return fpi;
case CHANNEL_EDCH:
/*Most configuration is now done in the actual dissecting function*/
macinf = wmem_new0(wmem_file_scope(), umts_mac_info);
rlcinf = wmem_new0(wmem_file_scope(), rlc_info);
fpi->no_ddi_entries = p_conv_data->no_ddi_entries;
for (i=0; i<fpi->no_ddi_entries; i++) {
fpi->edch_ddi[i] = p_conv_data->edch_ddi[i]; /*Set the DDI value*/
fpi->edch_macd_pdu_size[i] = p_conv_data->edch_macd_pdu_size[i]; /*Set the size*/
fpi->edch_lchId[i] = p_conv_data->edch_lchId[i]; /*Set the channel id for this entry*/
/*macinf->content[i] = lchId_type_table[p_conv_data->edch_lchId[i]]; */ /*Set the proper Content type for the mac layer.*/
/* rlcinf->mode[i] = lchId_rlc_map[p_conv_data->edch_lchId[i]];*/ /* Set RLC mode by lchid to RLC_MODE map in nbap.h */
}
fpi->edch_type = p_conv_data->edch_type;
/* macinf = wmem_new0(wmem_file_scope(), umts_mac_info);
macinf->content[0] = MAC_CONTENT_PS_DTCH;*/
p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf);
/* For RLC re-assembly to work we need a urnti signaled from NBAP */
rlcinf->urnti[0] = fpi->com_context_id;
/* rlcinf->mode[0] = RLC_AM;*/
rlcinf->li_size[0] = RLC_LI_7BITS;
rlcinf->ciphered[0] = FALSE;
rlcinf->deciphered[0] = FALSE;
p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf);
return fpi;
case CHANNEL_PCH:
fpi->paging_indications = p_conv_data->paging_indications;
fpi->num_chans = p_conv_data->num_dch_in_flow;
/* Set offset to point to first TFI
*/
if (is_control_frame) {
/* control frame, we're done */
return fpi;
}
/* Set offset to TFI */
offset = 3;
break;
case CHANNEL_DCH:
fpi->num_chans = p_conv_data->num_dch_in_flow;
if (is_control_frame) {
/* control frame, we're done */
return fpi;
}
rlcinf = wmem_new0(wmem_file_scope(), rlc_info);
macinf = wmem_new0(wmem_file_scope(), umts_mac_info);
offset = 2; /*To correctly read the tfi*/
fakes = 5; /* Reset fake counter. */
for (chan=0; chan < fpi->num_chans; chan++) { /*Iterate over the what channels*/
/*Iterate over the transport blocks*/
/*tfi = tvb_get_guint8(tvb, offset);*/
/*TFI is 5 bits according to 3GPP TS 25.321, paragraph 6.2.4.4*/
tfi = tvb_get_bits8(tvb, 3+offset*8, 5);
/*Figure out the number of tbs and size*/
num_tbs = (fpi->is_uplink) ? p_conv_data->fp_dch_channel_info[chan].ul_chan_num_tbs[tfi] : p_conv_data->fp_dch_channel_info[chan].dl_chan_num_tbs[tfi];
tb_size= (fpi->is_uplink) ? p_conv_data->fp_dch_channel_info[i].ul_chan_tf_size[tfi] : p_conv_data->fp_dch_channel_info[i].dl_chan_tf_size[tfi];
/*TODO: This stuff has to be reworked!*/
/*Generates a fake logical channel id for non multiplexed channel*/
if ( p_conv_data->dchs_in_flow_list[chan] != 31 && (p_conv_data->dchs_in_flow_list[chan] == 24 &&
tb_size != 340) ) {
fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]);
}
tb_bit_off = (2+p_conv_data->num_dch_in_flow)*8; /*Point to the C/T of first TB*/
/*Set configuration for individual blocks*/
for (j=0; j < num_tbs && j+chan < MAX_MAC_FRAMES; j++) {
/*Set transport channel id (useful for debugging)*/
macinf->trchid[j+chan] = p_conv_data->dchs_in_flow_list[chan];
/*Transport Channel m31 and 24 might be multiplexed!*/
if ( p_conv_data->dchs_in_flow_list[chan] == 31 || p_conv_data->dchs_in_flow_list[chan] == 24) {
/****** MUST FIGURE OUT IF THIS IS REALLY MULTIPLEXED OR NOT*******/
/*If Trchid == 31 and only on TB, we have no multiplexing*/
if (0/*p_conv_data->dchs_in_flow_list[chan] == 31 && num_tbs == 1*/) {
macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/
macinf->lchid[j+chan] = 1;
macinf->content[j+chan] = lchId_type_table[1]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/
rlcinf->mode[j+chan] = lchId_rlc_map[1]; /*Based RLC mode on logical channel id*/
}
/*Indicate we don't have multiplexing.*/
else if (p_conv_data->dchs_in_flow_list[chan] == 24 && tb_size != 340) {
macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/
/*g_warning("settin this for %d", pinfo->num);*/
macinf->lchid[j+chan] = fake_lchid;
macinf->fake_chid[j+chan] = TRUE;
macinf->content[j+chan] = MAC_CONTENT_PS_DTCH; /*lchId_type_table[fake_lchid];*/ /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/
rlcinf->mode[j+chan] = RLC_AM;/*lchId_rlc_map[fake_lchid];*/ /*Based RLC mode on logical channel id*/
}
/*We have multiplexing*/
else {
macinf->ctmux[j+chan] = TRUE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/
/* Peek at C/T, different RLC params for different logical channels */
/*C/T is 4 bits according to 3GPP TS 25.321, paragraph 9.2.1, from MAC header (not FP)*/
c_t = (tvb_get_bits8(tvb, tb_bit_off/*(2+p_conv_data->num_dch_in_flow)*8*/, 4) + 1) % 0xf; /* c_t = tvb_get_guint8(tvb, offset);*/
macinf->lchid[j+chan] = c_t;
macinf->content[j+chan] = lchId_type_table[c_t]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/
rlcinf->mode[j+chan] = lchId_rlc_map[c_t]; /*Based RLC mode on logical channel id*/
}
} else {
fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]);
macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/
/*macinf->content[j+chan] = MAC_CONTENT_CS_DTCH;*/
macinf->content[j+chan] = lchId_type_table[fake_lchid];
rlcinf->mode[j+chan] = lchId_rlc_map[fake_lchid];
/*Generate virtual logical channel id*/
/************************/
/*TODO: Once proper lchid is always set, this has to be removed*/
macinf->fake_chid[j+chan] = TRUE;
macinf->lchid[j+chan] = fake_lchid; /*make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]);*/
/************************/
}
/*** Set rlc info ***/
rlcinf->urnti[j+chan] = p_conv_data->com_context_id;
rlcinf->li_size[j+chan] = RLC_LI_7BITS;
#if 0
/*If this entry exists, SECRUITY_MODE is completed (signled by RRC)*/
if ( rrc_ciph_inf && g_tree_lookup(rrc_ciph_inf, GINT_TO_POINTER((gint)p_conv_data->com_context_id)) != NULL ) {
rlcinf->ciphered[j+chan] = TRUE;
} else {
rlcinf->ciphered[j+chan] = FALSE;
}
#endif
rlcinf->ciphered[j+chan] = FALSE;
rlcinf->deciphered[j+chan] = FALSE;
rlcinf->rbid[j+chan] = macinf->lchid[j+chan];
/*Step over this TB and it's C/T flag.*/
tb_bit_off += tb_size+4;
}
offset++;
}
p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf);
p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf);
/* Set offset to point to first TFI
* the Number of TFI's = number of DCH's in the flow
*/
offset = 2;
break;
case CHANNEL_FACH_FDD:
fpi->num_chans = p_conv_data->num_dch_in_flow;
if (is_control_frame) {
/* control frame, we're done */
return fpi;
}
/* Set offset to point to first TFI
* the Number of TFI's = number of DCH's in the flow
*/
offset = 2;
/* Set MAC data */
macinf = wmem_new0(wmem_file_scope(), umts_mac_info);
macinf->ctmux[0] = 1;
macinf->content[0] = MAC_CONTENT_DCCH;
p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf);
/* Set RLC data */
rlcinf = wmem_new0(wmem_file_scope(), rlc_info);
/* Make configurable ?(avaliable in NBAP?) */
/* For RLC re-assembly to work we need to fake urnti */
rlcinf->urnti[0] = fpi->channel;
rlcinf->mode[0] = RLC_AM;
/* rbid[MAX_RLC_CHANS] */
rlcinf->li_size[0] = RLC_LI_7BITS;
rlcinf->ciphered[0] = FALSE;
rlcinf->deciphered[0] = FALSE;
p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf);
break;
case CHANNEL_RACH_FDD:
fpi->num_chans = p_conv_data->num_dch_in_flow;
if (is_control_frame) {
/* control frame, we're done */
return fpi;
}
/* Set offset to point to first TFI
* the Number of TFI's = number of DCH's in the flow
*/
offset = 2;
/* set MAC data */
macinf = wmem_new0(wmem_file_scope(), umts_mac_info);
rlcinf = wmem_new0(wmem_file_scope(), rlc_info);
for ( chan = 0; chan < fpi->num_chans; chan++ ) {
macinf->ctmux[chan] = 1;
macinf->content[chan] = MAC_CONTENT_DCCH;
rlcinf->urnti[chan] = fpi->com_context_id; /*Note that MAC probably will change this*/
}
p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf);
p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf);
break;
case CHANNEL_HSDSCH_COMMON:
rlcinf = wmem_new0(wmem_file_scope(), rlc_info);
macinf = wmem_new0(wmem_file_scope(), umts_mac_info);
p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf);
p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf);
break;
default:
expert_add_info(pinfo, NULL, &ei_fp_transport_channel_type_unknown);
return NULL;
}
/* Peek at the packet as the per packet info seems not to take the tfi into account */
for (i=0; i<fpi->num_chans; i++) {
tfi = tvb_get_guint8(tvb, offset);
/*TFI is 5 bits according to 3GPP TS 25.321, paragraph 6.2.4.4*/
/*tfi = tvb_get_bits8(tvb, offset*8, 5);*/
if (pinfo->link_dir == P2P_DIR_UL) {
fpi->chan_tf_size[i] = p_conv_data->fp_dch_channel_info[i].ul_chan_tf_size[tfi];
fpi->chan_num_tbs[i] = p_conv_data->fp_dch_channel_info[i].ul_chan_num_tbs[tfi];
} else {
fpi->chan_tf_size[i] = p_conv_data->fp_dch_channel_info[i].dl_chan_tf_size[tfi];
fpi->chan_num_tbs[i] = p_conv_data->fp_dch_channel_info[i].dl_chan_num_tbs[tfi];
}
offset++;
}
return fpi;
}
| 167,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: void WebGL2RenderingContextBase::texSubImage3D(
GLenum target,
GLint level,
GLint xoffset,
GLint yoffset,
GLint zoffset,
GLsizei width,
GLsizei height,
GLsizei depth,
GLenum format,
GLenum type,
MaybeShared<DOMArrayBufferView> pixels,
GLuint src_offset) {
if (isContextLost())
return;
if (bound_pixel_unpack_buffer_) {
SynthesizeGLError(GL_INVALID_OPERATION, "texSubImage3D",
"a buffer is bound to PIXEL_UNPACK_BUFFER");
return;
}
TexImageHelperDOMArrayBufferView(
kTexSubImage3D, target, level, 0, width, height, depth, 0, format, type,
xoffset, yoffset, zoffset, pixels.View(), kNullNotReachable, src_offset);
}
Commit Message: Implement 2D texture uploading from client array with FLIP_Y or PREMULTIPLY_ALPHA.
BUG=774174
TEST=https://github.com/KhronosGroup/WebGL/pull/2555
[email protected]
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2;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: I4f4e7636314502451104730501a5048a5d7b9f3f
Reviewed-on: https://chromium-review.googlesource.com/808665
Commit-Queue: Zhenyao Mo <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#522003}
CWE ID: CWE-125 | void WebGL2RenderingContextBase::texSubImage3D(
GLenum target,
GLint level,
GLint xoffset,
GLint yoffset,
GLint zoffset,
GLsizei width,
GLsizei height,
GLsizei depth,
GLenum format,
GLenum type,
MaybeShared<DOMArrayBufferView> pixels,
GLuint src_offset) {
if (isContextLost())
return;
if (bound_pixel_unpack_buffer_) {
SynthesizeGLError(GL_INVALID_OPERATION, "texSubImage3D",
"a buffer is bound to PIXEL_UNPACK_BUFFER");
return;
}
if (unpack_flip_y_ || unpack_premultiply_alpha_) {
DCHECK(pixels);
SynthesizeGLError(
GL_INVALID_OPERATION, "texSubImage3D",
"FLIP_Y or PREMULTIPLY_ALPHA isn't allowed for uploading 3D textures");
return;
}
TexImageHelperDOMArrayBufferView(
kTexSubImage3D, target, level, 0, width, height, depth, 0, format, type,
xoffset, yoffset, zoffset, pixels.View(), kNullNotReachable, src_offset);
}
| 172,679 |
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 build_l4proto_tcp(const struct nf_conntrack *ct, struct nethdr *n)
{
ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT,
sizeof(struct nfct_attr_grp_port));
if (!nfct_attr_is_set(ct, ATTR_TCP_STATE))
return;
ct_build_u8(ct, ATTR_TCP_STATE, n, NTA_TCP_STATE);
if (CONFIG(sync).tcp_window_tracking) {
ct_build_u8(ct, ATTR_TCP_WSCALE_ORIG, n, NTA_TCP_WSCALE_ORIG);
ct_build_u8(ct, ATTR_TCP_WSCALE_REPL, n, NTA_TCP_WSCALE_REPL);
}
}
Commit Message:
CWE ID: CWE-17 | static void build_l4proto_tcp(const struct nf_conntrack *ct, struct nethdr *n)
{
if (!nfct_attr_is_set(ct, ATTR_TCP_STATE))
return;
ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT,
sizeof(struct nfct_attr_grp_port));
ct_build_u8(ct, ATTR_TCP_STATE, n, NTA_TCP_STATE);
if (CONFIG(sync).tcp_window_tracking) {
ct_build_u8(ct, ATTR_TCP_WSCALE_ORIG, n, NTA_TCP_WSCALE_ORIG);
ct_build_u8(ct, ATTR_TCP_WSCALE_REPL, n, NTA_TCP_WSCALE_REPL);
}
}
| 164,632 |
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: Mat_VarReadNextInfo4(mat_t *mat)
{
int M,O,data_type,class_type;
mat_int32_t tmp;
long nBytes;
size_t readresult;
matvar_t *matvar = NULL;
union {
mat_uint32_t u;
mat_uint8_t c[4];
} endian;
if ( mat == NULL || mat->fp == NULL )
return NULL;
else if ( NULL == (matvar = Mat_VarCalloc()) )
return NULL;
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
endian.u = 0x01020304;
/* See if MOPT may need byteswapping */
if ( tmp < 0 || tmp > 4052 ) {
if ( Mat_int32Swap(&tmp) > 4052 ) {
Mat_VarFree(matvar);
return NULL;
}
}
M = (int)floor(tmp / 1000.0);
switch ( M ) {
case 0:
/* IEEE little endian */
mat->byteswap = endian.c[0] != 4;
break;
case 1:
/* IEEE big endian */
mat->byteswap = endian.c[0] != 1;
break;
default:
/* VAX, Cray, or bogus */
Mat_VarFree(matvar);
return NULL;
}
tmp -= M*1000;
O = (int)floor(tmp / 100.0);
/* O must be zero */
if ( 0 != O ) {
Mat_VarFree(matvar);
return NULL;
}
tmp -= O*100;
data_type = (int)floor(tmp / 10.0);
/* Convert the V4 data type */
switch ( data_type ) {
case 0:
matvar->data_type = MAT_T_DOUBLE;
break;
case 1:
matvar->data_type = MAT_T_SINGLE;
break;
case 2:
matvar->data_type = MAT_T_INT32;
break;
case 3:
matvar->data_type = MAT_T_INT16;
break;
case 4:
matvar->data_type = MAT_T_UINT16;
break;
case 5:
matvar->data_type = MAT_T_UINT8;
break;
default:
Mat_VarFree(matvar);
return NULL;
}
tmp -= data_type*10;
class_type = (int)floor(tmp / 1.0);
switch ( class_type ) {
case 0:
matvar->class_type = MAT_C_DOUBLE;
break;
case 1:
matvar->class_type = MAT_C_CHAR;
break;
case 2:
matvar->class_type = MAT_C_SPARSE;
break;
default:
Mat_VarFree(matvar);
return NULL;
}
matvar->rank = 2;
matvar->dims = (size_t*)calloc(2, sizeof(*matvar->dims));
if ( NULL == matvar->dims ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( mat->byteswap )
Mat_int32Swap(&tmp);
matvar->dims[0] = tmp;
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( mat->byteswap )
Mat_int32Swap(&tmp);
matvar->dims[1] = tmp;
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&(matvar->isComplex),sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
if ( matvar->isComplex && MAT_C_CHAR == matvar->class_type ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
if ( mat->byteswap )
Mat_int32Swap(&tmp);
/* Check that the length of the variable name is at least 1 */
if ( tmp < 1 ) {
Mat_VarFree(matvar);
return NULL;
}
matvar->name = (char*)malloc(tmp);
if ( NULL == matvar->name ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(matvar->name,1,tmp,(FILE*)mat->fp);
if ( tmp != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
matvar->internal->datapos = ftell((FILE*)mat->fp);
if ( matvar->internal->datapos == -1L ) {
Mat_VarFree(matvar);
Mat_Critical("Couldn't determine file position");
return NULL;
}
{
int err;
size_t tmp2 = Mat_SizeOf(matvar->data_type);
if ( matvar->isComplex )
tmp2 *= 2;
err = SafeMulDims(matvar, &tmp2);
if ( err ) {
Mat_VarFree(matvar);
Mat_Critical("Integer multiplication overflow");
return NULL;
}
nBytes = (long)tmp2;
}
(void)fseek((FILE*)mat->fp,nBytes,SEEK_CUR);
return matvar;
}
Commit Message: Avoid uninitialized memory
As reported by https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=16856
CWE ID: | Mat_VarReadNextInfo4(mat_t *mat)
{
int M,O,data_type,class_type;
mat_int32_t tmp;
long nBytes;
size_t readresult;
matvar_t *matvar = NULL;
union {
mat_uint32_t u;
mat_uint8_t c[4];
} endian;
if ( mat == NULL || mat->fp == NULL )
return NULL;
else if ( NULL == (matvar = Mat_VarCalloc()) )
return NULL;
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
endian.u = 0x01020304;
/* See if MOPT may need byteswapping */
if ( tmp < 0 || tmp > 4052 ) {
if ( Mat_int32Swap(&tmp) > 4052 ) {
Mat_VarFree(matvar);
return NULL;
}
}
M = (int)floor(tmp / 1000.0);
switch ( M ) {
case 0:
/* IEEE little endian */
mat->byteswap = endian.c[0] != 4;
break;
case 1:
/* IEEE big endian */
mat->byteswap = endian.c[0] != 1;
break;
default:
/* VAX, Cray, or bogus */
Mat_VarFree(matvar);
return NULL;
}
tmp -= M*1000;
O = (int)floor(tmp / 100.0);
/* O must be zero */
if ( 0 != O ) {
Mat_VarFree(matvar);
return NULL;
}
tmp -= O*100;
data_type = (int)floor(tmp / 10.0);
/* Convert the V4 data type */
switch ( data_type ) {
case 0:
matvar->data_type = MAT_T_DOUBLE;
break;
case 1:
matvar->data_type = MAT_T_SINGLE;
break;
case 2:
matvar->data_type = MAT_T_INT32;
break;
case 3:
matvar->data_type = MAT_T_INT16;
break;
case 4:
matvar->data_type = MAT_T_UINT16;
break;
case 5:
matvar->data_type = MAT_T_UINT8;
break;
default:
Mat_VarFree(matvar);
return NULL;
}
tmp -= data_type*10;
class_type = (int)floor(tmp / 1.0);
switch ( class_type ) {
case 0:
matvar->class_type = MAT_C_DOUBLE;
break;
case 1:
matvar->class_type = MAT_C_CHAR;
break;
case 2:
matvar->class_type = MAT_C_SPARSE;
break;
default:
Mat_VarFree(matvar);
return NULL;
}
matvar->rank = 2;
matvar->dims = (size_t*)calloc(2, sizeof(*matvar->dims));
if ( NULL == matvar->dims ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( mat->byteswap )
Mat_int32Swap(&tmp);
matvar->dims[0] = tmp;
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( mat->byteswap )
Mat_int32Swap(&tmp);
matvar->dims[1] = tmp;
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&(matvar->isComplex),sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
if ( matvar->isComplex && MAT_C_CHAR == matvar->class_type ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
if ( mat->byteswap )
Mat_int32Swap(&tmp);
/* Check that the length of the variable name is at least 1 */
if ( tmp < 1 ) {
Mat_VarFree(matvar);
return NULL;
}
matvar->name = (char*)malloc(tmp);
if ( NULL == matvar->name ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(matvar->name,1,tmp,(FILE*)mat->fp);
if ( tmp != readresult ) {
Mat_VarFree(matvar);
return NULL;
} else {
matvar->name[tmp - 1] = '\0';
}
matvar->internal->datapos = ftell((FILE*)mat->fp);
if ( matvar->internal->datapos == -1L ) {
Mat_VarFree(matvar);
Mat_Critical("Couldn't determine file position");
return NULL;
}
{
int err;
size_t tmp2 = Mat_SizeOf(matvar->data_type);
if ( matvar->isComplex )
tmp2 *= 2;
err = SafeMulDims(matvar, &tmp2);
if ( err ) {
Mat_VarFree(matvar);
Mat_Critical("Integer multiplication overflow");
return NULL;
}
nBytes = (long)tmp2;
}
(void)fseek((FILE*)mat->fp,nBytes,SEEK_CUR);
return matvar;
}
| 169,491 |
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 AutofillManager::OnLoadedAutofillHeuristics(
const std::string& heuristic_xml) {
UploadRequired upload_required;
FormStructure::ParseQueryResponse(heuristic_xml,
form_structures_.get(),
&upload_required,
*metric_logger_);
}
Commit Message: Add support for the "uploadrequired" attribute for Autofill query responses
BUG=84693
TEST=unit_tests --gtest_filter=AutofillDownloadTest.QueryAndUploadTest
Review URL: http://codereview.chromium.org/6969090
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87729 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void AutofillManager::OnLoadedAutofillHeuristics(
const std::string& heuristic_xml) {
FormStructure::ParseQueryResponse(heuristic_xml,
form_structures_.get(),
*metric_logger_);
}
| 170,447 |
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 free_user(struct kref *ref)
{
struct ipmi_user *user = container_of(ref, struct ipmi_user, refcount);
kfree(user);
}
Commit Message: ipmi: fix use-after-free of user->release_barrier.rda
When we do the following test, we got oops in ipmi_msghandler driver
while((1))
do
service ipmievd restart & service ipmievd restart
done
---------------------------------------------------------------
[ 294.230186] Unable to handle kernel paging request at virtual address 0000803fea6ea008
[ 294.230188] Mem abort info:
[ 294.230190] ESR = 0x96000004
[ 294.230191] Exception class = DABT (current EL), IL = 32 bits
[ 294.230193] SET = 0, FnV = 0
[ 294.230194] EA = 0, S1PTW = 0
[ 294.230195] Data abort info:
[ 294.230196] ISV = 0, ISS = 0x00000004
[ 294.230197] CM = 0, WnR = 0
[ 294.230199] user pgtable: 4k pages, 48-bit VAs, pgdp = 00000000a1c1b75a
[ 294.230201] [0000803fea6ea008] pgd=0000000000000000
[ 294.230204] Internal error: Oops: 96000004 [#1] SMP
[ 294.235211] Modules linked in: 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 iw_cm dm_mirror dm_region_hash dm_log dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ghash_ce sha2_ce ses sha256_arm64 sha1_ce hibmc_drm hisi_sas_v2_hw enclosure sg hisi_sas_main sbsa_gwdt ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe ipmi_si mdio hns_dsaf ipmi_devintf ipmi_msghandler hns_enet_drv hns_mdio
[ 294.277745] CPU: 3 PID: 0 Comm: swapper/3 Kdump: loaded Not tainted 5.0.0-rc2+ #113
[ 294.285511] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017
[ 294.292835] pstate: 80000005 (Nzcv daif -PAN -UAO)
[ 294.297695] pc : __srcu_read_lock+0x38/0x58
[ 294.301940] lr : acquire_ipmi_user+0x2c/0x70 [ipmi_msghandler]
[ 294.307853] sp : ffff00001001bc80
[ 294.311208] x29: ffff00001001bc80 x28: ffff0000117e5000
[ 294.316594] x27: 0000000000000000 x26: dead000000000100
[ 294.321980] x25: dead000000000200 x24: ffff803f6bd06800
[ 294.327366] x23: 0000000000000000 x22: 0000000000000000
[ 294.332752] x21: ffff00001001bd04 x20: ffff80df33d19018
[ 294.338137] x19: ffff80df33d19018 x18: 0000000000000000
[ 294.343523] x17: 0000000000000000 x16: 0000000000000000
[ 294.348908] x15: 0000000000000000 x14: 0000000000000002
[ 294.354293] x13: 0000000000000000 x12: 0000000000000000
[ 294.359679] x11: 0000000000000000 x10: 0000000000100000
[ 294.365065] x9 : 0000000000000000 x8 : 0000000000000004
[ 294.370451] x7 : 0000000000000000 x6 : ffff80df34558678
[ 294.375836] x5 : 000000000000000c x4 : 0000000000000000
[ 294.381221] x3 : 0000000000000001 x2 : 0000803fea6ea000
[ 294.386607] x1 : 0000803fea6ea008 x0 : 0000000000000001
[ 294.391994] Process swapper/3 (pid: 0, stack limit = 0x0000000083087293)
[ 294.398791] Call trace:
[ 294.401266] __srcu_read_lock+0x38/0x58
[ 294.405154] acquire_ipmi_user+0x2c/0x70 [ipmi_msghandler]
[ 294.410716] deliver_response+0x80/0xf8 [ipmi_msghandler]
[ 294.416189] deliver_local_response+0x28/0x68 [ipmi_msghandler]
[ 294.422193] handle_one_recv_msg+0x158/0xcf8 [ipmi_msghandler]
[ 294.432050] handle_new_recv_msgs+0xc0/0x210 [ipmi_msghandler]
[ 294.441984] smi_recv_tasklet+0x8c/0x158 [ipmi_msghandler]
[ 294.451618] tasklet_action_common.isra.5+0x88/0x138
[ 294.460661] tasklet_action+0x2c/0x38
[ 294.468191] __do_softirq+0x120/0x2f8
[ 294.475561] irq_exit+0x134/0x140
[ 294.482445] __handle_domain_irq+0x6c/0xc0
[ 294.489954] gic_handle_irq+0xb8/0x178
[ 294.497037] el1_irq+0xb0/0x140
[ 294.503381] arch_cpu_idle+0x34/0x1a8
[ 294.510096] do_idle+0x1d4/0x290
[ 294.516322] cpu_startup_entry+0x28/0x30
[ 294.523230] secondary_start_kernel+0x184/0x1d0
[ 294.530657] Code: d538d082 d2800023 8b010c81 8b020021 (c85f7c25)
[ 294.539746] ---[ end trace 8a7a880dee570b29 ]---
[ 294.547341] Kernel panic - not syncing: Fatal exception in interrupt
[ 294.556837] SMP: stopping secondary CPUs
[ 294.563996] Kernel Offset: disabled
[ 294.570515] CPU features: 0x002,21006008
[ 294.577638] Memory Limit: none
[ 294.587178] Starting crashdump kernel...
[ 294.594314] Bye!
Because the user->release_barrier.rda is freed in ipmi_destroy_user(), but
the refcount is not zero, when acquire_ipmi_user() uses user->release_barrier.rda
in __srcu_read_lock(), it causes oops.
Fix this by calling cleanup_srcu_struct() when the refcount is zero.
Fixes: e86ee2d44b44 ("ipmi: Rework locking and shutdown for hot remove")
Cc: [email protected] # 4.18
Signed-off-by: Yang Yingliang <[email protected]>
Signed-off-by: Corey Minyard <[email protected]>
CWE ID: CWE-416 | static void free_user(struct kref *ref)
{
struct ipmi_user *user = container_of(ref, struct ipmi_user, refcount);
cleanup_srcu_struct(&user->release_barrier);
kfree(user);
}
| 169,725 |
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 ChromeDownloadDelegate::RequestHTTPGetDownload(
const std::string& url,
const std::string& user_agent,
const std::string& content_disposition,
const std::string& mime_type,
const std::string& cookie,
const std::string& referer,
const base::string16& file_name,
int64_t content_length,
bool has_user_gesture,
bool must_download) {
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jstring> jurl =
ConvertUTF8ToJavaString(env, url);
ScopedJavaLocalRef<jstring> juser_agent =
ConvertUTF8ToJavaString(env, user_agent);
ScopedJavaLocalRef<jstring> jcontent_disposition =
ConvertUTF8ToJavaString(env, content_disposition);
ScopedJavaLocalRef<jstring> jmime_type =
ConvertUTF8ToJavaString(env, mime_type);
ScopedJavaLocalRef<jstring> jcookie =
ConvertUTF8ToJavaString(env, cookie);
ScopedJavaLocalRef<jstring> jreferer =
ConvertUTF8ToJavaString(env, referer);
ScopedJavaLocalRef<jstring> jfilename =
base::android::ConvertUTF16ToJavaString(env, file_name);
Java_ChromeDownloadDelegate_requestHttpGetDownload(
env, java_ref_, jurl, juser_agent, jcontent_disposition, jmime_type,
jcookie, jreferer, has_user_gesture, jfilename, content_length,
must_download);
}
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 ChromeDownloadDelegate::RequestHTTPGetDownload(
| 171,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: PHP_FUNCTION(locale_filter_matches)
{
char* lang_tag = NULL;
int lang_tag_len = 0;
const char* loc_range = NULL;
int loc_range_len = 0;
int result = 0;
char* token = 0;
char* chrcheck = NULL;
char* can_lang_tag = NULL;
char* can_loc_range = NULL;
char* cur_lang_tag = NULL;
char* cur_loc_range = NULL;
zend_bool boolCanonical = 0;
UErrorCode status = U_ZERO_ERROR;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "ss|b",
&lang_tag, &lang_tag_len , &loc_range , &loc_range_len ,
&boolCanonical) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_filter_matches: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
if(loc_range_len == 0) {
loc_range = intl_locale_get_default(TSRMLS_C);
}
if( strcmp(loc_range,"*")==0){
RETURN_TRUE;
}
if( boolCanonical ){
/* canonicalize loc_range */
can_loc_range=get_icu_value_internal( loc_range , LOC_CANONICALIZE_TAG , &result , 0);
if( result ==0) {
intl_error_set( NULL, status,
"locale_filter_matches : unable to canonicalize loc_range" , 0 TSRMLS_CC );
RETURN_FALSE;
}
/* canonicalize lang_tag */
can_lang_tag = get_icu_value_internal( lang_tag , LOC_CANONICALIZE_TAG , &result , 0);
if( result ==0) {
intl_error_set( NULL, status,
"locale_filter_matches : unable to canonicalize lang_tag" , 0 TSRMLS_CC );
RETURN_FALSE;
}
/* Convert to lower case for case-insensitive comparison */
cur_lang_tag = ecalloc( 1, strlen(can_lang_tag) + 1);
/* Convert to lower case for case-insensitive comparison */
result = strToMatch( can_lang_tag , cur_lang_tag);
if( result == 0) {
efree( cur_lang_tag );
efree( can_lang_tag );
RETURN_FALSE;
}
cur_loc_range = ecalloc( 1, strlen(can_loc_range) + 1);
result = strToMatch( can_loc_range , cur_loc_range );
if( result == 0) {
efree( cur_lang_tag );
efree( can_lang_tag );
efree( cur_loc_range );
efree( can_loc_range );
RETURN_FALSE;
}
/* check if prefix */
token = strstr( cur_lang_tag , cur_loc_range );
if( token && (token==cur_lang_tag) ){
/* check if the char. after match is SEPARATOR */
chrcheck = token + (strlen(cur_loc_range));
if( isIDSeparator(*chrcheck) || isEndOfTag(*chrcheck) ){
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
if( can_lang_tag){
efree( can_lang_tag );
}
if( can_loc_range){
efree( can_loc_range );
}
RETURN_TRUE;
}
}
/* No prefix as loc_range */
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
if( can_lang_tag){
efree( can_lang_tag );
}
if( can_loc_range){
efree( can_loc_range );
}
RETURN_FALSE;
} /* end of if isCanonical */
else{
/* Convert to lower case for case-insensitive comparison */
cur_lang_tag = ecalloc( 1, strlen(lang_tag ) + 1);
result = strToMatch( lang_tag , cur_lang_tag);
if( result == 0) {
efree( cur_lang_tag );
RETURN_FALSE;
}
cur_loc_range = ecalloc( 1, strlen(loc_range ) + 1);
result = strToMatch( loc_range , cur_loc_range );
if( result == 0) {
efree( cur_lang_tag );
efree( cur_loc_range );
RETURN_FALSE;
}
/* check if prefix */
token = strstr( cur_lang_tag , cur_loc_range );
if( token && (token==cur_lang_tag) ){
/* check if the char. after match is SEPARATOR */
chrcheck = token + (strlen(cur_loc_range));
if( isIDSeparator(*chrcheck) || isEndOfTag(*chrcheck) ){
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
RETURN_TRUE;
}
}
/* No prefix as loc_range */
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
RETURN_FALSE;
}
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | PHP_FUNCTION(locale_filter_matches)
{
char* lang_tag = NULL;
int lang_tag_len = 0;
const char* loc_range = NULL;
int loc_range_len = 0;
int result = 0;
char* token = 0;
char* chrcheck = NULL;
char* can_lang_tag = NULL;
char* can_loc_range = NULL;
char* cur_lang_tag = NULL;
char* cur_loc_range = NULL;
zend_bool boolCanonical = 0;
UErrorCode status = U_ZERO_ERROR;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "ss|b",
&lang_tag, &lang_tag_len , &loc_range , &loc_range_len ,
&boolCanonical) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_filter_matches: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
if(loc_range_len == 0) {
loc_range = intl_locale_get_default(TSRMLS_C);
}
if( strcmp(loc_range,"*")==0){
RETURN_TRUE;
}
if( boolCanonical ){
/* canonicalize loc_range */
can_loc_range=get_icu_value_internal( loc_range , LOC_CANONICALIZE_TAG , &result , 0);
if( result ==0) {
intl_error_set( NULL, status,
"locale_filter_matches : unable to canonicalize loc_range" , 0 TSRMLS_CC );
RETURN_FALSE;
}
/* canonicalize lang_tag */
can_lang_tag = get_icu_value_internal( lang_tag , LOC_CANONICALIZE_TAG , &result , 0);
if( result ==0) {
intl_error_set( NULL, status,
"locale_filter_matches : unable to canonicalize lang_tag" , 0 TSRMLS_CC );
RETURN_FALSE;
}
/* Convert to lower case for case-insensitive comparison */
cur_lang_tag = ecalloc( 1, strlen(can_lang_tag) + 1);
/* Convert to lower case for case-insensitive comparison */
result = strToMatch( can_lang_tag , cur_lang_tag);
if( result == 0) {
efree( cur_lang_tag );
efree( can_lang_tag );
RETURN_FALSE;
}
cur_loc_range = ecalloc( 1, strlen(can_loc_range) + 1);
result = strToMatch( can_loc_range , cur_loc_range );
if( result == 0) {
efree( cur_lang_tag );
efree( can_lang_tag );
efree( cur_loc_range );
efree( can_loc_range );
RETURN_FALSE;
}
/* check if prefix */
token = strstr( cur_lang_tag , cur_loc_range );
if( token && (token==cur_lang_tag) ){
/* check if the char. after match is SEPARATOR */
chrcheck = token + (strlen(cur_loc_range));
if( isIDSeparator(*chrcheck) || isEndOfTag(*chrcheck) ){
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
if( can_lang_tag){
efree( can_lang_tag );
}
if( can_loc_range){
efree( can_loc_range );
}
RETURN_TRUE;
}
}
/* No prefix as loc_range */
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
if( can_lang_tag){
efree( can_lang_tag );
}
if( can_loc_range){
efree( can_loc_range );
}
RETURN_FALSE;
} /* end of if isCanonical */
else{
/* Convert to lower case for case-insensitive comparison */
cur_lang_tag = ecalloc( 1, strlen(lang_tag ) + 1);
result = strToMatch( lang_tag , cur_lang_tag);
if( result == 0) {
efree( cur_lang_tag );
RETURN_FALSE;
}
cur_loc_range = ecalloc( 1, strlen(loc_range ) + 1);
result = strToMatch( loc_range , cur_loc_range );
if( result == 0) {
efree( cur_lang_tag );
efree( cur_loc_range );
RETURN_FALSE;
}
/* check if prefix */
token = strstr( cur_lang_tag , cur_loc_range );
if( token && (token==cur_lang_tag) ){
/* check if the char. after match is SEPARATOR */
chrcheck = token + (strlen(cur_loc_range));
if( isIDSeparator(*chrcheck) || isEndOfTag(*chrcheck) ){
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
RETURN_TRUE;
}
}
/* No prefix as loc_range */
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
RETURN_FALSE;
}
}
| 167,193 |
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 Erase(const std::string& addr) {
base::AutoLock lock(lock_);
map_.erase(addr);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void Erase(const std::string& addr) {
// Erases the entry for |preview_id|.
void Erase(int32 preview_id) {
base::AutoLock lock(lock_);
map_.erase(preview_id);
}
| 170,830 |
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 perf_event_enable(struct perf_event *event)
{
struct perf_event_context *ctx = event->ctx;
struct task_struct *task = ctx->task;
if (!task) {
/*
* Enable the event on the cpu that it's on
*/
cpu_function_call(event->cpu, __perf_event_enable, event);
return;
}
raw_spin_lock_irq(&ctx->lock);
if (event->state >= PERF_EVENT_STATE_INACTIVE)
goto out;
/*
* If the event is in error state, clear that first.
* That way, if we see the event in error state below, we
* know that it has gone back into error state, as distinct
* from the task having been scheduled away before the
* cross-call arrived.
*/
if (event->state == PERF_EVENT_STATE_ERROR)
event->state = PERF_EVENT_STATE_OFF;
retry:
if (!ctx->is_active) {
__perf_event_mark_enabled(event);
goto out;
}
raw_spin_unlock_irq(&ctx->lock);
if (!task_function_call(task, __perf_event_enable, event))
return;
raw_spin_lock_irq(&ctx->lock);
/*
* If the context is active and the event is still off,
* we need to retry the cross-call.
*/
if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
/*
* task could have been flipped by a concurrent
* perf_event_context_sched_out()
*/
task = ctx->task;
goto retry;
}
out:
raw_spin_unlock_irq(&ctx->lock);
}
Commit Message: perf: Fix event->ctx locking
There have been a few reported issues wrt. the lack of locking around
changing event->ctx. This patch tries to address those.
It avoids the whole rwsem thing; and while it appears to work, please
give it some thought in review.
What I did fail at is sensible runtime checks on the use of
event->ctx, the RCU use makes it very hard.
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Paul E. McKenney <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Linus Torvalds <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-264 | void perf_event_enable(struct perf_event *event)
static void _perf_event_enable(struct perf_event *event)
{
struct perf_event_context *ctx = event->ctx;
struct task_struct *task = ctx->task;
if (!task) {
/*
* Enable the event on the cpu that it's on
*/
cpu_function_call(event->cpu, __perf_event_enable, event);
return;
}
raw_spin_lock_irq(&ctx->lock);
if (event->state >= PERF_EVENT_STATE_INACTIVE)
goto out;
/*
* If the event is in error state, clear that first.
* That way, if we see the event in error state below, we
* know that it has gone back into error state, as distinct
* from the task having been scheduled away before the
* cross-call arrived.
*/
if (event->state == PERF_EVENT_STATE_ERROR)
event->state = PERF_EVENT_STATE_OFF;
retry:
if (!ctx->is_active) {
__perf_event_mark_enabled(event);
goto out;
}
raw_spin_unlock_irq(&ctx->lock);
if (!task_function_call(task, __perf_event_enable, event))
return;
raw_spin_lock_irq(&ctx->lock);
/*
* If the context is active and the event is still off,
* we need to retry the cross-call.
*/
if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
/*
* task could have been flipped by a concurrent
* perf_event_context_sched_out()
*/
task = ctx->task;
goto retry;
}
out:
raw_spin_unlock_irq(&ctx->lock);
}
| 166,983 |
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 FILE *open_log_file(void)
{
if(log_fp) /* keep it open unless we rotate */
return log_fp;
log_fp = fopen(log_file, "a+");
if(log_fp == NULL) {
if (daemon_mode == FALSE) {
printf("Warning: Cannot open log file '%s' for writing\n", log_file);
}
return NULL;
}
(void)fcntl(fileno(log_fp), F_SETFD, FD_CLOEXEC);
return log_fp;
}
Commit Message: Merge branch 'maint'
CWE ID: CWE-264 | static FILE *open_log_file(void)
{
int fh;
struct stat st;
if(log_fp) /* keep it open unless we rotate */
return log_fp;
if ((fh = open(log_file, O_RDWR|O_APPEND|O_CREAT|O_NOFOLLOW, S_IRUSR|S_IWUSR)) == -1) {
if (daemon_mode == FALSE)
printf("Warning: Cannot open log file '%s' for writing\n", log_file);
return NULL;
}
log_fp = fdopen(fh, "a+");
if(log_fp == NULL) {
if (daemon_mode == FALSE)
printf("Warning: Cannot open log file '%s' for writing\n", log_file);
return NULL;
}
if ((fstat(fh, &st)) == -1) {
log_fp = NULL;
close(fh);
if (daemon_mode == FALSE)
printf("Warning: Cannot fstat log file '%s'\n", log_file);
return NULL;
}
if (st.st_nlink != 1 || (st.st_mode & S_IFMT) != S_IFREG) {
log_fp = NULL;
close(fh);
if (daemon_mode == FALSE)
printf("Warning: log file '%s' has an invalid mode\n", log_file);
return NULL;
}
(void)fcntl(fileno(log_fp), F_SETFD, FD_CLOEXEC);
return log_fp;
}
| 166,860 |
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: PageHandler::PageHandler(EmulationHandler* emulation_handler)
: DevToolsDomainHandler(Page::Metainfo::domainName),
enabled_(false),
screencast_enabled_(false),
screencast_quality_(kDefaultScreenshotQuality),
screencast_max_width_(-1),
screencast_max_height_(-1),
capture_every_nth_frame_(1),
capture_retry_count_(0),
has_compositor_frame_metadata_(false),
session_id_(0),
frame_counter_(0),
frames_in_flight_(0),
video_consumer_(nullptr),
last_surface_size_(gfx::Size()),
host_(nullptr),
emulation_handler_(emulation_handler),
observer_(this),
weak_factory_(this) {
bool create_video_consumer = true;
#ifdef OS_ANDROID
if (!CompositorImpl::IsInitialized())
create_video_consumer = false;
#endif
if (create_video_consumer) {
video_consumer_ = std::make_unique<DevToolsVideoConsumer>(
base::BindRepeating(&PageHandler::OnFrameFromVideoConsumer,
weak_factory_.GetWeakPtr()));
}
DCHECK(emulation_handler_);
}
Commit Message: [DevTools] Do not allow Page.setDownloadBehavior for extensions
Bug: 866426
Change-Id: I71b672978e1a8ec779ede49da16b21198567d3a4
Reviewed-on: https://chromium-review.googlesource.com/c/1270007
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598004}
CWE ID: CWE-20 | PageHandler::PageHandler(EmulationHandler* emulation_handler)
PageHandler::PageHandler(EmulationHandler* emulation_handler,
bool allow_set_download_behavior)
: DevToolsDomainHandler(Page::Metainfo::domainName),
enabled_(false),
screencast_enabled_(false),
screencast_quality_(kDefaultScreenshotQuality),
screencast_max_width_(-1),
screencast_max_height_(-1),
capture_every_nth_frame_(1),
capture_retry_count_(0),
has_compositor_frame_metadata_(false),
session_id_(0),
frame_counter_(0),
frames_in_flight_(0),
video_consumer_(nullptr),
last_surface_size_(gfx::Size()),
host_(nullptr),
emulation_handler_(emulation_handler),
allow_set_download_behavior_(allow_set_download_behavior),
observer_(this),
weak_factory_(this) {
bool create_video_consumer = true;
#ifdef OS_ANDROID
if (!CompositorImpl::IsInitialized())
create_video_consumer = false;
#endif
if (create_video_consumer) {
video_consumer_ = std::make_unique<DevToolsVideoConsumer>(
base::BindRepeating(&PageHandler::OnFrameFromVideoConsumer,
weak_factory_.GetWeakPtr()));
}
DCHECK(emulation_handler_);
}
| 172,607 |
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_libxml_resolveEntity(void* user_data,
const xmlChar *publicId, const xmlChar *systemId) {
raptor_sax2* sax2 = (raptor_sax2*)user_data;
return libxml2_resolveEntity(sax2->xc, publicId, systemId);
}
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_libxml_resolveEntity(void* user_data,
const xmlChar *publicId, const xmlChar *systemId)
{
raptor_sax2* sax2 = (raptor_sax2*)user_data;
xmlParserCtxtPtr ctxt = sax2->xc;
const unsigned char *uri_string = NULL;
xmlParserInputPtr entity_input;
int load_entity = 0;
if(ctxt->input)
uri_string = RAPTOR_GOOD_CAST(const unsigned char *, ctxt->input->filename);
if(!uri_string)
uri_string = RAPTOR_GOOD_CAST(const unsigned char *, ctxt->directory);
load_entity = RAPTOR_OPTIONS_GET_NUMERIC(sax2, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES);
if(load_entity)
load_entity = raptor_sax2_check_load_uri_string(sax2, uri_string);
if(load_entity) {
entity_input = xmlLoadExternalEntity(RAPTOR_GOOD_CAST(const char*, uri_string),
RAPTOR_GOOD_CAST(const char*, publicId),
ctxt);
} else {
RAPTOR_DEBUG4("Not loading entity URI %s by policy for publicId '%s' systemId '%s'\n", uri_string, publicId, systemId);
}
return entity_input;
}
| 165,659 |
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: htc_request_check_host_hdr(struct http *hp)
{
int u;
int seen_host = 0;
for (u = HTTP_HDR_FIRST; u < hp->nhd; u++) {
if (hp->hd[u].b == NULL)
continue;
AN(hp->hd[u].b);
AN(hp->hd[u].e);
if (http_IsHdr(&hp->hd[u], H_Host)) {
if (seen_host) {
return (400);
}
seen_host = 1;
}
}
return (0);
}
Commit Message: Check for duplicate Content-Length headers in requests
If a duplicate CL header is in the request, we fail the request with a
400 (Bad Request)
Fix a test case that was sending duplicate CL by misstake and would
not fail because of that.
CWE ID: | htc_request_check_host_hdr(struct http *hp)
htc_request_check_hdrs(struct sess *sp, struct http *hp)
{
int u;
int seen_host = 0;
int seen_cl = 0;
for (u = HTTP_HDR_FIRST; u < hp->nhd; u++) {
if (hp->hd[u].b == NULL)
continue;
AN(hp->hd[u].b);
AN(hp->hd[u].e);
if (http_IsHdr(&hp->hd[u], H_Host)) {
if (seen_host) {
WSP(sp, SLT_Error, "Duplicated Host header");
return (400);
}
seen_host = 1;
}
if (http_IsHdr(&hp->hd[u], H_Content_Length)) {
if (seen_cl) {
WSP(sp, SLT_Error,
"Duplicated Content-Length header");
return (400);
}
seen_cl = 1;
}
}
return (0);
}
| 167,478 |
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 MockRenderThread::OnMessageReceived(const IPC::Message& msg) {
sink_.OnMessageReceived(msg);
bool handled = true;
bool msg_is_ok = true;
IPC_BEGIN_MESSAGE_MAP_EX(MockRenderThread, msg, msg_is_ok)
IPC_MESSAGE_HANDLER(ViewHostMsg_CreateWidget, OnMsgCreateWidget)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP_EX()
return handled;
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | bool MockRenderThread::OnMessageReceived(const IPC::Message& msg) {
sink_.OnMessageReceived(msg);
bool handled = true;
bool msg_is_ok = true;
IPC_BEGIN_MESSAGE_MAP_EX(MockRenderThread, msg, msg_is_ok)
IPC_MESSAGE_HANDLER(ViewHostMsg_CreateWidget, OnMsgCreateWidget)
IPC_MESSAGE_HANDLER(ViewHostMsg_CreateWindow, OnMsgCreateWindow)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP_EX()
return handled;
}
| 171,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: const Block::Frame& Block::GetFrame(int idx) const
{
assert(idx >= 0);
assert(idx < m_frame_count);
const Frame& f = m_frames[idx];
assert(f.pos > 0);
assert(f.len > 0);
return f;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const Block::Frame& Block::GetFrame(int idx) const
| 174,324 |
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 wasm_dis(WasmOp *op, const unsigned char *buf, int buf_len) {
op->len = 1;
op->op = buf[0];
if (op->op > 0xbf) return 1;
WasmOpDef *opdef = &opcodes[op->op];
switch (op->op) {
case WASM_OP_TRAP:
case WASM_OP_NOP:
case WASM_OP_ELSE:
case WASM_OP_RETURN:
case WASM_OP_DROP:
case WASM_OP_SELECT:
case WASM_OP_I32EQZ:
case WASM_OP_I32EQ:
case WASM_OP_I32NE:
case WASM_OP_I32LTS:
case WASM_OP_I32LTU:
case WASM_OP_I32GTS:
case WASM_OP_I32GTU:
case WASM_OP_I32LES:
case WASM_OP_I32LEU:
case WASM_OP_I32GES:
case WASM_OP_I32GEU:
case WASM_OP_I64EQZ:
case WASM_OP_I64EQ:
case WASM_OP_I64NE:
case WASM_OP_I64LTS:
case WASM_OP_I64LTU:
case WASM_OP_I64GTS:
case WASM_OP_I64GTU:
case WASM_OP_I64LES:
case WASM_OP_I64LEU:
case WASM_OP_I64GES:
case WASM_OP_I64GEU:
case WASM_OP_F32EQ:
case WASM_OP_F32NE:
case WASM_OP_F32LT:
case WASM_OP_F32GT:
case WASM_OP_F32LE:
case WASM_OP_F32GE:
case WASM_OP_F64EQ:
case WASM_OP_F64NE:
case WASM_OP_F64LT:
case WASM_OP_F64GT:
case WASM_OP_F64LE:
case WASM_OP_F64GE:
case WASM_OP_I32CLZ:
case WASM_OP_I32CTZ:
case WASM_OP_I32POPCNT:
case WASM_OP_I32ADD:
case WASM_OP_I32SUB:
case WASM_OP_I32MUL:
case WASM_OP_I32DIVS:
case WASM_OP_I32DIVU:
case WASM_OP_I32REMS:
case WASM_OP_I32REMU:
case WASM_OP_I32AND:
case WASM_OP_I32OR:
case WASM_OP_I32XOR:
case WASM_OP_I32SHL:
case WASM_OP_I32SHRS:
case WASM_OP_I32SHRU:
case WASM_OP_I32ROTL:
case WASM_OP_I32ROTR:
case WASM_OP_I64CLZ:
case WASM_OP_I64CTZ:
case WASM_OP_I64POPCNT:
case WASM_OP_I64ADD:
case WASM_OP_I64SUB:
case WASM_OP_I64MUL:
case WASM_OP_I64DIVS:
case WASM_OP_I64DIVU:
case WASM_OP_I64REMS:
case WASM_OP_I64REMU:
case WASM_OP_I64AND:
case WASM_OP_I64OR:
case WASM_OP_I64XOR:
case WASM_OP_I64SHL:
case WASM_OP_I64SHRS:
case WASM_OP_I64SHRU:
case WASM_OP_I64ROTL:
case WASM_OP_I64ROTR:
case WASM_OP_F32ABS:
case WASM_OP_F32NEG:
case WASM_OP_F32CEIL:
case WASM_OP_F32FLOOR:
case WASM_OP_F32TRUNC:
case WASM_OP_F32NEAREST:
case WASM_OP_F32SQRT:
case WASM_OP_F32ADD:
case WASM_OP_F32SUB:
case WASM_OP_F32MUL:
case WASM_OP_F32DIV:
case WASM_OP_F32MIN:
case WASM_OP_F32MAX:
case WASM_OP_F32COPYSIGN:
case WASM_OP_F64ABS:
case WASM_OP_F64NEG:
case WASM_OP_F64CEIL:
case WASM_OP_F64FLOOR:
case WASM_OP_F64TRUNC:
case WASM_OP_F64NEAREST:
case WASM_OP_F64SQRT:
case WASM_OP_F64ADD:
case WASM_OP_F64SUB:
case WASM_OP_F64MUL:
case WASM_OP_F64DIV:
case WASM_OP_F64MIN:
case WASM_OP_F64MAX:
case WASM_OP_F64COPYSIGN:
case WASM_OP_I32WRAPI64:
case WASM_OP_I32TRUNCSF32:
case WASM_OP_I32TRUNCUF32:
case WASM_OP_I32TRUNCSF64:
case WASM_OP_I32TRUNCUF64:
case WASM_OP_I64EXTENDSI32:
case WASM_OP_I64EXTENDUI32:
case WASM_OP_I64TRUNCSF32:
case WASM_OP_I64TRUNCUF32:
case WASM_OP_I64TRUNCSF64:
case WASM_OP_I64TRUNCUF64:
case WASM_OP_F32CONVERTSI32:
case WASM_OP_F32CONVERTUI32:
case WASM_OP_F32CONVERTSI64:
case WASM_OP_F32CONVERTUI64:
case WASM_OP_F32DEMOTEF64:
case WASM_OP_F64CONVERTSI32:
case WASM_OP_F64CONVERTUI32:
case WASM_OP_F64CONVERTSI64:
case WASM_OP_F64CONVERTUI64:
case WASM_OP_F64PROMOTEF32:
case WASM_OP_I32REINTERPRETF32:
case WASM_OP_I64REINTERPRETF64:
case WASM_OP_F32REINTERPRETI32:
case WASM_OP_F64REINTERPRETI64:
case WASM_OP_END:
{
snprintf (op->txt, R_ASM_BUFSIZE, "%s", opdef->txt);
}
break;
case WASM_OP_BLOCK:
case WASM_OP_LOOP:
case WASM_OP_IF:
{
st32 val = 0;
size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
switch (0x80 - val) {
case R_BIN_WASM_VALUETYPE_EMPTY:
snprintf (op->txt, R_ASM_BUFSIZE, "%s", opdef->txt);
break;
case R_BIN_WASM_VALUETYPE_i32:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result i32)", opdef->txt);
break;
case R_BIN_WASM_VALUETYPE_i64:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result i64)", opdef->txt);
break;
case R_BIN_WASM_VALUETYPE_f32:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result f32)", opdef->txt);
break;
case R_BIN_WASM_VALUETYPE_f64:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result f64)", opdef->txt);
break;
default:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result ?)", opdef->txt);
break;
}
op->len += n;
}
break;
case WASM_OP_BR:
case WASM_OP_BRIF:
case WASM_OP_CALL:
{
ut32 val = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, val);
op->len += n;
}
break;
case WASM_OP_BRTABLE:
{
ut32 count = 0, *table = NULL, def = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &count);
if (!(n > 0 && n < buf_len)) goto err;
if (!(table = calloc (count, sizeof (ut32)))) goto err;
int i = 0;
op->len += n;
for (i = 0; i < count; i++) {
n = read_u32_leb128 (buf + op->len, buf + buf_len, &table[i]);
if (!(op->len + n <= buf_len)) goto beach;
op->len += n;
}
n = read_u32_leb128 (buf + op->len, buf + buf_len, &def);
if (!(n > 0 && n + op->len < buf_len)) goto beach;
op->len += n;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d ", opdef->txt, count);
for (i = 0; i < count && strlen (op->txt) < R_ASM_BUFSIZE; i++) {
snprintf (op->txt + strlen (op->txt), R_ASM_BUFSIZE, "%d ", table[i]);
}
snprintf (op->txt + strlen (op->txt), R_ASM_BUFSIZE, "%d", def);
free (table);
break;
beach:
free (table);
goto err;
}
break;
case WASM_OP_CALLINDIRECT:
{
ut32 val = 0, reserved = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
op->len += n;
n = read_u32_leb128 (buf + op->len, buf + buf_len, &reserved);
if (!(n == 1 && op->len + n <= buf_len)) goto err;
reserved &= 0x1;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d %d", opdef->txt, val, reserved);
op->len += n;
}
break;
case WASM_OP_GETLOCAL:
case WASM_OP_SETLOCAL:
case WASM_OP_TEELOCAL:
case WASM_OP_GETGLOBAL:
case WASM_OP_SETGLOBAL:
{
ut32 val = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, val);
op->len += n;
}
break;
case WASM_OP_I32LOAD:
case WASM_OP_I64LOAD:
case WASM_OP_F32LOAD:
case WASM_OP_F64LOAD:
case WASM_OP_I32LOAD8S:
case WASM_OP_I32LOAD8U:
case WASM_OP_I32LOAD16S:
case WASM_OP_I32LOAD16U:
case WASM_OP_I64LOAD8S:
case WASM_OP_I64LOAD8U:
case WASM_OP_I64LOAD16S:
case WASM_OP_I64LOAD16U:
case WASM_OP_I64LOAD32S:
case WASM_OP_I64LOAD32U:
case WASM_OP_I32STORE:
case WASM_OP_I64STORE:
case WASM_OP_F32STORE:
case WASM_OP_F64STORE:
case WASM_OP_I32STORE8:
case WASM_OP_I32STORE16:
case WASM_OP_I64STORE8:
case WASM_OP_I64STORE16:
case WASM_OP_I64STORE32:
{
ut32 flag = 0, offset = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &flag);
if (!(n > 0 && n < buf_len)) goto err;
op->len += n;
n = read_u32_leb128 (buf + op->len, buf + buf_len, &offset);
if (!(n > 0 && op->len + n <= buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d %d", opdef->txt, flag, offset);
op->len += n;
}
break;
case WASM_OP_CURRENTMEMORY:
case WASM_OP_GROWMEMORY:
{
ut32 reserved = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &reserved);
if (!(n == 1 && n < buf_len)) goto err;
reserved &= 0x1;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, reserved);
op->len += n;
}
break;
case WASM_OP_I32CONST:
{
st32 val = 0;
size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %" PFMT32d, opdef->txt, val);
op->len += n;
}
break;
case WASM_OP_I64CONST:
{
st64 val = 0;
size_t n = read_i64_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %" PFMT64d, opdef->txt, val);
op->len += n;
}
break;
case WASM_OP_F32CONST:
{
ut32 val = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
long double d = (long double)val;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %" LDBLFMT, opdef->txt, d);
op->len += n;
}
break;
case WASM_OP_F64CONST:
{
ut64 val = 0;
size_t n = read_u64_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
long double d = (long double)val;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %" LDBLFMT, opdef->txt, d);
op->len += n;
}
break;
default:
goto err;
}
return op->len;
err:
op->len = 1;
snprintf (op->txt, R_ASM_BUFSIZE, "invalid");
return op->len;
}
Commit Message: Fix crash in wasm disassembler
CWE ID: CWE-125 | int wasm_dis(WasmOp *op, const unsigned char *buf, int buf_len) {
op->len = 1;
op->op = buf[0];
if (op->op > 0xbf) {
return 1;
}
WasmOpDef *opdef = &opcodes[op->op];
switch (op->op) {
case WASM_OP_TRAP:
case WASM_OP_NOP:
case WASM_OP_ELSE:
case WASM_OP_RETURN:
case WASM_OP_DROP:
case WASM_OP_SELECT:
case WASM_OP_I32EQZ:
case WASM_OP_I32EQ:
case WASM_OP_I32NE:
case WASM_OP_I32LTS:
case WASM_OP_I32LTU:
case WASM_OP_I32GTS:
case WASM_OP_I32GTU:
case WASM_OP_I32LES:
case WASM_OP_I32LEU:
case WASM_OP_I32GES:
case WASM_OP_I32GEU:
case WASM_OP_I64EQZ:
case WASM_OP_I64EQ:
case WASM_OP_I64NE:
case WASM_OP_I64LTS:
case WASM_OP_I64LTU:
case WASM_OP_I64GTS:
case WASM_OP_I64GTU:
case WASM_OP_I64LES:
case WASM_OP_I64LEU:
case WASM_OP_I64GES:
case WASM_OP_I64GEU:
case WASM_OP_F32EQ:
case WASM_OP_F32NE:
case WASM_OP_F32LT:
case WASM_OP_F32GT:
case WASM_OP_F32LE:
case WASM_OP_F32GE:
case WASM_OP_F64EQ:
case WASM_OP_F64NE:
case WASM_OP_F64LT:
case WASM_OP_F64GT:
case WASM_OP_F64LE:
case WASM_OP_F64GE:
case WASM_OP_I32CLZ:
case WASM_OP_I32CTZ:
case WASM_OP_I32POPCNT:
case WASM_OP_I32ADD:
case WASM_OP_I32SUB:
case WASM_OP_I32MUL:
case WASM_OP_I32DIVS:
case WASM_OP_I32DIVU:
case WASM_OP_I32REMS:
case WASM_OP_I32REMU:
case WASM_OP_I32AND:
case WASM_OP_I32OR:
case WASM_OP_I32XOR:
case WASM_OP_I32SHL:
case WASM_OP_I32SHRS:
case WASM_OP_I32SHRU:
case WASM_OP_I32ROTL:
case WASM_OP_I32ROTR:
case WASM_OP_I64CLZ:
case WASM_OP_I64CTZ:
case WASM_OP_I64POPCNT:
case WASM_OP_I64ADD:
case WASM_OP_I64SUB:
case WASM_OP_I64MUL:
case WASM_OP_I64DIVS:
case WASM_OP_I64DIVU:
case WASM_OP_I64REMS:
case WASM_OP_I64REMU:
case WASM_OP_I64AND:
case WASM_OP_I64OR:
case WASM_OP_I64XOR:
case WASM_OP_I64SHL:
case WASM_OP_I64SHRS:
case WASM_OP_I64SHRU:
case WASM_OP_I64ROTL:
case WASM_OP_I64ROTR:
case WASM_OP_F32ABS:
case WASM_OP_F32NEG:
case WASM_OP_F32CEIL:
case WASM_OP_F32FLOOR:
case WASM_OP_F32TRUNC:
case WASM_OP_F32NEAREST:
case WASM_OP_F32SQRT:
case WASM_OP_F32ADD:
case WASM_OP_F32SUB:
case WASM_OP_F32MUL:
case WASM_OP_F32DIV:
case WASM_OP_F32MIN:
case WASM_OP_F32MAX:
case WASM_OP_F32COPYSIGN:
case WASM_OP_F64ABS:
case WASM_OP_F64NEG:
case WASM_OP_F64CEIL:
case WASM_OP_F64FLOOR:
case WASM_OP_F64TRUNC:
case WASM_OP_F64NEAREST:
case WASM_OP_F64SQRT:
case WASM_OP_F64ADD:
case WASM_OP_F64SUB:
case WASM_OP_F64MUL:
case WASM_OP_F64DIV:
case WASM_OP_F64MIN:
case WASM_OP_F64MAX:
case WASM_OP_F64COPYSIGN:
case WASM_OP_I32WRAPI64:
case WASM_OP_I32TRUNCSF32:
case WASM_OP_I32TRUNCUF32:
case WASM_OP_I32TRUNCSF64:
case WASM_OP_I32TRUNCUF64:
case WASM_OP_I64EXTENDSI32:
case WASM_OP_I64EXTENDUI32:
case WASM_OP_I64TRUNCSF32:
case WASM_OP_I64TRUNCUF32:
case WASM_OP_I64TRUNCSF64:
case WASM_OP_I64TRUNCUF64:
case WASM_OP_F32CONVERTSI32:
case WASM_OP_F32CONVERTUI32:
case WASM_OP_F32CONVERTSI64:
case WASM_OP_F32CONVERTUI64:
case WASM_OP_F32DEMOTEF64:
case WASM_OP_F64CONVERTSI32:
case WASM_OP_F64CONVERTUI32:
case WASM_OP_F64CONVERTSI64:
case WASM_OP_F64CONVERTUI64:
case WASM_OP_F64PROMOTEF32:
case WASM_OP_I32REINTERPRETF32:
case WASM_OP_I64REINTERPRETF64:
case WASM_OP_F32REINTERPRETI32:
case WASM_OP_F64REINTERPRETI64:
case WASM_OP_END:
{
snprintf (op->txt, R_ASM_BUFSIZE, "%s", opdef->txt);
}
break;
case WASM_OP_BLOCK:
case WASM_OP_LOOP:
case WASM_OP_IF:
{
st32 val = 0;
size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
switch (0x80 - val) {
case R_BIN_WASM_VALUETYPE_EMPTY:
snprintf (op->txt, R_ASM_BUFSIZE, "%s", opdef->txt);
break;
case R_BIN_WASM_VALUETYPE_i32:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result i32)", opdef->txt);
break;
case R_BIN_WASM_VALUETYPE_i64:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result i64)", opdef->txt);
break;
case R_BIN_WASM_VALUETYPE_f32:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result f32)", opdef->txt);
break;
case R_BIN_WASM_VALUETYPE_f64:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result f64)", opdef->txt);
break;
default:
snprintf (op->txt, R_ASM_BUFSIZE, "%s (result ?)", opdef->txt);
break;
}
op->len += n;
}
break;
case WASM_OP_BR:
case WASM_OP_BRIF:
case WASM_OP_CALL:
{
ut32 val = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, val);
op->len += n;
}
break;
case WASM_OP_BRTABLE:
{
ut32 count = 0, *table = NULL, def = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &count);
if (!(n > 0 && n < buf_len)) {
goto err;
}
if (!(table = calloc (count, sizeof (ut32)))) {
goto err;
}
int i = 0;
op->len += n;
for (i = 0; i < count; i++) {
n = read_u32_leb128 (buf + op->len, buf + buf_len, &table[i]);
if (!(op->len + n <= buf_len)) {
goto beach;
}
op->len += n;
}
n = read_u32_leb128 (buf + op->len, buf + buf_len, &def);
if (!(n > 0 && n + op->len < buf_len)) {
goto beach;
}
op->len += n;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d ", opdef->txt, count);
for (i = 0; i < count && strlen (op->txt) + 10 < R_ASM_BUFSIZE; i++) {
int optxtlen = strlen (op->txt);
snprintf (op->txt + optxtlen, R_ASM_BUFSIZE - optxtlen, "%d ", table[i]);
}
snprintf (op->txt + strlen (op->txt), R_ASM_BUFSIZE, "%d", def);
free (table);
break;
beach:
free (table);
goto err;
}
break;
case WASM_OP_CALLINDIRECT:
{
ut32 val = 0, reserved = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
op->len += n;
n = read_u32_leb128 (buf + op->len, buf + buf_len, &reserved);
if (!(n == 1 && op->len + n <= buf_len)) goto err;
reserved &= 0x1;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d %d", opdef->txt, val, reserved);
op->len += n;
}
break;
case WASM_OP_GETLOCAL:
case WASM_OP_SETLOCAL:
case WASM_OP_TEELOCAL:
case WASM_OP_GETGLOBAL:
case WASM_OP_SETGLOBAL:
{
ut32 val = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, val);
op->len += n;
}
break;
case WASM_OP_I32LOAD:
case WASM_OP_I64LOAD:
case WASM_OP_F32LOAD:
case WASM_OP_F64LOAD:
case WASM_OP_I32LOAD8S:
case WASM_OP_I32LOAD8U:
case WASM_OP_I32LOAD16S:
case WASM_OP_I32LOAD16U:
case WASM_OP_I64LOAD8S:
case WASM_OP_I64LOAD8U:
case WASM_OP_I64LOAD16S:
case WASM_OP_I64LOAD16U:
case WASM_OP_I64LOAD32S:
case WASM_OP_I64LOAD32U:
case WASM_OP_I32STORE:
case WASM_OP_I64STORE:
case WASM_OP_F32STORE:
case WASM_OP_F64STORE:
case WASM_OP_I32STORE8:
case WASM_OP_I32STORE16:
case WASM_OP_I64STORE8:
case WASM_OP_I64STORE16:
case WASM_OP_I64STORE32:
{
ut32 flag = 0, offset = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &flag);
if (!(n > 0 && n < buf_len)) goto err;
op->len += n;
n = read_u32_leb128 (buf + op->len, buf + buf_len, &offset);
if (!(n > 0 && op->len + n <= buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d %d", opdef->txt, flag, offset);
op->len += n;
}
break;
case WASM_OP_CURRENTMEMORY:
case WASM_OP_GROWMEMORY:
{
ut32 reserved = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &reserved);
if (!(n == 1 && n < buf_len)) goto err;
reserved &= 0x1;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %d", opdef->txt, reserved);
op->len += n;
}
break;
case WASM_OP_I32CONST:
{
st32 val = 0;
size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %" PFMT32d, opdef->txt, val);
op->len += n;
}
break;
case WASM_OP_I64CONST:
{
st64 val = 0;
size_t n = read_i64_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %" PFMT64d, opdef->txt, val);
op->len += n;
}
break;
case WASM_OP_F32CONST:
{
ut32 val = 0;
size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
long double d = (long double)val;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %" LDBLFMT, opdef->txt, d);
op->len += n;
}
break;
case WASM_OP_F64CONST:
{
ut64 val = 0;
size_t n = read_u64_leb128 (buf + 1, buf + buf_len, &val);
if (!(n > 0 && n < buf_len)) goto err;
long double d = (long double)val;
snprintf (op->txt, R_ASM_BUFSIZE, "%s %" LDBLFMT, opdef->txt, d);
op->len += n;
}
break;
default:
goto err;
}
return op->len;
err:
op->len = 1;
snprintf (op->txt, R_ASM_BUFSIZE, "invalid");
return op->len;
}
| 167,722 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void jas_matrix_divpow2(jas_matrix_t *matrix, int n)
{
int i;
int j;
jas_seqent_t *rowstart;
int rowstep;
jas_seqent_t *data;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = (*data >= 0) ? ((*data) >> n) :
(-((-(*data)) >> n));
}
}
}
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | void jas_matrix_divpow2(jas_matrix_t *matrix, int n)
{
jas_matind_t i;
jas_matind_t j;
jas_seqent_t *rowstart;
jas_matind_t rowstep;
jas_seqent_t *data;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = (*data >= 0) ? ((*data) >> n) :
(-((-(*data)) >> n));
}
}
}
}
| 168,704 |
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: Segment::Segment(IMkvReader* pReader, long long elem_start,
long long start, long long size)
: m_pReader(pReader),
m_element_start(elem_start),
m_start(start),
m_size(size),
m_pos(start),
m_pUnknownSize(0),
m_pSeekHead(NULL),
m_pInfo(NULL),
m_pTracks(NULL),
m_pCues(NULL),
m_pChapters(NULL),
m_clusters(NULL),
m_clusterCount(0),
m_clusterPreloadCount(0),
m_clusterSize(0) {}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | Segment::Segment(IMkvReader* pReader, long long elem_start,
long long start, long long size)
: m_pReader(pReader),
m_element_start(elem_start),
m_start(start),
m_size(size),
m_pos(start),
m_pUnknownSize(0),
m_pSeekHead(NULL),
m_pInfo(NULL),
m_pTracks(NULL),
m_pCues(NULL),
m_pChapters(NULL),
m_pTags(NULL),
m_clusters(NULL),
m_clusterCount(0),
m_clusterPreloadCount(0),
m_clusterSize(0) {}
| 173,864 |
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 SkippedMBMotionComp(
VideoDecData *video
)
{
Vop *prev = video->prevVop;
Vop *comp;
int ypos, xpos;
PIXEL *c_comp, *c_prev;
PIXEL *cu_comp, *cu_prev;
PIXEL *cv_comp, *cv_prev;
int width, width_uv;
int32 offset;
#ifdef PV_POSTPROC_ON // 2/14/2001
int imv;
int32 size = (int32) video->nTotalMB << 8;
uint8 *pp_dec_y, *pp_dec_u;
uint8 *pp_prev1;
int mvwidth = video->nMBPerRow << 1;
#endif
width = video->width;
width_uv = width >> 1;
ypos = video->mbnum_row << 4 ;
xpos = video->mbnum_col << 4 ;
offset = (int32)ypos * width + xpos;
/* zero motion compensation for previous frame */
/*mby*width + mbx;*/
c_prev = prev->yChan + offset;
/*by*width_uv + bx;*/
cu_prev = prev->uChan + (offset >> 2) + (xpos >> 2);
/*by*width_uv + bx;*/
cv_prev = prev->vChan + (offset >> 2) + (xpos >> 2);
comp = video->currVop;
c_comp = comp->yChan + offset;
cu_comp = comp->uChan + (offset >> 2) + (xpos >> 2);
cv_comp = comp->vChan + (offset >> 2) + (xpos >> 2);
/* Copy previous reconstructed frame into the current frame */
PutSKIPPED_MB(c_comp, c_prev, width);
PutSKIPPED_B(cu_comp, cu_prev, width_uv);
PutSKIPPED_B(cv_comp, cv_prev, width_uv);
/* 10/24/2000 post_processing semaphore generation */
#ifdef PV_POSTPROC_ON // 2/14/2001
if (video->postFilterType != PV_NO_POST_PROC)
{
imv = (offset >> 6) - (xpos >> 6) + (xpos >> 3);
/* Post-processing mode (copy previous MB) */
pp_prev1 = video->pstprcTypPrv + imv;
pp_dec_y = video->pstprcTypCur + imv;
*pp_dec_y = *pp_prev1;
*(pp_dec_y + 1) = *(pp_prev1 + 1);
*(pp_dec_y + mvwidth) = *(pp_prev1 + mvwidth);
*(pp_dec_y + mvwidth + 1) = *(pp_prev1 + mvwidth + 1);
/* chrominance */
/*4*MB_in_width*MB_in_height*/
pp_prev1 = video->pstprcTypPrv + (size >> 6) +
((imv + (xpos >> 3)) >> 2);
pp_dec_u = video->pstprcTypCur + (size >> 6) +
((imv + (xpos >> 3)) >> 2);
*pp_dec_u = *pp_prev1;
pp_dec_u[size>>8] = pp_prev1[size>>8];
}
#endif
/*----------------------------------------------------------------------------
; Return nothing or data or data pointer
----------------------------------------------------------------------------*/
return;
}
Commit Message: Fix NPDs in h263 decoder
Bug: 35269635
Test: decoded PoC with and without patch
Change-Id: I636a14360c7801cc5bca63c9cb44d1d235df8fd8
(cherry picked from commit 2ad2a92318a3b9daf78ebcdc597085adbf32600d)
CWE ID: | void SkippedMBMotionComp(
VideoDecData *video
)
{
Vop *prev = video->prevVop;
Vop *comp;
int ypos, xpos;
PIXEL *c_comp, *c_prev;
PIXEL *cu_comp, *cu_prev;
PIXEL *cv_comp, *cv_prev;
int width, width_uv;
int32 offset;
#ifdef PV_POSTPROC_ON // 2/14/2001
int imv;
int32 size = (int32) video->nTotalMB << 8;
uint8 *pp_dec_y, *pp_dec_u;
uint8 *pp_prev1;
int mvwidth = video->nMBPerRow << 1;
#endif
width = video->width;
width_uv = width >> 1;
ypos = video->mbnum_row << 4 ;
xpos = video->mbnum_col << 4 ;
offset = (int32)ypos * width + xpos;
/* zero motion compensation for previous frame */
/*mby*width + mbx;*/
c_prev = prev->yChan;
if (!c_prev) {
ALOGE("b/35269635");
android_errorWriteLog(0x534e4554, "35269635");
return;
}
c_prev += offset;
/*by*width_uv + bx;*/
cu_prev = prev->uChan + (offset >> 2) + (xpos >> 2);
/*by*width_uv + bx;*/
cv_prev = prev->vChan + (offset >> 2) + (xpos >> 2);
comp = video->currVop;
c_comp = comp->yChan + offset;
cu_comp = comp->uChan + (offset >> 2) + (xpos >> 2);
cv_comp = comp->vChan + (offset >> 2) + (xpos >> 2);
/* Copy previous reconstructed frame into the current frame */
PutSKIPPED_MB(c_comp, c_prev, width);
PutSKIPPED_B(cu_comp, cu_prev, width_uv);
PutSKIPPED_B(cv_comp, cv_prev, width_uv);
/* 10/24/2000 post_processing semaphore generation */
#ifdef PV_POSTPROC_ON // 2/14/2001
if (video->postFilterType != PV_NO_POST_PROC)
{
imv = (offset >> 6) - (xpos >> 6) + (xpos >> 3);
/* Post-processing mode (copy previous MB) */
pp_prev1 = video->pstprcTypPrv + imv;
pp_dec_y = video->pstprcTypCur + imv;
*pp_dec_y = *pp_prev1;
*(pp_dec_y + 1) = *(pp_prev1 + 1);
*(pp_dec_y + mvwidth) = *(pp_prev1 + mvwidth);
*(pp_dec_y + mvwidth + 1) = *(pp_prev1 + mvwidth + 1);
/* chrominance */
/*4*MB_in_width*MB_in_height*/
pp_prev1 = video->pstprcTypPrv + (size >> 6) +
((imv + (xpos >> 3)) >> 2);
pp_dec_u = video->pstprcTypCur + (size >> 6) +
((imv + (xpos >> 3)) >> 2);
*pp_dec_u = *pp_prev1;
pp_dec_u[size>>8] = pp_prev1[size>>8];
}
#endif
/*----------------------------------------------------------------------------
; Return nothing or data or data pointer
----------------------------------------------------------------------------*/
return;
}
| 174,005 |
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 CNB::SetupLSO(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength) const
{
PopulateIPLength(reinterpret_cast<IPv4Header*>(IpHeader), static_cast<USHORT>(EthPayloadLength));
tTcpIpPacketParsingResult packetReview;
packetReview = ParaNdis_CheckSumVerifyFlat(reinterpret_cast<IPv4Header*>(IpHeader), EthPayloadLength,
pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum,
__FUNCTION__);
if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS)
{
auto IpHeaderOffset = m_Context->Offload.ipHeaderOffset;
auto VHeader = static_cast<virtio_net_hdr_basic*>(VirtioHeader);
auto PriorityHdrLen = (m_ParentNBL->TCI() != 0) ? ETH_PRIORITY_HEADER_SIZE : 0;
VHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
VHeader->gso_type = packetReview.ipStatus == ppresIPV4 ? VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6;
VHeader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + IpHeaderOffset + PriorityHdrLen);
VHeader->gso_size = (USHORT)m_ParentNBL->MSS();
VHeader->csum_start = (USHORT)(m_ParentNBL->TCPHeaderOffset() + PriorityHdrLen);
VHeader->csum_offset = TCP_CHECKSUM_OFFSET;
}
}
Commit Message: NetKVM: BZ#1169718: Checking the length only on read
Signed-off-by: Joseph Hindin <[email protected]>
CWE ID: CWE-20 | void CNB::SetupLSO(virtio_net_hdr_basic *VirtioHeader, PVOID IpHeader, ULONG EthPayloadLength) const
{
PopulateIPLength(reinterpret_cast<IPv4Header*>(IpHeader), static_cast<USHORT>(EthPayloadLength));
tTcpIpPacketParsingResult packetReview;
packetReview = ParaNdis_CheckSumVerifyFlat(reinterpret_cast<IPv4Header*>(IpHeader), EthPayloadLength,
pcrIpChecksum | pcrFixIPChecksum | pcrTcpChecksum | pcrFixPHChecksum,
FALSE,
__FUNCTION__);
if (packetReview.xxpCheckSum == ppresPCSOK || packetReview.fixedXxpCS)
{
auto IpHeaderOffset = m_Context->Offload.ipHeaderOffset;
auto VHeader = static_cast<virtio_net_hdr_basic*>(VirtioHeader);
auto PriorityHdrLen = (m_ParentNBL->TCI() != 0) ? ETH_PRIORITY_HEADER_SIZE : 0;
VHeader->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
VHeader->gso_type = packetReview.ipStatus == ppresIPV4 ? VIRTIO_NET_HDR_GSO_TCPV4 : VIRTIO_NET_HDR_GSO_TCPV6;
VHeader->hdr_len = (USHORT)(packetReview.XxpIpHeaderSize + IpHeaderOffset + PriorityHdrLen);
VHeader->gso_size = (USHORT)m_ParentNBL->MSS();
VHeader->csum_start = (USHORT)(m_ParentNBL->TCPHeaderOffset() + PriorityHdrLen);
VHeader->csum_offset = TCP_CHECKSUM_OFFSET;
}
}
| 170,142 |
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<views::Border> AutofillPopupBaseView::CreateBorder() {
auto border = std::make_unique<views::BubbleBorder>(
views::BubbleBorder::NONE, views::BubbleBorder::SMALL_SHADOW,
SK_ColorWHITE);
border->SetCornerRadius(GetCornerRadius());
border->set_md_shadow_elevation(
ChromeLayoutProvider::Get()->GetShadowElevationMetric(
views::EMPHASIS_MEDIUM));
return border;
}
Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature.
Bug: 906135,831603
Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499
Reviewed-on: https://chromium-review.googlesource.com/c/1387124
Reviewed-by: Robert Kaplow <[email protected]>
Reviewed-by: Vasilii Sukhanov <[email protected]>
Reviewed-by: Fabio Tirelo <[email protected]>
Reviewed-by: Tommy Martino <[email protected]>
Commit-Queue: Mathieu Perreault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621360}
CWE ID: CWE-416 | std::unique_ptr<views::Border> AutofillPopupBaseView::CreateBorder() {
| 172,094 |
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 TargetHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
auto_attacher_.SetRenderFrameHost(frame_host);
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void TargetHandler::SetRenderer(RenderProcessHost* process_host,
void TargetHandler::SetRenderer(int process_host_id,
RenderFrameHostImpl* frame_host) {
auto_attacher_.SetRenderFrameHost(frame_host);
}
| 172,780 |
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 recv_stream(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t buf_len, int flags)
{
struct sock *sk = sock->sk;
struct tipc_port *tport = tipc_sk_port(sk);
struct sk_buff *buf;
struct tipc_msg *msg;
long timeout;
unsigned int sz;
int sz_to_copy, target, needed;
int sz_copied = 0;
u32 err;
int res = 0;
/* Catch invalid receive attempts */
if (unlikely(!buf_len))
return -EINVAL;
lock_sock(sk);
if (unlikely((sock->state == SS_UNCONNECTED))) {
res = -ENOTCONN;
goto exit;
}
/* will be updated in set_orig_addr() if needed */
m->msg_namelen = 0;
target = sock_rcvlowat(sk, flags & MSG_WAITALL, buf_len);
timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
restart:
/* Look for a message in receive queue; wait if necessary */
while (skb_queue_empty(&sk->sk_receive_queue)) {
if (sock->state == SS_DISCONNECTING) {
res = -ENOTCONN;
goto exit;
}
if (timeout <= 0L) {
res = timeout ? timeout : -EWOULDBLOCK;
goto exit;
}
release_sock(sk);
timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
tipc_rx_ready(sock),
timeout);
lock_sock(sk);
}
/* Look at first message in receive queue */
buf = skb_peek(&sk->sk_receive_queue);
msg = buf_msg(buf);
sz = msg_data_sz(msg);
err = msg_errcode(msg);
/* Discard an empty non-errored message & try again */
if ((!sz) && (!err)) {
advance_rx_queue(sk);
goto restart;
}
/* Optionally capture sender's address & ancillary data of first msg */
if (sz_copied == 0) {
set_orig_addr(m, msg);
res = anc_data_recv(m, msg, tport);
if (res)
goto exit;
}
/* Capture message data (if valid) & compute return value (always) */
if (!err) {
u32 offset = (u32)(unsigned long)(TIPC_SKB_CB(buf)->handle);
sz -= offset;
needed = (buf_len - sz_copied);
sz_to_copy = (sz <= needed) ? sz : needed;
res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg) + offset,
m->msg_iov, sz_to_copy);
if (res)
goto exit;
sz_copied += sz_to_copy;
if (sz_to_copy < sz) {
if (!(flags & MSG_PEEK))
TIPC_SKB_CB(buf)->handle =
(void *)(unsigned long)(offset + sz_to_copy);
goto exit;
}
} else {
if (sz_copied != 0)
goto exit; /* can't add error msg to valid data */
if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
res = 0;
else
res = -ECONNRESET;
}
/* Consume received message (optional) */
if (likely(!(flags & MSG_PEEK))) {
if (unlikely(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
tipc_acknowledge(tport->ref, tport->conn_unacked);
advance_rx_queue(sk);
}
/* Loop around if more data is required */
if ((sz_copied < buf_len) && /* didn't get all requested data */
(!skb_queue_empty(&sk->sk_receive_queue) ||
(sz_copied < target)) && /* and more is ready or required */
(!(flags & MSG_PEEK)) && /* and aren't just peeking at data */
(!err)) /* and haven't reached a FIN */
goto restart;
exit:
release_sock(sk);
return sz_copied ? sz_copied : res;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | static int recv_stream(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t buf_len, int flags)
{
struct sock *sk = sock->sk;
struct tipc_port *tport = tipc_sk_port(sk);
struct sk_buff *buf;
struct tipc_msg *msg;
long timeout;
unsigned int sz;
int sz_to_copy, target, needed;
int sz_copied = 0;
u32 err;
int res = 0;
/* Catch invalid receive attempts */
if (unlikely(!buf_len))
return -EINVAL;
lock_sock(sk);
if (unlikely((sock->state == SS_UNCONNECTED))) {
res = -ENOTCONN;
goto exit;
}
target = sock_rcvlowat(sk, flags & MSG_WAITALL, buf_len);
timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
restart:
/* Look for a message in receive queue; wait if necessary */
while (skb_queue_empty(&sk->sk_receive_queue)) {
if (sock->state == SS_DISCONNECTING) {
res = -ENOTCONN;
goto exit;
}
if (timeout <= 0L) {
res = timeout ? timeout : -EWOULDBLOCK;
goto exit;
}
release_sock(sk);
timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
tipc_rx_ready(sock),
timeout);
lock_sock(sk);
}
/* Look at first message in receive queue */
buf = skb_peek(&sk->sk_receive_queue);
msg = buf_msg(buf);
sz = msg_data_sz(msg);
err = msg_errcode(msg);
/* Discard an empty non-errored message & try again */
if ((!sz) && (!err)) {
advance_rx_queue(sk);
goto restart;
}
/* Optionally capture sender's address & ancillary data of first msg */
if (sz_copied == 0) {
set_orig_addr(m, msg);
res = anc_data_recv(m, msg, tport);
if (res)
goto exit;
}
/* Capture message data (if valid) & compute return value (always) */
if (!err) {
u32 offset = (u32)(unsigned long)(TIPC_SKB_CB(buf)->handle);
sz -= offset;
needed = (buf_len - sz_copied);
sz_to_copy = (sz <= needed) ? sz : needed;
res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg) + offset,
m->msg_iov, sz_to_copy);
if (res)
goto exit;
sz_copied += sz_to_copy;
if (sz_to_copy < sz) {
if (!(flags & MSG_PEEK))
TIPC_SKB_CB(buf)->handle =
(void *)(unsigned long)(offset + sz_to_copy);
goto exit;
}
} else {
if (sz_copied != 0)
goto exit; /* can't add error msg to valid data */
if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
res = 0;
else
res = -ECONNRESET;
}
/* Consume received message (optional) */
if (likely(!(flags & MSG_PEEK))) {
if (unlikely(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
tipc_acknowledge(tport->ref, tport->conn_unacked);
advance_rx_queue(sk);
}
/* Loop around if more data is required */
if ((sz_copied < buf_len) && /* didn't get all requested data */
(!skb_queue_empty(&sk->sk_receive_queue) ||
(sz_copied < target)) && /* and more is ready or required */
(!(flags & MSG_PEEK)) && /* and aren't just peeking at data */
(!err)) /* and haven't reached a FIN */
goto restart;
exit:
release_sock(sk);
return sz_copied ? sz_copied : res;
}
| 166,518 |
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: base::string16 GetAppForProtocolUsingRegistry(const GURL& url) {
base::string16 command_to_launch;
base::string16 cmd_key_path = base::ASCIIToUTF16(url.scheme());
base::win::RegKey cmd_key_name(HKEY_CLASSES_ROOT, cmd_key_path.c_str(),
KEY_READ);
if (cmd_key_name.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS &&
!command_to_launch.empty()) {
return command_to_launch;
}
cmd_key_path = base::ASCIIToUTF16(url.scheme() + "\\shell\\open\\command");
base::win::RegKey cmd_key_exe(HKEY_CLASSES_ROOT, cmd_key_path.c_str(),
KEY_READ);
if (cmd_key_exe.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS) {
base::CommandLine command_line(
base::CommandLine::FromString(command_to_launch));
return command_line.GetProgram().BaseName().value();
}
return base::string16();
}
Commit Message: Validate external protocols before launching on Windows
Bug: 889459
Change-Id: Id33ca6444bff1e6dd71b6000823cf6fec09746ef
Reviewed-on: https://chromium-review.googlesource.com/c/1256208
Reviewed-by: Greg Thompson <[email protected]>
Commit-Queue: Mustafa Emre Acer <[email protected]>
Cr-Commit-Position: refs/heads/master@{#597611}
CWE ID: CWE-20 | base::string16 GetAppForProtocolUsingRegistry(const GURL& url) {
const base::string16 url_scheme = base::ASCIIToUTF16(url.scheme());
if (!IsValidCustomProtocol(url_scheme))
return base::string16();
base::string16 command_to_launch;
base::win::RegKey cmd_key_name(HKEY_CLASSES_ROOT, url_scheme.c_str(),
KEY_READ);
if (cmd_key_name.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS &&
!command_to_launch.empty()) {
return command_to_launch;
}
const base::string16 cmd_key_path = url_scheme + L"\\shell\\open\\command";
base::win::RegKey cmd_key_exe(HKEY_CLASSES_ROOT, cmd_key_path.c_str(),
KEY_READ);
if (cmd_key_exe.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS) {
base::CommandLine command_line(
base::CommandLine::FromString(command_to_launch));
return command_line.GetProgram().BaseName().value();
}
return base::string16();
}
| 172,636 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION( msgfmt_format_message )
{
zval *args;
UChar *spattern = NULL;
int spattern_len = 0;
char *pattern = NULL;
int pattern_len = 0;
const char *slocale = NULL;
int slocale_len = 0;
MessageFormatter_object mf = {0};
MessageFormatter_object *mfo = &mf;
/* Parse parameters. */
if( zend_parse_method_parameters( ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "ssa",
&slocale, &slocale_len, &pattern, &pattern_len, &args ) == FAILURE )
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"msgfmt_format_message: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
msgformat_data_init(&mfo->mf_data TSRMLS_CC);
if(pattern && pattern_len) {
intl_convert_utf8_to_utf16(&spattern, &spattern_len, pattern, pattern_len, &INTL_DATA_ERROR_CODE(mfo));
if( U_FAILURE(INTL_DATA_ERROR_CODE((mfo))) )
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"msgfmt_format_message: error converting pattern to UTF-16", 0 TSRMLS_CC );
RETURN_FALSE;
}
} else {
spattern_len = 0;
spattern = NULL;
}
if(slocale_len == 0) {
slocale = intl_locale_get_default(TSRMLS_C);
}
#ifdef MSG_FORMAT_QUOTE_APOS
if(msgformat_fix_quotes(&spattern, &spattern_len, &INTL_DATA_ERROR_CODE(mfo)) != SUCCESS) {
intl_error_set( NULL, U_INVALID_FORMAT_ERROR,
"msgfmt_format_message: error converting pattern to quote-friendly format", 0 TSRMLS_CC );
RETURN_FALSE;
}
#endif
/* Create an ICU message formatter. */
MSG_FORMAT_OBJECT(mfo) = umsg_open(spattern, spattern_len, slocale, NULL, &INTL_DATA_ERROR_CODE(mfo));
if(spattern && spattern_len) {
efree(spattern);
}
INTL_METHOD_CHECK_STATUS(mfo, "Creating message formatter failed");
msgfmt_do_format(mfo, args, return_value TSRMLS_CC);
/* drop the temporary formatter */
msgformat_data_free(&mfo->mf_data TSRMLS_CC);
}
Commit Message: Fix bug #73007: add locale length check
CWE ID: CWE-119 | PHP_FUNCTION( msgfmt_format_message )
{
zval *args;
UChar *spattern = NULL;
int spattern_len = 0;
char *pattern = NULL;
int pattern_len = 0;
const char *slocale = NULL;
int slocale_len = 0;
MessageFormatter_object mf = {0};
MessageFormatter_object *mfo = &mf;
/* Parse parameters. */
if( zend_parse_method_parameters( ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "ssa",
&slocale, &slocale_len, &pattern, &pattern_len, &args ) == FAILURE )
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"msgfmt_format_message: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
INTL_CHECK_LOCALE_LEN(slocale_len);
msgformat_data_init(&mfo->mf_data TSRMLS_CC);
if(pattern && pattern_len) {
intl_convert_utf8_to_utf16(&spattern, &spattern_len, pattern, pattern_len, &INTL_DATA_ERROR_CODE(mfo));
if( U_FAILURE(INTL_DATA_ERROR_CODE((mfo))) )
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"msgfmt_format_message: error converting pattern to UTF-16", 0 TSRMLS_CC );
RETURN_FALSE;
}
} else {
spattern_len = 0;
spattern = NULL;
}
if(slocale_len == 0) {
slocale = intl_locale_get_default(TSRMLS_C);
}
#ifdef MSG_FORMAT_QUOTE_APOS
if(msgformat_fix_quotes(&spattern, &spattern_len, &INTL_DATA_ERROR_CODE(mfo)) != SUCCESS) {
intl_error_set( NULL, U_INVALID_FORMAT_ERROR,
"msgfmt_format_message: error converting pattern to quote-friendly format", 0 TSRMLS_CC );
RETURN_FALSE;
}
#endif
/* Create an ICU message formatter. */
MSG_FORMAT_OBJECT(mfo) = umsg_open(spattern, spattern_len, slocale, NULL, &INTL_DATA_ERROR_CODE(mfo));
if(spattern && spattern_len) {
efree(spattern);
}
INTL_METHOD_CHECK_STATUS(mfo, "Creating message formatter failed");
msgfmt_do_format(mfo, args, return_value TSRMLS_CC);
/* drop the temporary formatter */
msgformat_data_free(&mfo->mf_data TSRMLS_CC);
}
| 166,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 em_fxrstor(struct x86_emulate_ctxt *ctxt)
{
struct fxregs_state fx_state;
int rc;
rc = check_fxsr(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = segmented_read(ctxt, ctxt->memop.addr.mem, &fx_state, 512);
if (rc != X86EMUL_CONTINUE)
return rc;
if (fx_state.mxcsr >> 16)
return emulate_gp(ctxt, 0);
ctxt->ops->get_fpu(ctxt);
if (ctxt->mode < X86EMUL_MODE_PROT64)
rc = fxrstor_fixup(ctxt, &fx_state);
if (rc == X86EMUL_CONTINUE)
rc = asm_safe("fxrstor %[fx]", : [fx] "m"(fx_state));
ctxt->ops->put_fpu(ctxt);
return rc;
}
Commit Message: KVM: x86: Introduce segmented_write_std
Introduces segemented_write_std.
Switches from emulated reads/writes to standard read/writes in fxsave,
fxrstor, sgdt, and sidt. This fixes CVE-2017-2584, a longstanding
kernel memory leak.
Since commit 283c95d0e389 ("KVM: x86: emulate FXSAVE and FXRSTOR",
2016-11-09), which is luckily not yet in any final release, this would
also be an exploitable kernel memory *write*!
Reported-by: Dmitry Vyukov <[email protected]>
Cc: [email protected]
Fixes: 96051572c819194c37a8367624b285be10297eca
Fixes: 283c95d0e3891b64087706b344a4b545d04a6e62
Suggested-by: Paolo Bonzini <[email protected]>
Signed-off-by: Steve Rutherford <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-416 | static int em_fxrstor(struct x86_emulate_ctxt *ctxt)
{
struct fxregs_state fx_state;
int rc;
rc = check_fxsr(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = segmented_read_std(ctxt, ctxt->memop.addr.mem, &fx_state, 512);
if (rc != X86EMUL_CONTINUE)
return rc;
if (fx_state.mxcsr >> 16)
return emulate_gp(ctxt, 0);
ctxt->ops->get_fpu(ctxt);
if (ctxt->mode < X86EMUL_MODE_PROT64)
rc = fxrstor_fixup(ctxt, &fx_state);
if (rc == X86EMUL_CONTINUE)
rc = asm_safe("fxrstor %[fx]", : [fx] "m"(fx_state));
ctxt->ops->put_fpu(ctxt);
return rc;
}
| 168,444 |
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 BluetoothDeviceChromeOS::ConfirmPairing() {
if (!agent_.get() || confirmation_callback_.is_null())
return;
confirmation_callback_.Run(SUCCESS);
confirmation_callback_.Reset();
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void BluetoothDeviceChromeOS::ConfirmPairing() {
if (!pairing_context_.get())
return;
pairing_context_->ConfirmPairing();
}
| 171,220 |
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: PlatformSensor::PlatformSensor(mojom::SensorType type,
mojo::ScopedSharedBufferMapping mapping,
PlatformSensorProvider* provider)
: task_runner_(base::ThreadTaskRunnerHandle::Get()),
shared_buffer_mapping_(std::move(mapping)),
type_(type),
provider_(provider),
weak_factory_(this) {}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732 | PlatformSensor::PlatformSensor(mojom::SensorType type,
SensorReadingSharedBuffer* reading_buffer,
PlatformSensorProvider* provider)
: task_runner_(base::ThreadTaskRunnerHandle::Get()),
reading_buffer_(reading_buffer),
type_(type),
provider_(provider),
weak_factory_(this) {}
| 172,822 |
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: FLAC__StreamDecoderWriteStatus FLACParser::writeCallback(
const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
{
if (mWriteRequested) {
mWriteRequested = false;
mWriteHeader = frame->header;
mWriteBuffer = buffer;
mWriteCompleted = true;
return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
} else {
ALOGE("FLACParser::writeCallback unexpected");
return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119 | FLAC__StreamDecoderWriteStatus FLACParser::writeCallback(
const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
{
if (mWriteRequested) {
mWriteRequested = false;
mWriteHeader = frame->header;
memmove(mWriteBuffer, buffer, sizeof(const FLAC__int32 * const) * getChannels());
mWriteCompleted = true;
return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
} else {
ALOGE("FLACParser::writeCallback unexpected");
return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
}
}
| 174,026 |
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 AffiliationFetcher::ParseResponse(
AffiliationFetcherDelegate::Result* result) const {
std::string serialized_response;
if (!fetcher_->GetResponseAsString(&serialized_response)) {
NOTREACHED();
}
affiliation_pb::LookupAffiliationResponse response;
if (!response.ParseFromString(serialized_response))
return false;
result->reserve(requested_facet_uris_.size());
std::map<FacetURI, size_t> facet_uri_to_class_index;
for (int i = 0; i < response.affiliation_size(); ++i) {
const affiliation_pb::Affiliation& equivalence_class(
response.affiliation(i));
AffiliatedFacets affiliated_uris;
for (int j = 0; j < equivalence_class.facet_size(); ++j) {
const std::string& uri_spec(equivalence_class.facet(j));
FacetURI uri = FacetURI::FromPotentiallyInvalidSpec(uri_spec);
if (!uri.is_valid())
continue;
affiliated_uris.push_back(uri);
}
if (affiliated_uris.empty())
continue;
for (const FacetURI& uri : affiliated_uris) {
if (!facet_uri_to_class_index.count(uri))
facet_uri_to_class_index[uri] = result->size();
if (facet_uri_to_class_index[uri] !=
facet_uri_to_class_index[affiliated_uris[0]]) {
return false;
}
}
if (facet_uri_to_class_index[affiliated_uris[0]] == result->size())
result->push_back(affiliated_uris);
}
for (const FacetURI& uri : requested_facet_uris_) {
if (!facet_uri_to_class_index.count(uri))
result->push_back(AffiliatedFacets(1, uri));
}
return true;
}
Commit Message: Update AffiliationFetcher to use new Affiliation API wire format.
The new format is not backward compatible with the old one, therefore this CL updates the client side protobuf definitions to be in line with the API definition. However, this CL does not yet make use of any additional fields introduced in the new wire format.
BUG=437865
Review URL: https://codereview.chromium.org/996613002
Cr-Commit-Position: refs/heads/master@{#319860}
CWE ID: CWE-119 | bool AffiliationFetcher::ParseResponse(
AffiliationFetcherDelegate::Result* result) const {
std::string serialized_response;
if (!fetcher_->GetResponseAsString(&serialized_response)) {
NOTREACHED();
}
affiliation_pb::LookupAffiliationResponse response;
if (!response.ParseFromString(serialized_response))
return false;
result->reserve(requested_facet_uris_.size());
std::map<FacetURI, size_t> facet_uri_to_class_index;
for (int i = 0; i < response.affiliation_size(); ++i) {
const affiliation_pb::Affiliation& equivalence_class(
response.affiliation(i));
AffiliatedFacets affiliated_uris;
for (int j = 0; j < equivalence_class.facet_size(); ++j) {
const std::string& uri_spec(equivalence_class.facet(j).id());
FacetURI uri = FacetURI::FromPotentiallyInvalidSpec(uri_spec);
if (!uri.is_valid())
continue;
affiliated_uris.push_back(uri);
}
if (affiliated_uris.empty())
continue;
for (const FacetURI& uri : affiliated_uris) {
if (!facet_uri_to_class_index.count(uri))
facet_uri_to_class_index[uri] = result->size();
if (facet_uri_to_class_index[uri] !=
facet_uri_to_class_index[affiliated_uris[0]]) {
return false;
}
}
if (facet_uri_to_class_index[affiliated_uris[0]] == result->size())
result->push_back(affiliated_uris);
}
for (const FacetURI& uri : requested_facet_uris_) {
if (!facet_uri_to_class_index.count(uri))
result->push_back(AffiliatedFacets(1, uri));
}
return true;
}
| 171,143 |
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: unsigned int SAD(unsigned int max_sad, int block_idx = 0) {
unsigned int ret;
const uint8_t* const reference = GetReference(block_idx);
REGISTER_STATE_CHECK(ret = GET_PARAM(2)(source_data_, source_stride_,
reference, reference_stride_,
max_sad));
return ret;
}
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 | unsigned int SAD(unsigned int max_sad, int block_idx = 0) {
| 174,575 |
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 read_image_tga( gdIOCtx *ctx, oTga *tga )
{
int pixel_block_size = (tga->bits / 8);
int image_block_size = (tga->width * tga->height) * pixel_block_size;
uint8_t* decompression_buffer = NULL;
unsigned char* conversion_buffer = NULL;
int buffer_caret = 0;
int bitmap_caret = 0;
int i = 0;
int j = 0;
uint8_t encoded_pixels;
if(overflow2(tga->width, tga->height)) {
return -1;
}
if(overflow2(tga->width * tga->height, pixel_block_size)) {
return -1;
}
if(overflow2(image_block_size, sizeof(int))) {
return -1;
}
/*! \todo Add more image type support.
*/
if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE)
return -1;
/*! \brief Allocate memmory for image block
* Allocate a chunk of memory for the image block to be passed into.
*/
tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int));
if (tga->bitmap == NULL)
return -1;
switch (tga->imagetype) {
case TGA_TYPE_RGB:
/*! \brief Read in uncompressed RGB TGA
* Chunk load the pixel data from an uncompressed RGB type TGA.
*/
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gd_error("gd-tga: premature end of image data\n");
gdFree(conversion_buffer);
return -1;
}
while (buffer_caret < image_block_size) {
tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret];
buffer_caret++;
}
gdFree(conversion_buffer);
break;
case TGA_TYPE_RGB_RLE:
/*! \brief Read in RLE compressed RGB TGA
* Chunk load the pixel data from an RLE compressed RGB type TGA.
*/
decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t));
if (decompression_buffer == NULL) {
return -1;
}
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
gd_error("gd-tga: premature end of image data\n");
gdFree( decompression_buffer );
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gdFree(conversion_buffer);
gdFree(decompression_buffer);
return -1;
}
buffer_caret = 0;
while( buffer_caret < image_block_size) {
decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret];
buffer_caret++;
}
buffer_caret = 0;
while( bitmap_caret < image_block_size ) {
if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {
encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 );
buffer_caret++;
if (encoded_pixels != 0) {
if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
for (i = 0; i < encoded_pixels; i++) {
for (j = 0; j < pixel_block_size; j++, bitmap_caret++) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
}
}
buffer_caret += pixel_block_size;
} else {
encoded_pixels = decompression_buffer[ buffer_caret ] + 1;
buffer_caret++;
if (encoded_pixels != 0) {
if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
for (i = 0; i < encoded_pixels; i++) {
for( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
buffer_caret += pixel_block_size;
}
}
}
}
gdFree( decompression_buffer );
gdFree( conversion_buffer );
break;
}
return 1;
}
Commit Message: Proper fix for #248
CWE ID: CWE-125 | int read_image_tga( gdIOCtx *ctx, oTga *tga )
{
int pixel_block_size = (tga->bits / 8);
int image_block_size = (tga->width * tga->height) * pixel_block_size;
uint8_t* decompression_buffer = NULL;
unsigned char* conversion_buffer = NULL;
int buffer_caret = 0;
int bitmap_caret = 0;
int i = 0;
uint8_t encoded_pixels;
if(overflow2(tga->width, tga->height)) {
return -1;
}
if(overflow2(tga->width * tga->height, pixel_block_size)) {
return -1;
}
if(overflow2(image_block_size, sizeof(int))) {
return -1;
}
/*! \todo Add more image type support.
*/
if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE)
return -1;
/*! \brief Allocate memmory for image block
* Allocate a chunk of memory for the image block to be passed into.
*/
tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int));
if (tga->bitmap == NULL)
return -1;
switch (tga->imagetype) {
case TGA_TYPE_RGB:
/*! \brief Read in uncompressed RGB TGA
* Chunk load the pixel data from an uncompressed RGB type TGA.
*/
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gd_error("gd-tga: premature end of image data\n");
gdFree(conversion_buffer);
return -1;
}
while (buffer_caret < image_block_size) {
tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret];
buffer_caret++;
}
gdFree(conversion_buffer);
break;
case TGA_TYPE_RGB_RLE:
/*! \brief Read in RLE compressed RGB TGA
* Chunk load the pixel data from an RLE compressed RGB type TGA.
*/
decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t));
if (decompression_buffer == NULL) {
return -1;
}
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
gd_error("gd-tga: premature end of image data\n");
gdFree( decompression_buffer );
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gdFree(conversion_buffer);
gdFree(decompression_buffer);
return -1;
}
buffer_caret = 0;
while( buffer_caret < image_block_size) {
decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret];
buffer_caret++;
}
buffer_caret = 0;
while( bitmap_caret < image_block_size ) {
if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {
encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & !TGA_RLE_FLAG ) + 1 );
buffer_caret++;
if ((bitmap_caret + (encoded_pixels * pixel_block_size)) >= image_block_size) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
for (i = 0; i < encoded_pixels; i++) {
memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size);
bitmap_caret += pixel_block_size;
}
buffer_caret += pixel_block_size;
} else {
encoded_pixels = decompression_buffer[ buffer_caret ] + 1;
buffer_caret++;
if ((bitmap_caret + (encoded_pixels * pixel_block_size)) >= image_block_size) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size);
bitmap_caret += (encoded_pixels * pixel_block_size);
buffer_caret += (encoded_pixels * pixel_block_size);
}
}
gdFree( decompression_buffer );
gdFree( conversion_buffer );
break;
}
return 1;
}
| 166,980 |
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 uint8_t *extend_raw_data(LHAFileHeader **header,
LHAInputStream *stream,
size_t nbytes)
{
LHAFileHeader *new_header;
size_t new_raw_len;
uint8_t *result;
new_raw_len = RAW_DATA_LEN(header) + nbytes;
new_header = realloc(*header, sizeof(LHAFileHeader) + new_raw_len);
if (new_header == NULL) {
return NULL;
}
*header = new_header;
new_header->raw_data = (uint8_t *) (new_header + 1);
result = new_header->raw_data + new_header->raw_data_len;
if (!lha_input_stream_read(stream, result, nbytes)) {
return NULL;
}
new_header->raw_data_len = new_raw_len;
return result;
}
Commit Message: Fix integer underflow vulnerability in L3 decode.
Marcin 'Icewall' Noga of Cisco TALOS discovered that the level 3 header
decoding routines were vulnerable to an integer underflow, if the 32-bit
header length was less than the base level 3 header length. This could
lead to an exploitable heap corruption condition.
Thanks go to Marcin Noga and Regina Wilson of Cisco TALOS for reporting
this vulnerability.
CWE ID: CWE-190 | static uint8_t *extend_raw_data(LHAFileHeader **header,
LHAInputStream *stream,
size_t nbytes)
{
LHAFileHeader *new_header;
size_t new_raw_len;
uint8_t *result;
if (nbytes > LEVEL_3_MAX_HEADER_LEN) {
return NULL;
}
new_raw_len = RAW_DATA_LEN(header) + nbytes;
new_header = realloc(*header, sizeof(LHAFileHeader) + new_raw_len);
if (new_header == NULL) {
return NULL;
}
*header = new_header;
new_header->raw_data = (uint8_t *) (new_header + 1);
result = new_header->raw_data + new_header->raw_data_len;
if (!lha_input_stream_read(stream, result, nbytes)) {
return NULL;
}
new_header->raw_data_len = new_raw_len;
return result;
}
| 168,847 |
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 _gd2GetHeader(gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx)
{
int i;
int ch;
char id[5];
t_chunk_info *cidx;
int sidx;
int nc;
GD2_DBG(php_gd_error("Reading gd2 header info"));
for (i = 0; i < 4; i++) {
ch = gdGetC(in);
if (ch == EOF) {
goto fail1;
}
id[i] = ch;
}
id[4] = 0;
GD2_DBG(php_gd_error("Got file code: %s", id));
/* Equiv. of 'magick'. */
if (strcmp(id, GD2_ID) != 0) {
GD2_DBG(php_gd_error("Not a valid gd2 file"));
goto fail1;
}
/* Version */
if (gdGetWord(vers, in) != 1) {
goto fail1;
}
GD2_DBG(php_gd_error("Version: %d", *vers));
if ((*vers != 1) && (*vers != 2)) {
GD2_DBG(php_gd_error("Bad version: %d", *vers));
goto fail1;
}
/* Image Size */
if (!gdGetWord(sx, in)) {
GD2_DBG(php_gd_error("Could not get x-size"));
goto fail1;
}
if (!gdGetWord(sy, in)) {
GD2_DBG(php_gd_error("Could not get y-size"));
goto fail1;
}
GD2_DBG(php_gd_error("Image is %dx%d", *sx, *sy));
/* Chunk Size (pixels, not bytes!) */
if (gdGetWord(cs, in) != 1) {
goto fail1;
}
GD2_DBG(php_gd_error("ChunkSize: %d", *cs));
if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) {
GD2_DBG(php_gd_error("Bad chunk size: %d", *cs));
goto fail1;
}
/* Data Format */
if (gdGetWord(fmt, in) != 1) {
goto fail1;
}
GD2_DBG(php_gd_error("Format: %d", *fmt));
if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) {
GD2_DBG(php_gd_error("Bad data format: %d", *fmt));
goto fail1;
}
/* # of chunks wide */
if (gdGetWord(ncx, in) != 1) {
goto fail1;
}
GD2_DBG(php_gd_error("%d Chunks Wide", *ncx));
/* # of chunks high */
if (gdGetWord(ncy, in) != 1) {
goto fail1;
}
GD2_DBG(php_gd_error("%d Chunks vertically", *ncy));
if (gd2_compressed(*fmt)) {
nc = (*ncx) * (*ncy);
GD2_DBG(php_gd_error("Reading %d chunk index entries", nc));
sidx = sizeof(t_chunk_info) * nc;
if (sidx <= 0) {
goto fail1;
}
cidx = gdCalloc(sidx, 1);
for (i = 0; i < nc; i++) {
if (gdGetInt(&cidx[i].offset, in) != 1) {
gdFree(cidx);
goto fail1;
}
if (gdGetInt(&cidx[i].size, in) != 1) {
gdFree(cidx);
goto fail1;
}
if (cidx[i].offset < 0 || cidx[i].size < 0) {
gdFree(cidx);
goto fail1;
}
}
*chunkIdx = cidx;
}
GD2_DBG(php_gd_error("gd2 header complete"));
return 1;
fail1:
return 0;
}
Commit Message: Fixed #72339 Integer Overflow in _gd2GetHeader() resulting in heap overflow
CWE ID: CWE-190 | static int _gd2GetHeader(gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx)
{
int i;
int ch;
char id[5];
t_chunk_info *cidx;
int sidx;
int nc;
GD2_DBG(php_gd_error("Reading gd2 header info"));
for (i = 0; i < 4; i++) {
ch = gdGetC(in);
if (ch == EOF) {
goto fail1;
}
id[i] = ch;
}
id[4] = 0;
GD2_DBG(php_gd_error("Got file code: %s", id));
/* Equiv. of 'magick'. */
if (strcmp(id, GD2_ID) != 0) {
GD2_DBG(php_gd_error("Not a valid gd2 file"));
goto fail1;
}
/* Version */
if (gdGetWord(vers, in) != 1) {
goto fail1;
}
GD2_DBG(php_gd_error("Version: %d", *vers));
if ((*vers != 1) && (*vers != 2)) {
GD2_DBG(php_gd_error("Bad version: %d", *vers));
goto fail1;
}
/* Image Size */
if (!gdGetWord(sx, in)) {
GD2_DBG(php_gd_error("Could not get x-size"));
goto fail1;
}
if (!gdGetWord(sy, in)) {
GD2_DBG(php_gd_error("Could not get y-size"));
goto fail1;
}
GD2_DBG(php_gd_error("Image is %dx%d", *sx, *sy));
/* Chunk Size (pixels, not bytes!) */
if (gdGetWord(cs, in) != 1) {
goto fail1;
}
GD2_DBG(php_gd_error("ChunkSize: %d", *cs));
if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) {
GD2_DBG(php_gd_error("Bad chunk size: %d", *cs));
goto fail1;
}
/* Data Format */
if (gdGetWord(fmt, in) != 1) {
goto fail1;
}
GD2_DBG(php_gd_error("Format: %d", *fmt));
if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) {
GD2_DBG(php_gd_error("Bad data format: %d", *fmt));
goto fail1;
}
/* # of chunks wide */
if (gdGetWord(ncx, in) != 1) {
goto fail1;
}
GD2_DBG(php_gd_error("%d Chunks Wide", *ncx));
/* # of chunks high */
if (gdGetWord(ncy, in) != 1) {
goto fail1;
}
GD2_DBG(php_gd_error("%d Chunks vertically", *ncy));
if (gd2_compressed(*fmt)) {
nc = (*ncx) * (*ncy);
GD2_DBG(php_gd_error("Reading %d chunk index entries", nc));
if (overflow2(sidx, nc)) {
goto fail1;
}
sidx = sizeof(t_chunk_info) * nc;
if (sidx <= 0) {
goto fail1;
}
cidx = gdCalloc(sidx, 1);
if (cidx == NULL) {
goto fail1;
}
for (i = 0; i < nc; i++) {
if (gdGetInt(&cidx[i].offset, in) != 1) {
gdFree(cidx);
goto fail1;
}
if (gdGetInt(&cidx[i].size, in) != 1) {
gdFree(cidx);
goto fail1;
}
if (cidx[i].offset < 0 || cidx[i].size < 0) {
gdFree(cidx);
goto fail1;
}
}
*chunkIdx = cidx;
}
GD2_DBG(php_gd_error("gd2 header complete"));
return 1;
fail1:
return 0;
}
| 167,131 |
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: unsigned long long Track::GetUid() const
{
return m_info.uid;
}
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 | unsigned long long Track::GetUid() const
| 174,378 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ExtensionInstallDialogView::InitView() {
int left_column_width =
(prompt_->ShouldShowPermissions() || prompt_->GetRetainedFileCount() > 0)
? kPermissionsLeftColumnWidth
: kNoPermissionsLeftColumnWidth;
if (is_external_install())
left_column_width = kExternalInstallLeftColumnWidth;
int column_set_id = 0;
views::GridLayout* layout = CreateLayout(left_column_width, column_set_id);
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
if (prompt_->has_webstore_data()) {
layout->StartRow(0, column_set_id);
views::View* rating = new views::View();
rating->SetLayoutManager(new views::BoxLayout(
views::BoxLayout::kHorizontal, 0, 0, 0));
layout->AddView(rating);
prompt_->AppendRatingStars(AddResourceIcon, rating);
const gfx::FontList& small_font_list =
rb.GetFontList(ui::ResourceBundle::SmallFont);
views::Label* rating_count =
new views::Label(prompt_->GetRatingCount(), small_font_list);
rating_count->SetBorder(views::Border::CreateEmptyBorder(0, 2, 0, 0));
rating->AddChildView(rating_count);
layout->StartRow(0, column_set_id);
views::Label* user_count =
new views::Label(prompt_->GetUserCount(), small_font_list);
user_count->SetAutoColorReadabilityEnabled(false);
user_count->SetEnabledColor(SK_ColorGRAY);
layout->AddView(user_count);
layout->StartRow(0, column_set_id);
views::Link* store_link = new views::Link(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_STORE_LINK));
store_link->SetFontList(small_font_list);
store_link->set_listener(this);
layout->AddView(store_link);
if (prompt_->ShouldShowPermissions()) {
layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
layout->StartRow(0, column_set_id);
layout->AddView(new views::Separator(views::Separator::HORIZONTAL),
3,
1,
views::GridLayout::FILL,
views::GridLayout::FILL);
}
}
int content_width = left_column_width + views::kPanelHorizMargin + kIconSize;
CustomScrollableView* scrollable = new CustomScrollableView();
views::GridLayout* scroll_layout = new views::GridLayout(scrollable);
scrollable->SetLayoutManager(scroll_layout);
views::ColumnSet* scrollable_column_set =
scroll_layout->AddColumnSet(column_set_id);
int scrollable_width = prompt_->has_webstore_data() ? content_width
: left_column_width;
scrollable_column_set->AddColumn(views::GridLayout::LEADING,
views::GridLayout::LEADING,
0, // no resizing
views::GridLayout::USE_PREF,
scrollable_width,
scrollable_width);
int padding_width =
content_width + views::kButtonHEdgeMarginNew - scrollable_width;
scrollable_column_set->AddPaddingColumn(0, padding_width);
layout->StartRow(0, column_set_id);
scroll_view_ = new views::ScrollView();
scroll_view_->set_hide_horizontal_scrollbar(true);
scroll_view_->SetContents(scrollable);
layout->AddView(scroll_view_, 4, 1);
if (is_bundle_install()) {
BundleInstaller::ItemList items = prompt_->bundle()->GetItemsWithState(
BundleInstaller::Item::STATE_PENDING);
scroll_layout->AddPaddingRow(0, views::kRelatedControlSmallVerticalSpacing);
for (const BundleInstaller::Item& item : items) {
scroll_layout->StartRow(0, column_set_id);
views::Label* extension_label =
new views::Label(item.GetNameForDisplay());
extension_label->SetMultiLine(true);
extension_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
extension_label->SizeToFit(
scrollable_width - kSmallIconSize - kSmallIconPadding);
gfx::ImageSkia image = gfx::ImageSkia::CreateFrom1xBitmap(item.icon);
scroll_layout->AddView(new IconedView(extension_label, image));
}
scroll_layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
}
if (prompt_->ShouldShowPermissions()) {
bool has_permissions =
prompt_->GetPermissionCount(
ExtensionInstallPrompt::PermissionsType::ALL_PERMISSIONS) > 0;
if (has_permissions) {
AddPermissions(
scroll_layout,
rb,
column_set_id,
scrollable_width,
ExtensionInstallPrompt::PermissionsType::REGULAR_PERMISSIONS);
AddPermissions(
scroll_layout,
rb,
column_set_id,
scrollable_width,
ExtensionInstallPrompt::PermissionsType::WITHHELD_PERMISSIONS);
} else {
scroll_layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
scroll_layout->StartRow(0, column_set_id);
views::Label* permission_label = new views::Label(
l10n_util::GetStringUTF16(IDS_EXTENSION_NO_SPECIAL_PERMISSIONS));
permission_label->SetMultiLine(true);
permission_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
permission_label->SizeToFit(scrollable_width);
scroll_layout->AddView(permission_label);
}
}
if (prompt_->GetRetainedFileCount()) {
scroll_layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
scroll_layout->StartRow(0, column_set_id);
views::Label* retained_files_header =
new views::Label(prompt_->GetRetainedFilesHeading());
retained_files_header->SetMultiLine(true);
retained_files_header->SetHorizontalAlignment(gfx::ALIGN_LEFT);
retained_files_header->SizeToFit(scrollable_width);
scroll_layout->AddView(retained_files_header);
scroll_layout->StartRow(0, column_set_id);
PermissionDetails details;
for (size_t i = 0; i < prompt_->GetRetainedFileCount(); ++i) {
details.push_back(prompt_->GetRetainedFile(i));
}
ExpandableContainerView* issue_advice_view =
new ExpandableContainerView(this,
base::string16(),
details,
scrollable_width,
false);
scroll_layout->AddView(issue_advice_view);
}
if (prompt_->GetRetainedDeviceCount()) {
scroll_layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
scroll_layout->StartRow(0, column_set_id);
views::Label* retained_devices_header =
new views::Label(prompt_->GetRetainedDevicesHeading());
retained_devices_header->SetMultiLine(true);
retained_devices_header->SetHorizontalAlignment(gfx::ALIGN_LEFT);
retained_devices_header->SizeToFit(scrollable_width);
scroll_layout->AddView(retained_devices_header);
scroll_layout->StartRow(0, column_set_id);
PermissionDetails details;
for (size_t i = 0; i < prompt_->GetRetainedDeviceCount(); ++i) {
details.push_back(prompt_->GetRetainedDeviceMessageString(i));
}
ExpandableContainerView* issue_advice_view =
new ExpandableContainerView(this,
base::string16(),
details,
scrollable_width,
false);
scroll_layout->AddView(issue_advice_view);
}
DCHECK(prompt_->type() >= 0);
UMA_HISTOGRAM_ENUMERATION("Extensions.InstallPrompt.Type",
prompt_->type(),
ExtensionInstallPrompt::NUM_PROMPT_TYPES);
scroll_view_->ClipHeightTo(
0,
std::min(kScrollViewMaxHeight, scrollable->GetPreferredSize().height()));
dialog_size_ = gfx::Size(
content_width + 2 * views::kButtonHEdgeMarginNew,
container_->GetPreferredSize().height());
std::string event_name = ExperienceSamplingEvent::kExtensionInstallDialog;
event_name.append(
ExtensionInstallPrompt::PromptTypeToString(prompt_->type()));
sampling_event_ = ExperienceSamplingEvent::Create(event_name);
}
Commit Message: Make the webstore inline install dialog be tab-modal
Also clean up a few minor lint errors while I'm in here.
BUG=550047
Review URL: https://codereview.chromium.org/1496033003
Cr-Commit-Position: refs/heads/master@{#363925}
CWE ID: CWE-17 | void ExtensionInstallDialogView::InitView() {
int left_column_width =
(prompt_->ShouldShowPermissions() || prompt_->GetRetainedFileCount() > 0)
? kPermissionsLeftColumnWidth
: kNoPermissionsLeftColumnWidth;
if (is_external_install())
left_column_width = kExternalInstallLeftColumnWidth;
int column_set_id = 0;
views::GridLayout* layout = CreateLayout(left_column_width, column_set_id);
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
if (prompt_->has_webstore_data()) {
layout->StartRow(0, column_set_id);
views::View* rating = new views::View();
rating->SetLayoutManager(new views::BoxLayout(
views::BoxLayout::kHorizontal, 0, 0, 0));
layout->AddView(rating);
prompt_->AppendRatingStars(AddResourceIcon, rating);
const gfx::FontList& small_font_list =
rb.GetFontList(ui::ResourceBundle::SmallFont);
views::Label* rating_count =
new views::Label(prompt_->GetRatingCount(), small_font_list);
rating_count->SetBorder(views::Border::CreateEmptyBorder(0, 2, 0, 0));
rating->AddChildView(rating_count);
layout->StartRow(0, column_set_id);
views::Label* user_count =
new views::Label(prompt_->GetUserCount(), small_font_list);
user_count->SetAutoColorReadabilityEnabled(false);
user_count->SetEnabledColor(SK_ColorGRAY);
layout->AddView(user_count);
layout->StartRow(0, column_set_id);
views::Link* store_link = new views::Link(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_STORE_LINK));
store_link->SetFontList(small_font_list);
store_link->set_listener(this);
layout->AddView(store_link);
if (prompt_->ShouldShowPermissions()) {
layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
layout->StartRow(0, column_set_id);
layout->AddView(new views::Separator(views::Separator::HORIZONTAL),
3,
1,
views::GridLayout::FILL,
views::GridLayout::FILL);
}
}
int content_width = left_column_width + views::kPanelHorizMargin + kIconSize;
CustomScrollableView* scrollable = new CustomScrollableView();
views::GridLayout* scroll_layout = new views::GridLayout(scrollable);
scrollable->SetLayoutManager(scroll_layout);
views::ColumnSet* scrollable_column_set =
scroll_layout->AddColumnSet(column_set_id);
int scrollable_width = prompt_->has_webstore_data() ? content_width
: left_column_width;
scrollable_column_set->AddColumn(views::GridLayout::LEADING,
views::GridLayout::LEADING,
0, // no resizing
views::GridLayout::USE_PREF,
scrollable_width,
scrollable_width);
int padding_width =
content_width + views::kButtonHEdgeMarginNew - scrollable_width;
scrollable_column_set->AddPaddingColumn(0, padding_width);
layout->StartRow(0, column_set_id);
scroll_view_ = new views::ScrollView();
scroll_view_->set_hide_horizontal_scrollbar(true);
scroll_view_->SetContents(scrollable);
layout->AddView(scroll_view_, 4, 1);
if (is_bundle_install()) {
BundleInstaller::ItemList items = prompt_->bundle()->GetItemsWithState(
BundleInstaller::Item::STATE_PENDING);
scroll_layout->AddPaddingRow(0, views::kRelatedControlSmallVerticalSpacing);
for (const BundleInstaller::Item& item : items) {
scroll_layout->StartRow(0, column_set_id);
views::Label* extension_label =
new views::Label(item.GetNameForDisplay());
extension_label->SetMultiLine(true);
extension_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
extension_label->SizeToFit(
scrollable_width - kSmallIconSize - kSmallIconPadding);
gfx::ImageSkia image = gfx::ImageSkia::CreateFrom1xBitmap(item.icon);
scroll_layout->AddView(new IconedView(extension_label, image));
}
scroll_layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
}
if (prompt_->ShouldShowPermissions()) {
bool has_permissions =
prompt_->GetPermissionCount(
ExtensionInstallPrompt::PermissionsType::ALL_PERMISSIONS) > 0;
if (has_permissions) {
AddPermissions(
scroll_layout,
rb,
column_set_id,
scrollable_width,
ExtensionInstallPrompt::PermissionsType::REGULAR_PERMISSIONS);
AddPermissions(
scroll_layout,
rb,
column_set_id,
scrollable_width,
ExtensionInstallPrompt::PermissionsType::WITHHELD_PERMISSIONS);
} else {
scroll_layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
scroll_layout->StartRow(0, column_set_id);
views::Label* permission_label = new views::Label(
l10n_util::GetStringUTF16(IDS_EXTENSION_NO_SPECIAL_PERMISSIONS));
permission_label->SetMultiLine(true);
permission_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
permission_label->SizeToFit(scrollable_width);
scroll_layout->AddView(permission_label);
}
}
if (prompt_->GetRetainedFileCount()) {
scroll_layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
scroll_layout->StartRow(0, column_set_id);
views::Label* retained_files_header =
new views::Label(prompt_->GetRetainedFilesHeading());
retained_files_header->SetMultiLine(true);
retained_files_header->SetHorizontalAlignment(gfx::ALIGN_LEFT);
retained_files_header->SizeToFit(scrollable_width);
scroll_layout->AddView(retained_files_header);
scroll_layout->StartRow(0, column_set_id);
PermissionDetails details;
for (size_t i = 0; i < prompt_->GetRetainedFileCount(); ++i) {
details.push_back(prompt_->GetRetainedFile(i));
}
ExpandableContainerView* issue_advice_view =
new ExpandableContainerView(this,
base::string16(),
details,
scrollable_width,
false);
scroll_layout->AddView(issue_advice_view);
}
if (prompt_->GetRetainedDeviceCount()) {
scroll_layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);
scroll_layout->StartRow(0, column_set_id);
views::Label* retained_devices_header =
new views::Label(prompt_->GetRetainedDevicesHeading());
retained_devices_header->SetMultiLine(true);
retained_devices_header->SetHorizontalAlignment(gfx::ALIGN_LEFT);
retained_devices_header->SizeToFit(scrollable_width);
scroll_layout->AddView(retained_devices_header);
scroll_layout->StartRow(0, column_set_id);
PermissionDetails details;
for (size_t i = 0; i < prompt_->GetRetainedDeviceCount(); ++i) {
details.push_back(prompt_->GetRetainedDeviceMessageString(i));
}
ExpandableContainerView* issue_advice_view =
new ExpandableContainerView(this,
base::string16(),
details,
scrollable_width,
false);
scroll_layout->AddView(issue_advice_view);
}
DCHECK_GE(prompt_->type(), 0);
UMA_HISTOGRAM_ENUMERATION("Extensions.InstallPrompt.Type",
prompt_->type(),
ExtensionInstallPrompt::NUM_PROMPT_TYPES);
scroll_view_->ClipHeightTo(
0,
std::min(kScrollViewMaxHeight, scrollable->GetPreferredSize().height()));
dialog_size_ = gfx::Size(
content_width + 2 * views::kButtonHEdgeMarginNew,
container_->GetPreferredSize().height());
std::string event_name = ExperienceSamplingEvent::kExtensionInstallDialog;
event_name.append(
ExtensionInstallPrompt::PromptTypeToString(prompt_->type()));
sampling_event_ = ExperienceSamplingEvent::Create(event_name);
}
| 172,207 |
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 DocumentThreadableLoader::loadRequest(const ResourceRequest& request, ResourceLoaderOptions resourceLoaderOptions)
{
const KURL& requestURL = request.url();
ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
if (m_forceDoNotAllowStoredCredentials)
resourceLoaderOptions.allowCredentials = DoNotAllowStoredCredentials;
resourceLoaderOptions.securityOrigin = m_securityOrigin;
if (m_async) {
if (!m_actualRequest.isNull())
resourceLoaderOptions.dataBufferingPolicy = BufferData;
if (m_options.timeoutMilliseconds > 0)
m_timeoutTimer.startOneShot(m_options.timeoutMilliseconds / 1000.0, BLINK_FROM_HERE);
FetchRequest newRequest(request, m_options.initiator, resourceLoaderOptions);
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
newRequest.setOriginRestriction(FetchRequest::NoOriginRestriction);
ASSERT(!resource());
if (request.requestContext() == WebURLRequest::RequestContextVideo || request.requestContext() == WebURLRequest::RequestContextAudio)
setResource(RawResource::fetchMedia(newRequest, document().fetcher()));
else if (request.requestContext() == WebURLRequest::RequestContextManifest)
setResource(RawResource::fetchManifest(newRequest, document().fetcher()));
else
setResource(RawResource::fetch(newRequest, document().fetcher()));
if (!resource()) {
InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client);
ThreadableLoaderClient* client = m_client;
clear();
client->didFail(ResourceError(errorDomainBlinkInternal, 0, requestURL.getString(), "Failed to start loading."));
return;
}
if (resource()->loader()) {
unsigned long identifier = resource()->identifier();
InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
} else {
InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client);
}
return;
}
FetchRequest fetchRequest(request, m_options.initiator, resourceLoaderOptions);
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
fetchRequest.setOriginRestriction(FetchRequest::NoOriginRestriction);
Resource* resource = RawResource::fetchSynchronously(fetchRequest, document().fetcher());
ResourceResponse response = resource ? resource->response() : ResourceResponse();
unsigned long identifier = resource ? resource->identifier() : std::numeric_limits<unsigned long>::max();
ResourceError error = resource ? resource->resourceError() : ResourceError();
InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
if (!resource) {
m_client->didFail(error);
return;
}
if (!error.isNull() && !requestURL.isLocalFile() && response.httpStatusCode() <= 0) {
m_client->didFail(error);
return;
}
if (requestURL != response.url() && !isAllowedRedirect(response.url())) {
m_client->didFailRedirectCheck();
return;
}
handleResponse(identifier, response, nullptr);
if (!m_client)
return;
SharedBuffer* data = resource->resourceBuffer();
if (data)
handleReceivedData(data->data(), data->size());
if (!m_client)
return;
handleSuccessfulFinish(identifier, 0.0);
}
Commit Message: DocumentThreadableLoader: Add guards for sync notifyFinished() in setResource()
In loadRequest(), setResource() can call clear() synchronously:
DocumentThreadableLoader::clear()
DocumentThreadableLoader::handleError()
Resource::didAddClient()
RawResource::didAddClient()
and thus |m_client| can be null while resource() isn't null after setResource(),
causing crashes (Issue 595964).
This CL checks whether |*this| is destructed and
whether |m_client| is null after setResource().
BUG=595964
Review-Url: https://codereview.chromium.org/1902683002
Cr-Commit-Position: refs/heads/master@{#391001}
CWE ID: CWE-189 | void DocumentThreadableLoader::loadRequest(const ResourceRequest& request, ResourceLoaderOptions resourceLoaderOptions)
{
const KURL& requestURL = request.url();
ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
if (m_forceDoNotAllowStoredCredentials)
resourceLoaderOptions.allowCredentials = DoNotAllowStoredCredentials;
resourceLoaderOptions.securityOrigin = m_securityOrigin;
if (m_async) {
if (!m_actualRequest.isNull())
resourceLoaderOptions.dataBufferingPolicy = BufferData;
if (m_options.timeoutMilliseconds > 0)
m_timeoutTimer.startOneShot(m_options.timeoutMilliseconds / 1000.0, BLINK_FROM_HERE);
FetchRequest newRequest(request, m_options.initiator, resourceLoaderOptions);
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
newRequest.setOriginRestriction(FetchRequest::NoOriginRestriction);
ASSERT(!resource());
WeakPtr<DocumentThreadableLoader> self(m_weakFactory.createWeakPtr());
if (request.requestContext() == WebURLRequest::RequestContextVideo || request.requestContext() == WebURLRequest::RequestContextAudio)
setResource(RawResource::fetchMedia(newRequest, document().fetcher()));
else if (request.requestContext() == WebURLRequest::RequestContextManifest)
setResource(RawResource::fetchManifest(newRequest, document().fetcher()));
else
setResource(RawResource::fetch(newRequest, document().fetcher()));
// setResource() might call notifyFinished() synchronously, and thus
// clear() might be called and |this| may be dead here.
if (!self)
return;
if (!resource()) {
InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client);
ThreadableLoaderClient* client = m_client;
clear();
// setResource() might call notifyFinished() and thus clear()
// synchronously, and in such cases ThreadableLoaderClient is
// already notified and |client| is null.
if (!client)
return;
client->didFail(ResourceError(errorDomainBlinkInternal, 0, requestURL.getString(), "Failed to start loading."));
return;
}
if (resource()->loader()) {
unsigned long identifier = resource()->identifier();
InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
} else {
InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client);
}
return;
}
FetchRequest fetchRequest(request, m_options.initiator, resourceLoaderOptions);
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
fetchRequest.setOriginRestriction(FetchRequest::NoOriginRestriction);
Resource* resource = RawResource::fetchSynchronously(fetchRequest, document().fetcher());
ResourceResponse response = resource ? resource->response() : ResourceResponse();
unsigned long identifier = resource ? resource->identifier() : std::numeric_limits<unsigned long>::max();
ResourceError error = resource ? resource->resourceError() : ResourceError();
InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
if (!resource) {
m_client->didFail(error);
return;
}
if (!error.isNull() && !requestURL.isLocalFile() && response.httpStatusCode() <= 0) {
m_client->didFail(error);
return;
}
if (requestURL != response.url() && !isAllowedRedirect(response.url())) {
m_client->didFailRedirectCheck();
return;
}
handleResponse(identifier, response, nullptr);
if (!m_client)
return;
SharedBuffer* data = resource->resourceBuffer();
if (data)
handleReceivedData(data->data(), data->size());
if (!m_client)
return;
handleSuccessfulFinish(identifier, 0.0);
}
| 171,612 |
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 MagickBooleanType ContrastStretchImage(Image *image,
const double black_point,const double white_point,ExceptionInfo *exception)
{
#define MaxRange(color) ((double) ScaleQuantumToMap((Quantum) (color)))
#define ContrastStretchImageTag "ContrastStretch/Image"
CacheView
*image_view;
double
*black,
*histogram,
*stretch_map,
*white;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Allocate histogram and stretch map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageGray(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace,exception);
black=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*black));
white=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*white));
histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)*
sizeof(*histogram));
stretch_map=(double *) AcquireQuantumMemory(MaxMap+1UL,
GetPixelChannels(image)*sizeof(*stretch_map));
if ((black == (double *) NULL) || (white == (double *) NULL) ||
(histogram == (double *) NULL) || (stretch_map == (double *) NULL))
{
if (stretch_map != (double *) NULL)
stretch_map=(double *) RelinquishMagickMemory(stretch_map);
if (histogram != (double *) NULL)
histogram=(double *) RelinquishMagickMemory(histogram);
if (white != (double *) NULL)
white=(double *) RelinquishMagickMemory(white);
if (black != (double *) NULL)
black=(double *) RelinquishMagickMemory(black);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
/*
Form histogram.
*/
status=MagickTrue;
(void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*histogram));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
pixel=GetPixelIntensity(image,p);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
if (image->channel_mask != DefaultChannels)
pixel=(double) p[i];
histogram[GetPixelChannels(image)*ScaleQuantumToMap(
ClampToQuantum(pixel))+i]++;
}
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
/*
Find the histogram boundaries by locating the black/white levels.
*/
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
intensity;
register ssize_t
j;
black[i]=0.0;
white[i]=MaxRange(QuantumRange);
intensity=0.0;
for (j=0; j <= (ssize_t) MaxMap; j++)
{
intensity+=histogram[GetPixelChannels(image)*j+i];
if (intensity > black_point)
break;
}
black[i]=(double) j;
intensity=0.0;
for (j=(ssize_t) MaxMap; j != 0; j--)
{
intensity+=histogram[GetPixelChannels(image)*j+i];
if (intensity > ((double) image->columns*image->rows-white_point))
break;
}
white[i]=(double) j;
}
histogram=(double *) RelinquishMagickMemory(histogram);
/*
Stretch the histogram to create the stretched image mapping.
*/
(void) ResetMagickMemory(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*stretch_map));
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
register ssize_t
j;
for (j=0; j <= (ssize_t) MaxMap; j++)
{
double
gamma;
gamma=PerceptibleReciprocal(white[i]-black[i]);
if (j < (ssize_t) black[i])
stretch_map[GetPixelChannels(image)*j+i]=0.0;
else
if (j > (ssize_t) white[i])
stretch_map[GetPixelChannels(image)*j+i]=(double) QuantumRange;
else
if (black[i] != white[i])
stretch_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum(
(double) (MaxMap*gamma*(j-black[i])));
}
}
if (image->storage_class == PseudoClass)
{
register ssize_t
j;
/*
Stretch-contrast colormap.
*/
for (j=0; j < (ssize_t) image->colors; j++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,RedPixelChannel);
image->colormap[j].red=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+i];
}
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,GreenPixelChannel);
image->colormap[j].green=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+i];
}
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,BluePixelChannel);
image->colormap[j].blue=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+i];
}
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,AlphaPixelChannel);
image->colormap[j].alpha=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+i];
}
}
}
/*
Stretch-contrast image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
if (GetPixelWriteMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel=GetPixelChannelChannel(image,j);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (black[j] == white[j])
continue;
q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(q[j])+j]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ContrastStretchImage)
#endif
proceed=SetImageProgress(image,ContrastStretchImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
stretch_map=(double *) RelinquishMagickMemory(stretch_map);
white=(double *) RelinquishMagickMemory(white);
black=(double *) RelinquishMagickMemory(black);
return(status);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/663
https://github.com/ImageMagick/ImageMagick/issues/655
CWE ID: CWE-119 | MagickExport MagickBooleanType ContrastStretchImage(Image *image,
const double black_point,const double white_point,ExceptionInfo *exception)
{
#define MaxRange(color) ((double) ScaleQuantumToMap((Quantum) (color)))
#define ContrastStretchImageTag "ContrastStretch/Image"
CacheView
*image_view;
double
*black,
*histogram,
*stretch_map,
*white;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Allocate histogram and stretch map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SyncImagePixelCache(image,exception) == MagickFalse)
return(MagickFalse);
if (SetImageGray(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace,exception);
black=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*black));
white=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*white));
histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)*
sizeof(*histogram));
stretch_map=(double *) AcquireQuantumMemory(MaxMap+1UL,
GetPixelChannels(image)*sizeof(*stretch_map));
if ((black == (double *) NULL) || (white == (double *) NULL) ||
(histogram == (double *) NULL) || (stretch_map == (double *) NULL))
{
if (stretch_map != (double *) NULL)
stretch_map=(double *) RelinquishMagickMemory(stretch_map);
if (histogram != (double *) NULL)
histogram=(double *) RelinquishMagickMemory(histogram);
if (white != (double *) NULL)
white=(double *) RelinquishMagickMemory(white);
if (black != (double *) NULL)
black=(double *) RelinquishMagickMemory(black);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
/*
Form histogram.
*/
status=MagickTrue;
(void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*histogram));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
pixel=GetPixelIntensity(image,p);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
if (image->channel_mask != DefaultChannels)
pixel=(double) p[i];
histogram[GetPixelChannels(image)*ScaleQuantumToMap(
ClampToQuantum(pixel))+i]++;
}
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
/*
Find the histogram boundaries by locating the black/white levels.
*/
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
intensity;
register ssize_t
j;
black[i]=0.0;
white[i]=MaxRange(QuantumRange);
intensity=0.0;
for (j=0; j <= (ssize_t) MaxMap; j++)
{
intensity+=histogram[GetPixelChannels(image)*j+i];
if (intensity > black_point)
break;
}
black[i]=(double) j;
intensity=0.0;
for (j=(ssize_t) MaxMap; j != 0; j--)
{
intensity+=histogram[GetPixelChannels(image)*j+i];
if (intensity > ((double) image->columns*image->rows-white_point))
break;
}
white[i]=(double) j;
}
histogram=(double *) RelinquishMagickMemory(histogram);
/*
Stretch the histogram to create the stretched image mapping.
*/
(void) ResetMagickMemory(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*stretch_map));
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
register ssize_t
j;
for (j=0; j <= (ssize_t) MaxMap; j++)
{
double
gamma;
gamma=PerceptibleReciprocal(white[i]-black[i]);
if (j < (ssize_t) black[i])
stretch_map[GetPixelChannels(image)*j+i]=0.0;
else
if (j > (ssize_t) white[i])
stretch_map[GetPixelChannels(image)*j+i]=(double) QuantumRange;
else
if (black[i] != white[i])
stretch_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum(
(double) (MaxMap*gamma*(j-black[i])));
}
}
if (image->storage_class == PseudoClass)
{
register ssize_t
j;
/*
Stretch-contrast colormap.
*/
for (j=0; j < (ssize_t) image->colors; j++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,RedPixelChannel);
image->colormap[j].red=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+i];
}
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,GreenPixelChannel);
image->colormap[j].green=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+i];
}
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,BluePixelChannel);
image->colormap[j].blue=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+i];
}
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,AlphaPixelChannel);
image->colormap[j].alpha=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+i];
}
}
}
/*
Stretch-contrast image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
if (GetPixelWriteMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel=GetPixelChannelChannel(image,j);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (black[j] == white[j])
continue;
q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(q[j])+j]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ContrastStretchImage)
#endif
proceed=SetImageProgress(image,ContrastStretchImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
stretch_map=(double *) RelinquishMagickMemory(stretch_map);
white=(double *) RelinquishMagickMemory(white);
black=(double *) RelinquishMagickMemory(black);
return(status);
}
| 167,963 |
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: qboolean S_AL_Init( soundInterface_t *si )
{
#ifdef USE_OPENAL
const char* device = NULL;
const char* inputdevice = NULL;
int i;
if( !si ) {
return qfalse;
}
for (i = 0; i < MAX_RAW_STREAMS; i++) {
streamSourceHandles[i] = -1;
streamPlaying[i] = qfalse;
streamSources[i] = 0;
streamNumBuffers[i] = 0;
streamBufIndex[i] = 0;
}
s_alPrecache = Cvar_Get( "s_alPrecache", "1", CVAR_ARCHIVE );
s_alGain = Cvar_Get( "s_alGain", "1.0", CVAR_ARCHIVE );
s_alSources = Cvar_Get( "s_alSources", "96", CVAR_ARCHIVE );
s_alDopplerFactor = Cvar_Get( "s_alDopplerFactor", "1.0", CVAR_ARCHIVE );
s_alDopplerSpeed = Cvar_Get( "s_alDopplerSpeed", "9000", CVAR_ARCHIVE );
s_alMinDistance = Cvar_Get( "s_alMinDistance", "120", CVAR_CHEAT );
s_alMaxDistance = Cvar_Get("s_alMaxDistance", "1024", CVAR_CHEAT);
s_alRolloff = Cvar_Get( "s_alRolloff", "2", CVAR_CHEAT);
s_alGraceDistance = Cvar_Get("s_alGraceDistance", "512", CVAR_CHEAT);
s_alDriver = Cvar_Get( "s_alDriver", ALDRIVER_DEFAULT, CVAR_ARCHIVE | CVAR_LATCH );
s_alInputDevice = Cvar_Get( "s_alInputDevice", "", CVAR_ARCHIVE | CVAR_LATCH );
s_alDevice = Cvar_Get("s_alDevice", "", CVAR_ARCHIVE | CVAR_LATCH);
if( !QAL_Init( s_alDriver->string ) )
{
Com_Printf( "Failed to load library: \"%s\".\n", s_alDriver->string );
if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) || !QAL_Init( ALDRIVER_DEFAULT ) ) {
return qfalse;
}
}
device = s_alDevice->string;
if(device && !*device)
device = NULL;
inputdevice = s_alInputDevice->string;
if(inputdevice && !*inputdevice)
inputdevice = NULL;
enumeration_all_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATE_ALL_EXT");
enumeration_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT");
if(enumeration_ext || enumeration_all_ext)
{
char devicenames[16384] = "";
const char *devicelist;
#ifdef _WIN32
const char *defaultdevice;
#endif
int curlen;
if(enumeration_all_ext)
{
devicelist = qalcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
#ifdef _WIN32
defaultdevice = qalcGetString(NULL, ALC_DEFAULT_ALL_DEVICES_SPECIFIER);
#endif
}
else
{
devicelist = qalcGetString(NULL, ALC_DEVICE_SPECIFIER);
#ifdef _WIN32
defaultdevice = qalcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
#endif
enumeration_ext = qtrue;
}
#ifdef _WIN32
if(!device && defaultdevice && !strcmp(defaultdevice, "Generic Hardware"))
device = "Generic Software";
#endif
if(devicelist)
{
while((curlen = strlen(devicelist)))
{
Q_strcat(devicenames, sizeof(devicenames), devicelist);
Q_strcat(devicenames, sizeof(devicenames), "\n");
devicelist += curlen + 1;
}
}
s_alAvailableDevices = Cvar_Get("s_alAvailableDevices", devicenames, CVAR_ROM | CVAR_NORESTART);
}
alDevice = qalcOpenDevice(device);
if( !alDevice && device )
{
Com_Printf( "Failed to open OpenAL device '%s', trying default.\n", device );
alDevice = qalcOpenDevice(NULL);
}
if( !alDevice )
{
QAL_Shutdown( );
Com_Printf( "Failed to open OpenAL device.\n" );
return qfalse;
}
alContext = qalcCreateContext( alDevice, NULL );
if( !alContext )
{
QAL_Shutdown( );
qalcCloseDevice( alDevice );
Com_Printf( "Failed to create OpenAL context.\n" );
return qfalse;
}
qalcMakeContextCurrent( alContext );
S_AL_BufferInit( );
S_AL_SrcInit( );
qalDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
qalDopplerFactor( s_alDopplerFactor->value );
qalSpeedOfSound( s_alDopplerSpeed->value );
#ifdef USE_VOIP
s_alCapture = Cvar_Get( "s_alCapture", "1", CVAR_ARCHIVE | CVAR_LATCH );
if (!s_alCapture->integer)
{
Com_Printf("OpenAL capture support disabled by user ('+set s_alCapture 1' to enable)\n");
}
#if USE_MUMBLE
else if (cl_useMumble->integer)
{
Com_Printf("OpenAL capture support disabled for Mumble support\n");
}
#endif
else
{
#ifdef __APPLE__
if (qalcCaptureOpenDevice == NULL)
#else
if (!qalcIsExtensionPresent(NULL, "ALC_EXT_capture"))
#endif
{
Com_Printf("No ALC_EXT_capture support, can't record audio.\n");
}
else
{
char inputdevicenames[16384] = "";
const char *inputdevicelist;
const char *defaultinputdevice;
int curlen;
capture_ext = qtrue;
inputdevicelist = qalcGetString(NULL, ALC_CAPTURE_DEVICE_SPECIFIER);
defaultinputdevice = qalcGetString(NULL, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER);
if (inputdevicelist)
{
while((curlen = strlen(inputdevicelist)))
{
Q_strcat(inputdevicenames, sizeof(inputdevicenames), inputdevicelist);
Q_strcat(inputdevicenames, sizeof(inputdevicenames), "\n");
inputdevicelist += curlen + 1;
}
}
s_alAvailableInputDevices = Cvar_Get("s_alAvailableInputDevices", inputdevicenames, CVAR_ROM | CVAR_NORESTART);
Com_Printf("OpenAL default capture device is '%s'\n", defaultinputdevice ? defaultinputdevice : "none");
alCaptureDevice = qalcCaptureOpenDevice(inputdevice, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
if( !alCaptureDevice && inputdevice )
{
Com_Printf( "Failed to open OpenAL Input device '%s', trying default.\n", inputdevice );
alCaptureDevice = qalcCaptureOpenDevice(NULL, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
}
Com_Printf( "OpenAL capture device %s.\n",
(alCaptureDevice == NULL) ? "failed to open" : "opened");
}
}
#endif
si->Shutdown = S_AL_Shutdown;
si->StartSound = S_AL_StartSound;
si->StartLocalSound = S_AL_StartLocalSound;
si->StartBackgroundTrack = S_AL_StartBackgroundTrack;
si->StopBackgroundTrack = S_AL_StopBackgroundTrack;
si->RawSamples = S_AL_RawSamples;
si->StopAllSounds = S_AL_StopAllSounds;
si->ClearLoopingSounds = S_AL_ClearLoopingSounds;
si->AddLoopingSound = S_AL_AddLoopingSound;
si->AddRealLoopingSound = S_AL_AddRealLoopingSound;
si->StopLoopingSound = S_AL_StopLoopingSound;
si->Respatialize = S_AL_Respatialize;
si->UpdateEntityPosition = S_AL_UpdateEntityPosition;
si->Update = S_AL_Update;
si->DisableSounds = S_AL_DisableSounds;
si->BeginRegistration = S_AL_BeginRegistration;
si->RegisterSound = S_AL_RegisterSound;
si->ClearSoundBuffer = S_AL_ClearSoundBuffer;
si->SoundInfo = S_AL_SoundInfo;
si->SoundList = S_AL_SoundList;
#ifdef USE_VOIP
si->StartCapture = S_AL_StartCapture;
si->AvailableCaptureSamples = S_AL_AvailableCaptureSamples;
si->Capture = S_AL_Capture;
si->StopCapture = S_AL_StopCapture;
si->MasterGain = S_AL_MasterGain;
#endif
return qtrue;
#else
return qfalse;
#endif
}
Commit Message: Don't open .pk3 files as OpenAL drivers.
CWE ID: CWE-269 | qboolean S_AL_Init( soundInterface_t *si )
{
#ifdef USE_OPENAL
const char* device = NULL;
const char* inputdevice = NULL;
int i;
if( !si ) {
return qfalse;
}
for (i = 0; i < MAX_RAW_STREAMS; i++) {
streamSourceHandles[i] = -1;
streamPlaying[i] = qfalse;
streamSources[i] = 0;
streamNumBuffers[i] = 0;
streamBufIndex[i] = 0;
}
s_alPrecache = Cvar_Get( "s_alPrecache", "1", CVAR_ARCHIVE );
s_alGain = Cvar_Get( "s_alGain", "1.0", CVAR_ARCHIVE );
s_alSources = Cvar_Get( "s_alSources", "96", CVAR_ARCHIVE );
s_alDopplerFactor = Cvar_Get( "s_alDopplerFactor", "1.0", CVAR_ARCHIVE );
s_alDopplerSpeed = Cvar_Get( "s_alDopplerSpeed", "9000", CVAR_ARCHIVE );
s_alMinDistance = Cvar_Get( "s_alMinDistance", "120", CVAR_CHEAT );
s_alMaxDistance = Cvar_Get("s_alMaxDistance", "1024", CVAR_CHEAT);
s_alRolloff = Cvar_Get( "s_alRolloff", "2", CVAR_CHEAT);
s_alGraceDistance = Cvar_Get("s_alGraceDistance", "512", CVAR_CHEAT);
s_alDriver = Cvar_Get( "s_alDriver", ALDRIVER_DEFAULT, CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED );
s_alInputDevice = Cvar_Get( "s_alInputDevice", "", CVAR_ARCHIVE | CVAR_LATCH );
s_alDevice = Cvar_Get("s_alDevice", "", CVAR_ARCHIVE | CVAR_LATCH);
if ( COM_CompareExtension( s_alDriver->string, ".pk3" ) )
{
Com_Printf( "Rejecting DLL named \"%s\"", s_alDriver->string );
return qfalse;
}
if( !QAL_Init( s_alDriver->string ) )
{
Com_Printf( "Failed to load library: \"%s\".\n", s_alDriver->string );
if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) || !QAL_Init( ALDRIVER_DEFAULT ) ) {
return qfalse;
}
}
device = s_alDevice->string;
if(device && !*device)
device = NULL;
inputdevice = s_alInputDevice->string;
if(inputdevice && !*inputdevice)
inputdevice = NULL;
enumeration_all_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATE_ALL_EXT");
enumeration_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT");
if(enumeration_ext || enumeration_all_ext)
{
char devicenames[16384] = "";
const char *devicelist;
#ifdef _WIN32
const char *defaultdevice;
#endif
int curlen;
if(enumeration_all_ext)
{
devicelist = qalcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
#ifdef _WIN32
defaultdevice = qalcGetString(NULL, ALC_DEFAULT_ALL_DEVICES_SPECIFIER);
#endif
}
else
{
devicelist = qalcGetString(NULL, ALC_DEVICE_SPECIFIER);
#ifdef _WIN32
defaultdevice = qalcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
#endif
enumeration_ext = qtrue;
}
#ifdef _WIN32
if(!device && defaultdevice && !strcmp(defaultdevice, "Generic Hardware"))
device = "Generic Software";
#endif
if(devicelist)
{
while((curlen = strlen(devicelist)))
{
Q_strcat(devicenames, sizeof(devicenames), devicelist);
Q_strcat(devicenames, sizeof(devicenames), "\n");
devicelist += curlen + 1;
}
}
s_alAvailableDevices = Cvar_Get("s_alAvailableDevices", devicenames, CVAR_ROM | CVAR_NORESTART);
}
alDevice = qalcOpenDevice(device);
if( !alDevice && device )
{
Com_Printf( "Failed to open OpenAL device '%s', trying default.\n", device );
alDevice = qalcOpenDevice(NULL);
}
if( !alDevice )
{
QAL_Shutdown( );
Com_Printf( "Failed to open OpenAL device.\n" );
return qfalse;
}
alContext = qalcCreateContext( alDevice, NULL );
if( !alContext )
{
QAL_Shutdown( );
qalcCloseDevice( alDevice );
Com_Printf( "Failed to create OpenAL context.\n" );
return qfalse;
}
qalcMakeContextCurrent( alContext );
S_AL_BufferInit( );
S_AL_SrcInit( );
qalDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
qalDopplerFactor( s_alDopplerFactor->value );
qalSpeedOfSound( s_alDopplerSpeed->value );
#ifdef USE_VOIP
s_alCapture = Cvar_Get( "s_alCapture", "1", CVAR_ARCHIVE | CVAR_LATCH );
if (!s_alCapture->integer)
{
Com_Printf("OpenAL capture support disabled by user ('+set s_alCapture 1' to enable)\n");
}
#if USE_MUMBLE
else if (cl_useMumble->integer)
{
Com_Printf("OpenAL capture support disabled for Mumble support\n");
}
#endif
else
{
#ifdef __APPLE__
if (qalcCaptureOpenDevice == NULL)
#else
if (!qalcIsExtensionPresent(NULL, "ALC_EXT_capture"))
#endif
{
Com_Printf("No ALC_EXT_capture support, can't record audio.\n");
}
else
{
char inputdevicenames[16384] = "";
const char *inputdevicelist;
const char *defaultinputdevice;
int curlen;
capture_ext = qtrue;
inputdevicelist = qalcGetString(NULL, ALC_CAPTURE_DEVICE_SPECIFIER);
defaultinputdevice = qalcGetString(NULL, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER);
if (inputdevicelist)
{
while((curlen = strlen(inputdevicelist)))
{
Q_strcat(inputdevicenames, sizeof(inputdevicenames), inputdevicelist);
Q_strcat(inputdevicenames, sizeof(inputdevicenames), "\n");
inputdevicelist += curlen + 1;
}
}
s_alAvailableInputDevices = Cvar_Get("s_alAvailableInputDevices", inputdevicenames, CVAR_ROM | CVAR_NORESTART);
Com_Printf("OpenAL default capture device is '%s'\n", defaultinputdevice ? defaultinputdevice : "none");
alCaptureDevice = qalcCaptureOpenDevice(inputdevice, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
if( !alCaptureDevice && inputdevice )
{
Com_Printf( "Failed to open OpenAL Input device '%s', trying default.\n", inputdevice );
alCaptureDevice = qalcCaptureOpenDevice(NULL, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
}
Com_Printf( "OpenAL capture device %s.\n",
(alCaptureDevice == NULL) ? "failed to open" : "opened");
}
}
#endif
si->Shutdown = S_AL_Shutdown;
si->StartSound = S_AL_StartSound;
si->StartLocalSound = S_AL_StartLocalSound;
si->StartBackgroundTrack = S_AL_StartBackgroundTrack;
si->StopBackgroundTrack = S_AL_StopBackgroundTrack;
si->RawSamples = S_AL_RawSamples;
si->StopAllSounds = S_AL_StopAllSounds;
si->ClearLoopingSounds = S_AL_ClearLoopingSounds;
si->AddLoopingSound = S_AL_AddLoopingSound;
si->AddRealLoopingSound = S_AL_AddRealLoopingSound;
si->StopLoopingSound = S_AL_StopLoopingSound;
si->Respatialize = S_AL_Respatialize;
si->UpdateEntityPosition = S_AL_UpdateEntityPosition;
si->Update = S_AL_Update;
si->DisableSounds = S_AL_DisableSounds;
si->BeginRegistration = S_AL_BeginRegistration;
si->RegisterSound = S_AL_RegisterSound;
si->ClearSoundBuffer = S_AL_ClearSoundBuffer;
si->SoundInfo = S_AL_SoundInfo;
si->SoundList = S_AL_SoundList;
#ifdef USE_VOIP
si->StartCapture = S_AL_StartCapture;
si->AvailableCaptureSamples = S_AL_AvailableCaptureSamples;
si->Capture = S_AL_Capture;
si->StopCapture = S_AL_StopCapture;
si->MasterGain = S_AL_MasterGain;
#endif
return qtrue;
#else
return qfalse;
#endif
}
| 170,078 |
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 ChromePluginServiceFilter::IsPluginEnabled(
int render_process_id,
int render_view_id,
const void* context,
const GURL& url,
const GURL& policy_url,
webkit::WebPluginInfo* plugin) {
base::AutoLock auto_lock(lock_);
const ProcessDetails* details = GetProcess(render_process_id);
if (details) {
for (size_t i = 0; i < details->overridden_plugins.size(); ++i) {
if (details->overridden_plugins[i].render_view_id == render_view_id &&
(details->overridden_plugins[i].url == url ||
details->overridden_plugins[i].url.is_empty())) {
bool use = details->overridden_plugins[i].plugin.path == plugin->path;
if (!use)
return false;
*plugin = details->overridden_plugins[i].plugin;
break;
}
}
}
ResourceContextMap::iterator prefs_it =
resource_context_map_.find(context);
if (prefs_it == resource_context_map_.end())
return false;
PluginPrefs* plugin_prefs = prefs_it->second.get();
if (!plugin_prefs->IsPluginEnabled(*plugin))
return false;
RestrictedPluginMap::const_iterator it =
restricted_plugins_.find(plugin->path);
if (it != restricted_plugins_.end()) {
if (it->second.first != plugin_prefs)
return false;
const GURL& origin = it->second.second;
if (!origin.is_empty() &&
(policy_url.scheme() != origin.scheme() ||
policy_url.host() != origin.host() ||
policy_url.port() != origin.port())) {
return false;
}
}
return true;
}
Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/
BUG=172573
Review URL: https://codereview.chromium.org/12177018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-287 | bool ChromePluginServiceFilter::IsPluginEnabled(
bool ChromePluginServiceFilter::IsPluginAvailable(
int render_process_id,
int render_view_id,
const void* context,
const GURL& url,
const GURL& policy_url,
webkit::WebPluginInfo* plugin) {
base::AutoLock auto_lock(lock_);
const ProcessDetails* details = GetProcess(render_process_id);
if (details) {
for (size_t i = 0; i < details->overridden_plugins.size(); ++i) {
if (details->overridden_plugins[i].render_view_id == render_view_id &&
(details->overridden_plugins[i].url == url ||
details->overridden_plugins[i].url.is_empty())) {
bool use = details->overridden_plugins[i].plugin.path == plugin->path;
if (use)
*plugin = details->overridden_plugins[i].plugin;
return use;
}
}
}
ResourceContextMap::iterator prefs_it =
resource_context_map_.find(context);
if (prefs_it == resource_context_map_.end())
return false;
PluginPrefs* plugin_prefs = prefs_it->second.get();
if (!plugin_prefs->IsPluginEnabled(*plugin))
return false;
RestrictedPluginMap::const_iterator it =
restricted_plugins_.find(plugin->path);
if (it != restricted_plugins_.end()) {
if (it->second.first != plugin_prefs)
return false;
const GURL& origin = it->second.second;
if (!origin.is_empty() &&
(policy_url.scheme() != origin.scheme() ||
policy_url.host() != origin.host() ||
policy_url.port() != origin.port())) {
return false;
}
}
return true;
}
| 171,470 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ShellContentUtilityClient::ShellContentUtilityClient() {
if (base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kProcessType) == switches::kUtilityProcess)
network_service_test_helper_ = std::make_unique<NetworkServiceTestHelper>();
}
Commit Message: Fix content_shell with network service enabled not loading pages.
This regressed in my earlier cl r528763.
This is a reland of r547221.
Bug: 833612
Change-Id: I4c2649414d42773f2530e1abe5912a04fcd0ed9b
Reviewed-on: https://chromium-review.googlesource.com/1064702
Reviewed-by: Jay Civelli <[email protected]>
Commit-Queue: John Abd-El-Malek <[email protected]>
Cr-Commit-Position: refs/heads/master@{#560011}
CWE ID: CWE-264 | ShellContentUtilityClient::ShellContentUtilityClient() {
ShellContentUtilityClient::ShellContentUtilityClient(bool is_browsertest) {
if (is_browsertest &&
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kProcessType) == switches::kUtilityProcess) {
network_service_test_helper_ = std::make_unique<NetworkServiceTestHelper>();
}
}
| 172,122 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(radius_get_vendor_attr)
{
int res;
const void *data;
int len;
u_int32_t vendor;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &data, &len) == FAILURE) {
return;
}
res = rad_get_vendor_attr(&vendor, &data, (size_t *) &len);
if (res == -1) {
RETURN_FALSE;
} else {
array_init(return_value);
add_assoc_long(return_value, "attr", res);
add_assoc_long(return_value, "vendor", vendor);
add_assoc_stringl(return_value, "data", (char *) data, len, 1);
return;
}
}
Commit Message: Fix a security issue in radius_get_vendor_attr().
The underlying rad_get_vendor_attr() function assumed that it would always be
given valid VSA data. Indeed, the buffer length wasn't even passed in; the
assumption was that the length field within the VSA structure would be valid.
This could result in denial of service by providing a length that would be
beyond the memory limit, or potential arbitrary memory access by providing a
length greater than the actual data given.
rad_get_vendor_attr() has been changed to require the raw data length be
provided, and this is then used to check that the VSA is valid.
Conflicts:
radlib_vs.h
CWE ID: CWE-119 | PHP_FUNCTION(radius_get_vendor_attr)
{
const void *data, *raw;
int len;
u_int32_t vendor;
unsigned char type;
size_t data_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &raw, &len) == FAILURE) {
return;
}
if (rad_get_vendor_attr(&vendor, &type, &data, &data_len, raw, len) == -1) {
RETURN_FALSE;
} else {
array_init(return_value);
add_assoc_long(return_value, "attr", type);
add_assoc_long(return_value, "vendor", vendor);
add_assoc_stringl(return_value, "data", (char *) data, data_len, 1);
return;
}
}
| 166,077 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ut64 MACH0_(get_main)(struct MACH0_(obj_t)* bin) {
ut64 addr = 0LL;
struct symbol_t *symbols;
int i;
if (!(symbols = MACH0_(get_symbols) (bin))) {
return 0;
}
for (i = 0; !symbols[i].last; i++) {
if (!strcmp (symbols[i].name, "_main")) {
addr = symbols[i].addr;
break;
}
}
free (symbols);
if (!addr && bin->main_cmd.cmd == LC_MAIN) {
addr = bin->entry + bin->baddr;
}
if (!addr) {
ut8 b[128];
ut64 entry = addr_to_offset(bin, bin->entry);
if (entry > bin->size || entry + sizeof (b) > bin->size)
return 0;
i = r_buf_read_at (bin->b, entry, b, sizeof (b));
if (i < 1) {
return 0;
}
for (i = 0; i < 64; i++) {
if (b[i] == 0xe8 && !b[i+3] && !b[i+4]) {
int delta = b[i+1] | (b[i+2] << 8) | (b[i+3] << 16) | (b[i+4] << 24);
return bin->entry + i + 5 + delta;
}
}
}
return addr;
}
Commit Message: Fix null deref and uaf in mach0 parser
CWE ID: CWE-416 | ut64 MACH0_(get_main)(struct MACH0_(obj_t)* bin) {
ut64 addr = 0LL;
struct symbol_t *symbols;
int i;
if (!(symbols = MACH0_(get_symbols) (bin))) {
return 0;
}
for (i = 0; !symbols[i].last; i++) {
if (!strcmp (symbols[i].name, "_main")) {
addr = symbols[i].addr;
break;
}
}
free (symbols);
if (!addr && bin->main_cmd.cmd == LC_MAIN) {
addr = bin->entry + bin->baddr;
}
if (!addr) {
ut8 b[128];
ut64 entry = addr_to_offset(bin, bin->entry);
if (entry > bin->size || entry + sizeof (b) > bin->size) {
return 0;
}
i = r_buf_read_at (bin->b, entry, b, sizeof (b));
if (i < 1) {
return 0;
}
for (i = 0; i < 64; i++) {
if (b[i] == 0xe8 && !b[i+3] && !b[i+4]) {
int delta = b[i+1] | (b[i+2] << 8) | (b[i+3] << 16) | (b[i+4] << 24);
return bin->entry + i + 5 + delta;
}
}
}
return addr;
}
| 168,235 |
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: mconvert(struct magic_set *ms, struct magic *m, int flip)
{
union VALUETYPE *p = &ms->ms_value;
switch (cvt_flip(m->type, flip)) {
case FILE_BYTE:
cvt_8(p, m);
return 1;
case FILE_SHORT:
cvt_16(p, m);
return 1;
case FILE_LONG:
case FILE_DATE:
case FILE_LDATE:
cvt_32(p, m);
return 1;
case FILE_QUAD:
case FILE_QDATE:
case FILE_QLDATE:
case FILE_QWDATE:
cvt_64(p, m);
return 1;
case FILE_STRING:
case FILE_BESTRING16:
case FILE_LESTRING16: {
/* Null terminate and eat *trailing* return */
p->s[sizeof(p->s) - 1] = '\0';
return 1;
}
case FILE_PSTRING: {
char *ptr1 = p->s, *ptr2 = ptr1 + file_pstring_length_size(m);
size_t len = file_pstring_get_length(m, ptr1);
if (len >= sizeof(p->s))
len = sizeof(p->s) - 1;
while (len--)
*ptr1++ = *ptr2++;
*ptr1 = '\0';
return 1;
}
case FILE_BESHORT:
p->h = (short)((p->hs[0]<<8)|(p->hs[1]));
cvt_16(p, m);
return 1;
case FILE_BELONG:
case FILE_BEDATE:
case FILE_BELDATE:
p->l = (int32_t)
((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3]));
cvt_32(p, m);
return 1;
case FILE_BEQUAD:
case FILE_BEQDATE:
case FILE_BEQLDATE:
case FILE_BEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7]));
cvt_64(p, m);
return 1;
case FILE_LESHORT:
p->h = (short)((p->hs[1]<<8)|(p->hs[0]));
cvt_16(p, m);
return 1;
case FILE_LELONG:
case FILE_LEDATE:
case FILE_LELDATE:
p->l = (int32_t)
((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0]));
cvt_32(p, m);
return 1;
case FILE_LEQUAD:
case FILE_LEQDATE:
case FILE_LEQLDATE:
case FILE_LEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0]));
cvt_64(p, m);
return 1;
case FILE_MELONG:
case FILE_MEDATE:
case FILE_MELDATE:
p->l = (int32_t)
((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2]));
cvt_32(p, m);
return 1;
case FILE_FLOAT:
cvt_float(p, m);
return 1;
case FILE_BEFLOAT:
p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)|
((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]);
cvt_float(p, m);
return 1;
case FILE_LEFLOAT:
p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)|
((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]);
cvt_float(p, m);
return 1;
case FILE_DOUBLE:
cvt_double(p, m);
return 1;
case FILE_BEDOUBLE:
p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]);
cvt_double(p, m);
return 1;
case FILE_LEDOUBLE:
p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]);
cvt_double(p, m);
return 1;
case FILE_REGEX:
case FILE_SEARCH:
case FILE_DEFAULT:
case FILE_CLEAR:
case FILE_NAME:
case FILE_USE:
return 1;
default:
file_magerror(ms, "invalid type %d in mconvert()", m->type);
return 0;
}
}
Commit Message: * Enforce limit of 8K on regex searches that have no limits
* Allow the l modifier for regex to mean line count. Default
to byte count. If line count is specified, assume a max
of 80 characters per line to limit the byte count.
* Don't allow conversions to be used for dates, allowing
the mask field to be used as an offset.
* Bump the version of the magic format so that regex changes
are visible.
CWE ID: CWE-399 | mconvert(struct magic_set *ms, struct magic *m, int flip)
{
union VALUETYPE *p = &ms->ms_value;
uint8_t type;
switch (type = cvt_flip(m->type, flip)) {
case FILE_BYTE:
cvt_8(p, m);
return 1;
case FILE_SHORT:
cvt_16(p, m);
return 1;
case FILE_LONG:
case FILE_DATE:
case FILE_LDATE:
cvt_32(p, m);
return 1;
case FILE_QUAD:
case FILE_QDATE:
case FILE_QLDATE:
case FILE_QWDATE:
cvt_64(p, m);
return 1;
case FILE_STRING:
case FILE_BESTRING16:
case FILE_LESTRING16: {
/* Null terminate and eat *trailing* return */
p->s[sizeof(p->s) - 1] = '\0';
return 1;
}
case FILE_PSTRING: {
char *ptr1 = p->s, *ptr2 = ptr1 + file_pstring_length_size(m);
size_t len = file_pstring_get_length(m, ptr1);
if (len >= sizeof(p->s))
len = sizeof(p->s) - 1;
while (len--)
*ptr1++ = *ptr2++;
*ptr1 = '\0';
return 1;
}
case FILE_BESHORT:
p->h = (short)((p->hs[0]<<8)|(p->hs[1]));
cvt_16(p, m);
return 1;
case FILE_BELONG:
case FILE_BEDATE:
case FILE_BELDATE:
p->l = (int32_t)
((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3]));
if (type == FILE_BELONG)
cvt_32(p, m);
return 1;
case FILE_BEQUAD:
case FILE_BEQDATE:
case FILE_BEQLDATE:
case FILE_BEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7]));
if (type == FILE_BEQUAD)
cvt_64(p, m);
return 1;
case FILE_LESHORT:
p->h = (short)((p->hs[1]<<8)|(p->hs[0]));
cvt_16(p, m);
return 1;
case FILE_LELONG:
case FILE_LEDATE:
case FILE_LELDATE:
p->l = (int32_t)
((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0]));
if (type == FILE_LELONG)
cvt_32(p, m);
return 1;
case FILE_LEQUAD:
case FILE_LEQDATE:
case FILE_LEQLDATE:
case FILE_LEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0]));
if (type == FILE_LEQUAD)
cvt_64(p, m);
return 1;
case FILE_MELONG:
case FILE_MEDATE:
case FILE_MELDATE:
p->l = (int32_t)
((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2]));
if (type == FILE_MELONG)
cvt_32(p, m);
return 1;
case FILE_FLOAT:
cvt_float(p, m);
return 1;
case FILE_BEFLOAT:
p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)|
((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]);
cvt_float(p, m);
return 1;
case FILE_LEFLOAT:
p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)|
((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]);
cvt_float(p, m);
return 1;
case FILE_DOUBLE:
cvt_double(p, m);
return 1;
case FILE_BEDOUBLE:
p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]);
cvt_double(p, m);
return 1;
case FILE_LEDOUBLE:
p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]);
cvt_double(p, m);
return 1;
case FILE_REGEX:
case FILE_SEARCH:
case FILE_DEFAULT:
case FILE_CLEAR:
case FILE_NAME:
case FILE_USE:
return 1;
default:
file_magerror(ms, "invalid type %d in mconvert()", m->type);
return 0;
}
}
| 166,358 |
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 IOHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
process_host_ = process_host;
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void IOHandler::SetRenderer(RenderProcessHost* process_host,
void IOHandler::SetRenderer(int process_host_id,
RenderFrameHostImpl* frame_host) {
RenderProcessHost* process_host = RenderProcessHost::FromID(process_host_id);
if (process_host) {
browser_context_ = process_host->GetBrowserContext();
storage_partition_ = process_host->GetStoragePartition();
} else {
browser_context_ = nullptr;
storage_partition_ = nullptr;
}
}
| 172,751 |
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 php_wddx_pop_element(void *user_data, const XML_Char *name)
{
st_entry *ent1, *ent2;
wddx_stack *stack = (wddx_stack *)user_data;
HashTable *target_hash;
zend_class_entry **pce;
zval *obj;
zval *tmp;
TSRMLS_FETCH();
/* OBJECTS_FIXME */
if (stack->top == 0) {
return;
}
if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||
!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||
!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||
!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||
!strcmp(name, EL_DATETIME)) {
wddx_stack_top(stack, (void**)&ent1);
if (!ent1->data) {
if (stack->top > 1) {
stack->top--;
efree(ent1);
} else {
stack->done = 1;
}
return;
}
if (!strcmp(name, EL_BINARY)) {
int new_len=0;
unsigned char *new_str;
new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);
STR_FREE(Z_STRVAL_P(ent1->data));
if (new_str) {
Z_STRVAL_P(ent1->data) = new_str;
Z_STRLEN_P(ent1->data) = new_len;
} else {
ZVAL_EMPTY_STRING(ent1->data);
}
}
/* Call __wakeup() method on the object. */
if (Z_TYPE_P(ent1->data) == IS_OBJECT) {
zval *fname, *retval = NULL;
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__wakeup", 1);
call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
if (stack->top > 1) {
stack->top--;
wddx_stack_top(stack, (void**)&ent2);
/* if non-existent field */
if (ent2->data == NULL) {
zval_ptr_dtor(&ent1->data);
efree(ent1);
return;
}
if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {
target_hash = HASH_OF(ent2->data);
if (ent1->varname) {
if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&
ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {
zend_bool incomplete_class = 0;
zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),
Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {
incomplete_class = 1;
pce = &PHP_IC_ENTRY;
}
/* Initialize target object */
MAKE_STD_ZVAL(obj);
object_init_ex(obj, *pce);
/* Merge current hashtable with object's default properties */
zend_hash_merge(Z_OBJPROP_P(obj),
Z_ARRVAL_P(ent2->data),
(void (*)(void *)) zval_add_ref,
(void *) &tmp, sizeof(zval *), 0);
if (incomplete_class) {
php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
}
/* Clean up old array entry */
zval_ptr_dtor(&ent2->data);
/* Set stack entry to point to the newly created object */
ent2->data = obj;
/* Clean up class name var entry */
zval_ptr_dtor(&ent1->data);
} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {
zend_class_entry *old_scope = EG(scope);
EG(scope) = Z_OBJCE_P(ent2->data);
Z_DELREF_P(ent1->data);
add_property_zval(ent2->data, ent1->varname, ent1->data);
EG(scope) = old_scope;
} else {
zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);
}
efree(ent1->varname);
} else {
zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);
}
}
efree(ent1);
} else {
stack->done = 1;
}
} else if (!strcmp(name, EL_VAR) && stack->varname) {
efree(stack->varname);
stack->varname = NULL;
} else if (!strcmp(name, EL_FIELD)) {
st_entry *ent;
wddx_stack_top(stack, (void **)&ent);
efree(ent);
stack->top--;
}
}
Commit Message: Fix bug #73331 - do not try to serialize/unserialize objects wddx can not handle
Proper soltion would be to call serialize/unserialize and deal with the result,
but this requires more work that should be done by wddx maintainer (not me).
CWE ID: CWE-476 | static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
st_entry *ent1, *ent2;
wddx_stack *stack = (wddx_stack *)user_data;
HashTable *target_hash;
zend_class_entry **pce;
zval *obj;
zval *tmp;
TSRMLS_FETCH();
/* OBJECTS_FIXME */
if (stack->top == 0) {
return;
}
if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||
!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||
!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||
!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||
!strcmp(name, EL_DATETIME)) {
wddx_stack_top(stack, (void**)&ent1);
if (!ent1->data) {
if (stack->top > 1) {
stack->top--;
efree(ent1);
} else {
stack->done = 1;
}
return;
}
if (!strcmp(name, EL_BINARY)) {
int new_len=0;
unsigned char *new_str;
new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);
STR_FREE(Z_STRVAL_P(ent1->data));
if (new_str) {
Z_STRVAL_P(ent1->data) = new_str;
Z_STRLEN_P(ent1->data) = new_len;
} else {
ZVAL_EMPTY_STRING(ent1->data);
}
}
/* Call __wakeup() method on the object. */
if (Z_TYPE_P(ent1->data) == IS_OBJECT) {
zval *fname, *retval = NULL;
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__wakeup", 1);
call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
if (stack->top > 1) {
stack->top--;
wddx_stack_top(stack, (void**)&ent2);
/* if non-existent field */
if (ent2->data == NULL) {
zval_ptr_dtor(&ent1->data);
efree(ent1);
return;
}
if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {
target_hash = HASH_OF(ent2->data);
if (ent1->varname) {
if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&
ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {
zend_bool incomplete_class = 0;
zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),
Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {
incomplete_class = 1;
pce = &PHP_IC_ENTRY;
}
if (pce != &PHP_IC_ENTRY && ((*pce)->serialize || (*pce)->unserialize)) {
ent2->data = NULL;
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Class %s can not be unserialized", Z_STRVAL_P(ent1->data));
} else {
/* Initialize target object */
MAKE_STD_ZVAL(obj);
object_init_ex(obj, *pce);
/* Merge current hashtable with object's default properties */
zend_hash_merge(Z_OBJPROP_P(obj),
Z_ARRVAL_P(ent2->data),
(void (*)(void *)) zval_add_ref,
(void *) &tmp, sizeof(zval *), 0);
if (incomplete_class) {
php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
}
/* Clean up old array entry */
zval_ptr_dtor(&ent2->data);
/* Set stack entry to point to the newly created object */
ent2->data = obj;
}
/* Clean up class name var entry */
zval_ptr_dtor(&ent1->data);
} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {
zend_class_entry *old_scope = EG(scope);
EG(scope) = Z_OBJCE_P(ent2->data);
Z_DELREF_P(ent1->data);
add_property_zval(ent2->data, ent1->varname, ent1->data);
EG(scope) = old_scope;
} else {
zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);
}
efree(ent1->varname);
} else {
zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);
}
}
efree(ent1);
} else {
stack->done = 1;
}
} else if (!strcmp(name, EL_VAR) && stack->varname) {
efree(stack->varname);
stack->varname = NULL;
} else if (!strcmp(name, EL_FIELD)) {
st_entry *ent;
wddx_stack_top(stack, (void **)&ent);
efree(ent);
stack->top--;
}
}
| 168,669 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct json_object* json_tokener_parse_ex(struct json_tokener *tok,
const char *str, int len)
{
struct json_object *obj = NULL;
char c = '\1';
#ifdef HAVE_SETLOCALE
char *oldlocale=NULL, *tmplocale;
tmplocale = setlocale(LC_NUMERIC, NULL);
if (tmplocale) oldlocale = strdup(tmplocale);
setlocale(LC_NUMERIC, "C");
#endif
tok->char_offset = 0;
tok->err = json_tokener_success;
while (PEEK_CHAR(c, tok)) {
redo_char:
switch(state) {
case json_tokener_state_eatws:
/* Advance until we change state */
while (isspace((int)c)) {
if ((!ADVANCE_CHAR(str, tok)) || (!PEEK_CHAR(c, tok)))
goto out;
}
if(c == '/' && !(tok->flags & JSON_TOKENER_STRICT)) {
printbuf_reset(tok->pb);
printbuf_memappend_fast(tok->pb, &c, 1);
state = json_tokener_state_comment_start;
} else {
state = saved_state;
goto redo_char;
}
break;
case json_tokener_state_start:
switch(c) {
case '{':
state = json_tokener_state_eatws;
saved_state = json_tokener_state_object_field_start;
current = json_object_new_object();
break;
case '[':
state = json_tokener_state_eatws;
saved_state = json_tokener_state_array;
current = json_object_new_array();
break;
case 'I':
case 'i':
state = json_tokener_state_inf;
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
case 'N':
case 'n':
state = json_tokener_state_null; // or NaN
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
case '\'':
if (tok->flags & JSON_TOKENER_STRICT) {
/* in STRICT mode only double-quote are allowed */
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
case '"':
state = json_tokener_state_string;
printbuf_reset(tok->pb);
tok->quote_char = c;
break;
case 'T':
case 't':
case 'F':
case 'f':
state = json_tokener_state_boolean;
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
#if defined(__GNUC__)
case '0' ... '9':
#else
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
#endif
case '-':
state = json_tokener_state_number;
printbuf_reset(tok->pb);
tok->is_double = 0;
goto redo_char;
default:
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
break;
case json_tokener_state_finish:
if(tok->depth == 0) goto out;
obj = json_object_get(current);
json_tokener_reset_level(tok, tok->depth);
tok->depth--;
goto redo_char;
case json_tokener_state_inf: /* aka starts with 'i' */
{
int size;
int size_inf;
int is_negative = 0;
printbuf_memappend_fast(tok->pb, &c, 1);
size = json_min(tok->st_pos+1, json_null_str_len);
size_inf = json_min(tok->st_pos+1, json_inf_str_len);
char *infbuf = tok->pb->buf;
if (*infbuf == '-')
{
infbuf++;
is_negative = 1;
}
if ((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_inf_str, infbuf, size_inf) == 0) ||
(strncmp(json_inf_str, infbuf, size_inf) == 0)
)
{
if (tok->st_pos == json_inf_str_len)
{
current = json_object_new_double(is_negative ? -INFINITY : INFINITY);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else {
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_null: /* aka starts with 'n' */
{
int size;
int size_nan;
printbuf_memappend_fast(tok->pb, &c, 1);
size = json_min(tok->st_pos+1, json_null_str_len);
size_nan = json_min(tok->st_pos+1, json_nan_str_len);
if((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_null_str, tok->pb->buf, size) == 0)
|| (strncmp(json_null_str, tok->pb->buf, size) == 0)
) {
if (tok->st_pos == json_null_str_len) {
current = NULL;
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
}
else if ((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_nan_str, tok->pb->buf, size_nan) == 0) ||
(strncmp(json_nan_str, tok->pb->buf, size_nan) == 0)
)
{
if (tok->st_pos == json_nan_str_len)
{
current = json_object_new_double(NAN);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else {
tok->err = json_tokener_error_parse_null;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_comment_start:
if(c == '*') {
state = json_tokener_state_comment;
} else if(c == '/') {
state = json_tokener_state_comment_eol;
} else {
tok->err = json_tokener_error_parse_comment;
goto out;
}
printbuf_memappend_fast(tok->pb, &c, 1);
break;
case json_tokener_state_comment:
{
/* Advance until we change state */
const char *case_start = str;
while(c != '*') {
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
printbuf_memappend_fast(tok->pb, case_start, 1+str-case_start);
state = json_tokener_state_comment_end;
}
break;
case json_tokener_state_comment_eol:
{
/* Advance until we change state */
const char *case_start = str;
while(c != '\n') {
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf);
state = json_tokener_state_eatws;
}
break;
case json_tokener_state_comment_end:
printbuf_memappend_fast(tok->pb, &c, 1);
if(c == '/') {
MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf);
state = json_tokener_state_eatws;
} else {
state = json_tokener_state_comment;
}
break;
case json_tokener_state_string:
{
/* Advance until we change state */
const char *case_start = str;
while(1) {
if(c == tok->quote_char) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
current = json_object_new_string_len(tok->pb->buf, tok->pb->bpos);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
break;
} else if(c == '\\') {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
saved_state = json_tokener_state_string;
state = json_tokener_state_string_escape;
break;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
}
break;
case json_tokener_state_string_escape:
switch(c) {
case '"':
case '\\':
case '/':
printbuf_memappend_fast(tok->pb, &c, 1);
state = saved_state;
break;
case 'b':
case 'n':
case 'r':
case 't':
case 'f':
if(c == 'b') printbuf_memappend_fast(tok->pb, "\b", 1);
else if(c == 'n') printbuf_memappend_fast(tok->pb, "\n", 1);
else if(c == 'r') printbuf_memappend_fast(tok->pb, "\r", 1);
else if(c == 't') printbuf_memappend_fast(tok->pb, "\t", 1);
else if(c == 'f') printbuf_memappend_fast(tok->pb, "\f", 1);
state = saved_state;
break;
case 'u':
tok->ucs_char = 0;
tok->st_pos = 0;
state = json_tokener_state_escape_unicode;
break;
default:
tok->err = json_tokener_error_parse_string;
goto out;
}
break;
case json_tokener_state_escape_unicode:
{
unsigned int got_hi_surrogate = 0;
/* Handle a 4-byte sequence, or two sequences if a surrogate pair */
while(1) {
if(strchr(json_hex_chars, c)) {
tok->ucs_char += ((unsigned int)hexdigit(c) << ((3-tok->st_pos++)*4));
if(tok->st_pos == 4) {
unsigned char unescaped_utf[4];
if (got_hi_surrogate) {
if (IS_LOW_SURROGATE(tok->ucs_char)) {
/* Recalculate the ucs_char, then fall thru to process normally */
tok->ucs_char = DECODE_SURROGATE_PAIR(got_hi_surrogate, tok->ucs_char);
} else {
/* Hi surrogate was not followed by a low surrogate */
/* Replace the hi and process the rest normally */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
got_hi_surrogate = 0;
}
if (tok->ucs_char < 0x80) {
unescaped_utf[0] = tok->ucs_char;
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 1);
} else if (tok->ucs_char < 0x800) {
unescaped_utf[0] = 0xc0 | (tok->ucs_char >> 6);
unescaped_utf[1] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 2);
} else if (IS_HIGH_SURROGATE(tok->ucs_char)) {
/* Got a high surrogate. Remember it and look for the
* the beginning of another sequence, which should be the
* low surrogate.
*/
got_hi_surrogate = tok->ucs_char;
/* Not at end, and the next two chars should be "\u" */
if ((tok->char_offset+1 != len) &&
(tok->char_offset+2 != len) &&
(str[1] == '\\') &&
(str[2] == 'u'))
{
/* Advance through the 16 bit surrogate, and move on to the
* next sequence. The next step is to process the following
* characters.
*/
if( !ADVANCE_CHAR(str, tok) || !ADVANCE_CHAR(str, tok) ) {
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
/* Advance to the first char of the next sequence and
* continue processing with the next sequence.
*/
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
goto out;
}
tok->ucs_char = 0;
tok->st_pos = 0;
continue; /* other json_tokener_state_escape_unicode */
} else {
/* Got a high surrogate without another sequence following
* it. Put a replacement char in for the hi surrogate
* and pretend we finished.
*/
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
} else if (IS_LOW_SURROGATE(tok->ucs_char)) {
/* Got a low surrogate not preceded by a high */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
} else if (tok->ucs_char < 0x10000) {
unescaped_utf[0] = 0xe0 | (tok->ucs_char >> 12);
unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 6) & 0x3f);
unescaped_utf[2] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 3);
} else if (tok->ucs_char < 0x110000) {
unescaped_utf[0] = 0xf0 | ((tok->ucs_char >> 18) & 0x07);
unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 12) & 0x3f);
unescaped_utf[2] = 0x80 | ((tok->ucs_char >> 6) & 0x3f);
unescaped_utf[3] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 4);
} else {
/* Don't know what we got--insert the replacement char */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
state = saved_state;
break;
}
} else {
tok->err = json_tokener_error_parse_string;
goto out;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
if (got_hi_surrogate) /* Clean up any pending chars */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
goto out;
}
}
}
break;
case json_tokener_state_boolean:
{
int size1, size2;
printbuf_memappend_fast(tok->pb, &c, 1);
size1 = json_min(tok->st_pos+1, json_true_str_len);
size2 = json_min(tok->st_pos+1, json_false_str_len);
if((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_true_str, tok->pb->buf, size1) == 0)
|| (strncmp(json_true_str, tok->pb->buf, size1) == 0)
) {
if(tok->st_pos == json_true_str_len) {
current = json_object_new_boolean(1);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else if((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_false_str, tok->pb->buf, size2) == 0)
|| (strncmp(json_false_str, tok->pb->buf, size2) == 0)) {
if(tok->st_pos == json_false_str_len) {
current = json_object_new_boolean(0);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else {
tok->err = json_tokener_error_parse_boolean;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_number:
{
/* Advance until we change state */
const char *case_start = str;
int case_len=0;
while(c && strchr(json_number_chars, c)) {
++case_len;
if(c == '.' || c == 'e' || c == 'E')
tok->is_double = 1;
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, case_len);
goto out;
}
}
if (case_len>0)
printbuf_memappend_fast(tok->pb, case_start, case_len);
if (tok->pb->buf[0] == '-' && case_len == 1 &&
(c == 'i' || c == 'I'))
{
state = json_tokener_state_inf;
goto redo_char;
}
}
{
int64_t num64;
double numd;
if (!tok->is_double && json_parse_int64(tok->pb->buf, &num64) == 0) {
if (num64 && tok->pb->buf[0]=='0' && (tok->flags & JSON_TOKENER_STRICT)) {
/* in strict mode, number must not start with 0 */
tok->err = json_tokener_error_parse_number;
goto out;
}
current = json_object_new_int64(num64);
}
else if(tok->is_double && json_parse_double(tok->pb->buf, &numd) == 0)
{
current = json_object_new_double_s(numd, tok->pb->buf);
} else {
tok->err = json_tokener_error_parse_number;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
break;
case json_tokener_state_array_after_sep:
case json_tokener_state_array:
if(c == ']') {
if (state == json_tokener_state_array_after_sep &&
(tok->flags & JSON_TOKENER_STRICT))
{
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else {
if(tok->depth >= tok->max_depth-1) {
tok->err = json_tokener_error_depth;
goto out;
}
state = json_tokener_state_array_add;
tok->depth++;
json_tokener_reset_level(tok, tok->depth);
goto redo_char;
}
break;
case json_tokener_state_array_add:
json_object_array_add(current, obj);
saved_state = json_tokener_state_array_sep;
state = json_tokener_state_eatws;
goto redo_char;
case json_tokener_state_array_sep:
if(c == ']') {
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else if(c == ',') {
saved_state = json_tokener_state_array_after_sep;
state = json_tokener_state_eatws;
} else {
tok->err = json_tokener_error_parse_array;
goto out;
}
break;
case json_tokener_state_object_field_start:
case json_tokener_state_object_field_start_after_sep:
if(c == '}') {
if (state == json_tokener_state_object_field_start_after_sep &&
(tok->flags & JSON_TOKENER_STRICT))
{
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else if (c == '"' || c == '\'') {
tok->quote_char = c;
printbuf_reset(tok->pb);
state = json_tokener_state_object_field;
} else {
tok->err = json_tokener_error_parse_object_key_name;
goto out;
}
break;
case json_tokener_state_object_field:
{
/* Advance until we change state */
const char *case_start = str;
while(1) {
if(c == tok->quote_char) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
obj_field_name = strdup(tok->pb->buf);
saved_state = json_tokener_state_object_field_end;
state = json_tokener_state_eatws;
break;
} else if(c == '\\') {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
saved_state = json_tokener_state_object_field;
state = json_tokener_state_string_escape;
break;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
}
break;
case json_tokener_state_object_field_end:
if(c == ':') {
saved_state = json_tokener_state_object_value;
state = json_tokener_state_eatws;
} else {
tok->err = json_tokener_error_parse_object_key_sep;
goto out;
}
break;
case json_tokener_state_object_value:
if(tok->depth >= tok->max_depth-1) {
tok->err = json_tokener_error_depth;
goto out;
}
state = json_tokener_state_object_value_add;
tok->depth++;
json_tokener_reset_level(tok, tok->depth);
goto redo_char;
case json_tokener_state_object_value_add:
json_object_object_add(current, obj_field_name, obj);
free(obj_field_name);
obj_field_name = NULL;
saved_state = json_tokener_state_object_sep;
state = json_tokener_state_eatws;
goto redo_char;
case json_tokener_state_object_sep:
if(c == '}') {
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else if(c == ',') {
saved_state = json_tokener_state_object_field_start_after_sep;
state = json_tokener_state_eatws;
} else {
tok->err = json_tokener_error_parse_object_value_sep;
goto out;
}
break;
}
if (!ADVANCE_CHAR(str, tok))
goto out;
} /* while(POP_CHAR) */
Commit Message: Patch to address the following issues:
* CVE-2013-6371: hash collision denial of service
* CVE-2013-6370: buffer overflow if size_t is larger than int
CWE ID: CWE-310 | struct json_object* json_tokener_parse_ex(struct json_tokener *tok,
const char *str, int len)
{
struct json_object *obj = NULL;
char c = '\1';
#ifdef HAVE_SETLOCALE
char *oldlocale=NULL, *tmplocale;
tmplocale = setlocale(LC_NUMERIC, NULL);
if (tmplocale) oldlocale = strdup(tmplocale);
setlocale(LC_NUMERIC, "C");
#endif
tok->char_offset = 0;
tok->err = json_tokener_success;
/* this interface is presently not 64-bit clean due to the int len argument
and the internal printbuf interface that takes 32-bit int len arguments
so the function limits the maximum string size to INT32_MAX (2GB).
If the function is called with len == -1 then strlen is called to check
the string length is less than INT32_MAX (2GB) */
if ((len < -1) || (len == -1 && strlen(str) > INT32_MAX)) {
tok->err = json_tokener_error_size;
return NULL;
}
while (PEEK_CHAR(c, tok)) {
redo_char:
switch(state) {
case json_tokener_state_eatws:
/* Advance until we change state */
while (isspace((int)c)) {
if ((!ADVANCE_CHAR(str, tok)) || (!PEEK_CHAR(c, tok)))
goto out;
}
if(c == '/' && !(tok->flags & JSON_TOKENER_STRICT)) {
printbuf_reset(tok->pb);
printbuf_memappend_fast(tok->pb, &c, 1);
state = json_tokener_state_comment_start;
} else {
state = saved_state;
goto redo_char;
}
break;
case json_tokener_state_start:
switch(c) {
case '{':
state = json_tokener_state_eatws;
saved_state = json_tokener_state_object_field_start;
current = json_object_new_object();
break;
case '[':
state = json_tokener_state_eatws;
saved_state = json_tokener_state_array;
current = json_object_new_array();
break;
case 'I':
case 'i':
state = json_tokener_state_inf;
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
case 'N':
case 'n':
state = json_tokener_state_null; // or NaN
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
case '\'':
if (tok->flags & JSON_TOKENER_STRICT) {
/* in STRICT mode only double-quote are allowed */
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
case '"':
state = json_tokener_state_string;
printbuf_reset(tok->pb);
tok->quote_char = c;
break;
case 'T':
case 't':
case 'F':
case 'f':
state = json_tokener_state_boolean;
printbuf_reset(tok->pb);
tok->st_pos = 0;
goto redo_char;
#if defined(__GNUC__)
case '0' ... '9':
#else
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
#endif
case '-':
state = json_tokener_state_number;
printbuf_reset(tok->pb);
tok->is_double = 0;
goto redo_char;
default:
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
break;
case json_tokener_state_finish:
if(tok->depth == 0) goto out;
obj = json_object_get(current);
json_tokener_reset_level(tok, tok->depth);
tok->depth--;
goto redo_char;
case json_tokener_state_inf: /* aka starts with 'i' */
{
int size;
int size_inf;
int is_negative = 0;
printbuf_memappend_fast(tok->pb, &c, 1);
size = json_min(tok->st_pos+1, json_null_str_len);
size_inf = json_min(tok->st_pos+1, json_inf_str_len);
char *infbuf = tok->pb->buf;
if (*infbuf == '-')
{
infbuf++;
is_negative = 1;
}
if ((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_inf_str, infbuf, size_inf) == 0) ||
(strncmp(json_inf_str, infbuf, size_inf) == 0)
)
{
if (tok->st_pos == json_inf_str_len)
{
current = json_object_new_double(is_negative ? -INFINITY : INFINITY);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else {
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_null: /* aka starts with 'n' */
{
int size;
int size_nan;
printbuf_memappend_fast(tok->pb, &c, 1);
size = json_min(tok->st_pos+1, json_null_str_len);
size_nan = json_min(tok->st_pos+1, json_nan_str_len);
if((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_null_str, tok->pb->buf, size) == 0)
|| (strncmp(json_null_str, tok->pb->buf, size) == 0)
) {
if (tok->st_pos == json_null_str_len) {
current = NULL;
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
}
else if ((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_nan_str, tok->pb->buf, size_nan) == 0) ||
(strncmp(json_nan_str, tok->pb->buf, size_nan) == 0)
)
{
if (tok->st_pos == json_nan_str_len)
{
current = json_object_new_double(NAN);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else {
tok->err = json_tokener_error_parse_null;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_comment_start:
if(c == '*') {
state = json_tokener_state_comment;
} else if(c == '/') {
state = json_tokener_state_comment_eol;
} else {
tok->err = json_tokener_error_parse_comment;
goto out;
}
printbuf_memappend_fast(tok->pb, &c, 1);
break;
case json_tokener_state_comment:
{
/* Advance until we change state */
const char *case_start = str;
while(c != '*') {
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
printbuf_memappend_fast(tok->pb, case_start, 1+str-case_start);
state = json_tokener_state_comment_end;
}
break;
case json_tokener_state_comment_eol:
{
/* Advance until we change state */
const char *case_start = str;
while(c != '\n') {
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf);
state = json_tokener_state_eatws;
}
break;
case json_tokener_state_comment_end:
printbuf_memappend_fast(tok->pb, &c, 1);
if(c == '/') {
MC_DEBUG("json_tokener_comment: %s\n", tok->pb->buf);
state = json_tokener_state_eatws;
} else {
state = json_tokener_state_comment;
}
break;
case json_tokener_state_string:
{
/* Advance until we change state */
const char *case_start = str;
while(1) {
if(c == tok->quote_char) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
current = json_object_new_string_len(tok->pb->buf, tok->pb->bpos);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
break;
} else if(c == '\\') {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
saved_state = json_tokener_state_string;
state = json_tokener_state_string_escape;
break;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
}
break;
case json_tokener_state_string_escape:
switch(c) {
case '"':
case '\\':
case '/':
printbuf_memappend_fast(tok->pb, &c, 1);
state = saved_state;
break;
case 'b':
case 'n':
case 'r':
case 't':
case 'f':
if(c == 'b') printbuf_memappend_fast(tok->pb, "\b", 1);
else if(c == 'n') printbuf_memappend_fast(tok->pb, "\n", 1);
else if(c == 'r') printbuf_memappend_fast(tok->pb, "\r", 1);
else if(c == 't') printbuf_memappend_fast(tok->pb, "\t", 1);
else if(c == 'f') printbuf_memappend_fast(tok->pb, "\f", 1);
state = saved_state;
break;
case 'u':
tok->ucs_char = 0;
tok->st_pos = 0;
state = json_tokener_state_escape_unicode;
break;
default:
tok->err = json_tokener_error_parse_string;
goto out;
}
break;
case json_tokener_state_escape_unicode:
{
unsigned int got_hi_surrogate = 0;
/* Handle a 4-byte sequence, or two sequences if a surrogate pair */
while(1) {
if(strchr(json_hex_chars, c)) {
tok->ucs_char += ((unsigned int)hexdigit(c) << ((3-tok->st_pos++)*4));
if(tok->st_pos == 4) {
unsigned char unescaped_utf[4];
if (got_hi_surrogate) {
if (IS_LOW_SURROGATE(tok->ucs_char)) {
/* Recalculate the ucs_char, then fall thru to process normally */
tok->ucs_char = DECODE_SURROGATE_PAIR(got_hi_surrogate, tok->ucs_char);
} else {
/* Hi surrogate was not followed by a low surrogate */
/* Replace the hi and process the rest normally */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
got_hi_surrogate = 0;
}
if (tok->ucs_char < 0x80) {
unescaped_utf[0] = tok->ucs_char;
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 1);
} else if (tok->ucs_char < 0x800) {
unescaped_utf[0] = 0xc0 | (tok->ucs_char >> 6);
unescaped_utf[1] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 2);
} else if (IS_HIGH_SURROGATE(tok->ucs_char)) {
/* Got a high surrogate. Remember it and look for the
* the beginning of another sequence, which should be the
* low surrogate.
*/
got_hi_surrogate = tok->ucs_char;
/* Not at end, and the next two chars should be "\u" */
if ((tok->char_offset+1 != len) &&
(tok->char_offset+2 != len) &&
(str[1] == '\\') &&
(str[2] == 'u'))
{
/* Advance through the 16 bit surrogate, and move on to the
* next sequence. The next step is to process the following
* characters.
*/
if( !ADVANCE_CHAR(str, tok) || !ADVANCE_CHAR(str, tok) ) {
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
/* Advance to the first char of the next sequence and
* continue processing with the next sequence.
*/
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
goto out;
}
tok->ucs_char = 0;
tok->st_pos = 0;
continue; /* other json_tokener_state_escape_unicode */
} else {
/* Got a high surrogate without another sequence following
* it. Put a replacement char in for the hi surrogate
* and pretend we finished.
*/
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
} else if (IS_LOW_SURROGATE(tok->ucs_char)) {
/* Got a low surrogate not preceded by a high */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
} else if (tok->ucs_char < 0x10000) {
unescaped_utf[0] = 0xe0 | (tok->ucs_char >> 12);
unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 6) & 0x3f);
unescaped_utf[2] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 3);
} else if (tok->ucs_char < 0x110000) {
unescaped_utf[0] = 0xf0 | ((tok->ucs_char >> 18) & 0x07);
unescaped_utf[1] = 0x80 | ((tok->ucs_char >> 12) & 0x3f);
unescaped_utf[2] = 0x80 | ((tok->ucs_char >> 6) & 0x3f);
unescaped_utf[3] = 0x80 | (tok->ucs_char & 0x3f);
printbuf_memappend_fast(tok->pb, (char*)unescaped_utf, 4);
} else {
/* Don't know what we got--insert the replacement char */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
}
state = saved_state;
break;
}
} else {
tok->err = json_tokener_error_parse_string;
goto out;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
if (got_hi_surrogate) /* Clean up any pending chars */
printbuf_memappend_fast(tok->pb, (char*)utf8_replacement_char, 3);
goto out;
}
}
}
break;
case json_tokener_state_boolean:
{
int size1, size2;
printbuf_memappend_fast(tok->pb, &c, 1);
size1 = json_min(tok->st_pos+1, json_true_str_len);
size2 = json_min(tok->st_pos+1, json_false_str_len);
if((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_true_str, tok->pb->buf, size1) == 0)
|| (strncmp(json_true_str, tok->pb->buf, size1) == 0)
) {
if(tok->st_pos == json_true_str_len) {
current = json_object_new_boolean(1);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else if((!(tok->flags & JSON_TOKENER_STRICT) &&
strncasecmp(json_false_str, tok->pb->buf, size2) == 0)
|| (strncmp(json_false_str, tok->pb->buf, size2) == 0)) {
if(tok->st_pos == json_false_str_len) {
current = json_object_new_boolean(0);
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
} else {
tok->err = json_tokener_error_parse_boolean;
goto out;
}
tok->st_pos++;
}
break;
case json_tokener_state_number:
{
/* Advance until we change state */
const char *case_start = str;
int case_len=0;
while(c && strchr(json_number_chars, c)) {
++case_len;
if(c == '.' || c == 'e' || c == 'E')
tok->is_double = 1;
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, case_len);
goto out;
}
}
if (case_len>0)
printbuf_memappend_fast(tok->pb, case_start, case_len);
if (tok->pb->buf[0] == '-' && case_len == 1 &&
(c == 'i' || c == 'I'))
{
state = json_tokener_state_inf;
goto redo_char;
}
}
{
int64_t num64;
double numd;
if (!tok->is_double && json_parse_int64(tok->pb->buf, &num64) == 0) {
if (num64 && tok->pb->buf[0]=='0' && (tok->flags & JSON_TOKENER_STRICT)) {
/* in strict mode, number must not start with 0 */
tok->err = json_tokener_error_parse_number;
goto out;
}
current = json_object_new_int64(num64);
}
else if(tok->is_double && json_parse_double(tok->pb->buf, &numd) == 0)
{
current = json_object_new_double_s(numd, tok->pb->buf);
} else {
tok->err = json_tokener_error_parse_number;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
goto redo_char;
}
break;
case json_tokener_state_array_after_sep:
case json_tokener_state_array:
if(c == ']') {
if (state == json_tokener_state_array_after_sep &&
(tok->flags & JSON_TOKENER_STRICT))
{
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else {
if(tok->depth >= tok->max_depth-1) {
tok->err = json_tokener_error_depth;
goto out;
}
state = json_tokener_state_array_add;
tok->depth++;
json_tokener_reset_level(tok, tok->depth);
goto redo_char;
}
break;
case json_tokener_state_array_add:
json_object_array_add(current, obj);
saved_state = json_tokener_state_array_sep;
state = json_tokener_state_eatws;
goto redo_char;
case json_tokener_state_array_sep:
if(c == ']') {
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else if(c == ',') {
saved_state = json_tokener_state_array_after_sep;
state = json_tokener_state_eatws;
} else {
tok->err = json_tokener_error_parse_array;
goto out;
}
break;
case json_tokener_state_object_field_start:
case json_tokener_state_object_field_start_after_sep:
if(c == '}') {
if (state == json_tokener_state_object_field_start_after_sep &&
(tok->flags & JSON_TOKENER_STRICT))
{
tok->err = json_tokener_error_parse_unexpected;
goto out;
}
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else if (c == '"' || c == '\'') {
tok->quote_char = c;
printbuf_reset(tok->pb);
state = json_tokener_state_object_field;
} else {
tok->err = json_tokener_error_parse_object_key_name;
goto out;
}
break;
case json_tokener_state_object_field:
{
/* Advance until we change state */
const char *case_start = str;
while(1) {
if(c == tok->quote_char) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
obj_field_name = strdup(tok->pb->buf);
saved_state = json_tokener_state_object_field_end;
state = json_tokener_state_eatws;
break;
} else if(c == '\\') {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
saved_state = json_tokener_state_object_field;
state = json_tokener_state_string_escape;
break;
}
if (!ADVANCE_CHAR(str, tok) || !PEEK_CHAR(c, tok)) {
printbuf_memappend_fast(tok->pb, case_start, str-case_start);
goto out;
}
}
}
break;
case json_tokener_state_object_field_end:
if(c == ':') {
saved_state = json_tokener_state_object_value;
state = json_tokener_state_eatws;
} else {
tok->err = json_tokener_error_parse_object_key_sep;
goto out;
}
break;
case json_tokener_state_object_value:
if(tok->depth >= tok->max_depth-1) {
tok->err = json_tokener_error_depth;
goto out;
}
state = json_tokener_state_object_value_add;
tok->depth++;
json_tokener_reset_level(tok, tok->depth);
goto redo_char;
case json_tokener_state_object_value_add:
json_object_object_add(current, obj_field_name, obj);
free(obj_field_name);
obj_field_name = NULL;
saved_state = json_tokener_state_object_sep;
state = json_tokener_state_eatws;
goto redo_char;
case json_tokener_state_object_sep:
if(c == '}') {
saved_state = json_tokener_state_finish;
state = json_tokener_state_eatws;
} else if(c == ',') {
saved_state = json_tokener_state_object_field_start_after_sep;
state = json_tokener_state_eatws;
} else {
tok->err = json_tokener_error_parse_object_value_sep;
goto out;
}
break;
}
if (!ADVANCE_CHAR(str, tok))
goto out;
} /* while(POP_CHAR) */
| 166,539 |
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: status_t MPEG4Source::fragmentedRead(
MediaBuffer **out, const ReadOptions *options) {
ALOGV("MPEG4Source::fragmentedRead");
CHECK(mStarted);
*out = NULL;
int64_t targetSampleTimeUs = -1;
int64_t seekTimeUs;
ReadOptions::SeekMode mode;
if (options && options->getSeekTo(&seekTimeUs, &mode)) {
int numSidxEntries = mSegments.size();
if (numSidxEntries != 0) {
int64_t totalTime = 0;
off64_t totalOffset = mFirstMoofOffset;
for (int i = 0; i < numSidxEntries; i++) {
const SidxEntry *se = &mSegments[i];
if (totalTime + se->mDurationUs > seekTimeUs) {
if ((mode == ReadOptions::SEEK_NEXT_SYNC && seekTimeUs > totalTime) ||
(mode == ReadOptions::SEEK_CLOSEST_SYNC &&
(seekTimeUs - totalTime) > (totalTime + se->mDurationUs - seekTimeUs))) {
totalTime += se->mDurationUs;
totalOffset += se->mSize;
}
break;
}
totalTime += se->mDurationUs;
totalOffset += se->mSize;
}
mCurrentMoofOffset = totalOffset;
mCurrentSamples.clear();
mCurrentSampleIndex = 0;
parseChunk(&totalOffset);
mCurrentTime = totalTime * mTimescale / 1000000ll;
} else {
mCurrentMoofOffset = mFirstMoofOffset;
mCurrentSamples.clear();
mCurrentSampleIndex = 0;
off64_t tmp = mCurrentMoofOffset;
parseChunk(&tmp);
mCurrentTime = 0;
}
if (mBuffer != NULL) {
mBuffer->release();
mBuffer = NULL;
}
}
off64_t offset = 0;
size_t size = 0;
uint32_t cts = 0;
bool isSyncSample = false;
bool newBuffer = false;
if (mBuffer == NULL) {
newBuffer = true;
if (mCurrentSampleIndex >= mCurrentSamples.size()) {
if (mNextMoofOffset <= mCurrentMoofOffset) {
return ERROR_END_OF_STREAM;
}
off64_t nextMoof = mNextMoofOffset;
mCurrentMoofOffset = nextMoof;
mCurrentSamples.clear();
mCurrentSampleIndex = 0;
parseChunk(&nextMoof);
if (mCurrentSampleIndex >= mCurrentSamples.size()) {
return ERROR_END_OF_STREAM;
}
}
const Sample *smpl = &mCurrentSamples[mCurrentSampleIndex];
offset = smpl->offset;
size = smpl->size;
cts = mCurrentTime + smpl->compositionOffset;
mCurrentTime += smpl->duration;
isSyncSample = (mCurrentSampleIndex == 0); // XXX
status_t err = mGroup->acquire_buffer(&mBuffer);
if (err != OK) {
CHECK(mBuffer == NULL);
ALOGV("acquire_buffer returned %d", err);
return err;
}
}
const Sample *smpl = &mCurrentSamples[mCurrentSampleIndex];
const sp<MetaData> bufmeta = mBuffer->meta_data();
bufmeta->clear();
if (smpl->encryptedsizes.size()) {
bufmeta->setData(kKeyPlainSizes, 0,
smpl->clearsizes.array(), smpl->clearsizes.size() * 4);
bufmeta->setData(kKeyEncryptedSizes, 0,
smpl->encryptedsizes.array(), smpl->encryptedsizes.size() * 4);
bufmeta->setData(kKeyCryptoIV, 0, smpl->iv, 16); // use 16 or the actual size?
bufmeta->setInt32(kKeyCryptoDefaultIVSize, mDefaultIVSize);
bufmeta->setInt32(kKeyCryptoMode, mCryptoMode);
bufmeta->setData(kKeyCryptoKey, 0, mCryptoKey, 16);
}
if ((!mIsAVC && !mIsHEVC)|| mWantsNALFragments) {
if (newBuffer) {
ssize_t num_bytes_read =
mDataSource->readAt(offset, (uint8_t *)mBuffer->data(), size);
if (num_bytes_read < (ssize_t)size) {
mBuffer->release();
mBuffer = NULL;
ALOGV("i/o error");
return ERROR_IO;
}
CHECK(mBuffer != NULL);
mBuffer->set_range(0, size);
mBuffer->meta_data()->setInt64(
kKeyTime, ((int64_t)cts * 1000000) / mTimescale);
mBuffer->meta_data()->setInt64(
kKeyDuration, ((int64_t)smpl->duration * 1000000) / mTimescale);
if (targetSampleTimeUs >= 0) {
mBuffer->meta_data()->setInt64(
kKeyTargetTime, targetSampleTimeUs);
}
if (isSyncSample) {
mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
}
++mCurrentSampleIndex;
}
if (!mIsAVC && !mIsHEVC) {
*out = mBuffer;
mBuffer = NULL;
return OK;
}
CHECK(mBuffer->range_length() >= mNALLengthSize);
const uint8_t *src =
(const uint8_t *)mBuffer->data() + mBuffer->range_offset();
size_t nal_size = parseNALSize(src);
if (mBuffer->range_length() < mNALLengthSize + nal_size) {
ALOGE("incomplete NAL unit.");
mBuffer->release();
mBuffer = NULL;
return ERROR_MALFORMED;
}
MediaBuffer *clone = mBuffer->clone();
CHECK(clone != NULL);
clone->set_range(mBuffer->range_offset() + mNALLengthSize, nal_size);
CHECK(mBuffer != NULL);
mBuffer->set_range(
mBuffer->range_offset() + mNALLengthSize + nal_size,
mBuffer->range_length() - mNALLengthSize - nal_size);
if (mBuffer->range_length() == 0) {
mBuffer->release();
mBuffer = NULL;
}
*out = clone;
return OK;
} else {
ALOGV("whole NAL");
ssize_t num_bytes_read = 0;
int32_t drm = 0;
bool usesDRM = (mFormat->findInt32(kKeyIsDRM, &drm) && drm != 0);
if (usesDRM) {
num_bytes_read =
mDataSource->readAt(offset, (uint8_t*)mBuffer->data(), size);
} else {
num_bytes_read = mDataSource->readAt(offset, mSrcBuffer, size);
}
if (num_bytes_read < (ssize_t)size) {
mBuffer->release();
mBuffer = NULL;
ALOGV("i/o error");
return ERROR_IO;
}
if (usesDRM) {
CHECK(mBuffer != NULL);
mBuffer->set_range(0, size);
} else {
uint8_t *dstData = (uint8_t *)mBuffer->data();
size_t srcOffset = 0;
size_t dstOffset = 0;
while (srcOffset < size) {
bool isMalFormed = (srcOffset + mNALLengthSize > size);
size_t nalLength = 0;
if (!isMalFormed) {
nalLength = parseNALSize(&mSrcBuffer[srcOffset]);
srcOffset += mNALLengthSize;
isMalFormed = srcOffset + nalLength > size;
}
if (isMalFormed) {
ALOGE("Video is malformed");
mBuffer->release();
mBuffer = NULL;
return ERROR_MALFORMED;
}
if (nalLength == 0) {
continue;
}
CHECK(dstOffset + 4 <= mBuffer->size());
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 1;
memcpy(&dstData[dstOffset], &mSrcBuffer[srcOffset], nalLength);
srcOffset += nalLength;
dstOffset += nalLength;
}
CHECK_EQ(srcOffset, size);
CHECK(mBuffer != NULL);
mBuffer->set_range(0, dstOffset);
}
mBuffer->meta_data()->setInt64(
kKeyTime, ((int64_t)cts * 1000000) / mTimescale);
mBuffer->meta_data()->setInt64(
kKeyDuration, ((int64_t)smpl->duration * 1000000) / mTimescale);
if (targetSampleTimeUs >= 0) {
mBuffer->meta_data()->setInt64(
kKeyTargetTime, targetSampleTimeUs);
}
if (isSyncSample) {
mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
}
++mCurrentSampleIndex;
*out = mBuffer;
mBuffer = NULL;
return OK;
}
}
Commit Message: Add AUtils::isInRange, and use it to detect malformed MPEG4 nal sizes
Bug: 19641538
Change-Id: I5aae3f100846c125decc61eec7cd6563e3f33777
CWE ID: CWE-119 | status_t MPEG4Source::fragmentedRead(
MediaBuffer **out, const ReadOptions *options) {
ALOGV("MPEG4Source::fragmentedRead");
CHECK(mStarted);
*out = NULL;
int64_t targetSampleTimeUs = -1;
int64_t seekTimeUs;
ReadOptions::SeekMode mode;
if (options && options->getSeekTo(&seekTimeUs, &mode)) {
int numSidxEntries = mSegments.size();
if (numSidxEntries != 0) {
int64_t totalTime = 0;
off64_t totalOffset = mFirstMoofOffset;
for (int i = 0; i < numSidxEntries; i++) {
const SidxEntry *se = &mSegments[i];
if (totalTime + se->mDurationUs > seekTimeUs) {
if ((mode == ReadOptions::SEEK_NEXT_SYNC && seekTimeUs > totalTime) ||
(mode == ReadOptions::SEEK_CLOSEST_SYNC &&
(seekTimeUs - totalTime) > (totalTime + se->mDurationUs - seekTimeUs))) {
totalTime += se->mDurationUs;
totalOffset += se->mSize;
}
break;
}
totalTime += se->mDurationUs;
totalOffset += se->mSize;
}
mCurrentMoofOffset = totalOffset;
mCurrentSamples.clear();
mCurrentSampleIndex = 0;
parseChunk(&totalOffset);
mCurrentTime = totalTime * mTimescale / 1000000ll;
} else {
mCurrentMoofOffset = mFirstMoofOffset;
mCurrentSamples.clear();
mCurrentSampleIndex = 0;
off64_t tmp = mCurrentMoofOffset;
parseChunk(&tmp);
mCurrentTime = 0;
}
if (mBuffer != NULL) {
mBuffer->release();
mBuffer = NULL;
}
}
off64_t offset = 0;
size_t size = 0;
uint32_t cts = 0;
bool isSyncSample = false;
bool newBuffer = false;
if (mBuffer == NULL) {
newBuffer = true;
if (mCurrentSampleIndex >= mCurrentSamples.size()) {
if (mNextMoofOffset <= mCurrentMoofOffset) {
return ERROR_END_OF_STREAM;
}
off64_t nextMoof = mNextMoofOffset;
mCurrentMoofOffset = nextMoof;
mCurrentSamples.clear();
mCurrentSampleIndex = 0;
parseChunk(&nextMoof);
if (mCurrentSampleIndex >= mCurrentSamples.size()) {
return ERROR_END_OF_STREAM;
}
}
const Sample *smpl = &mCurrentSamples[mCurrentSampleIndex];
offset = smpl->offset;
size = smpl->size;
cts = mCurrentTime + smpl->compositionOffset;
mCurrentTime += smpl->duration;
isSyncSample = (mCurrentSampleIndex == 0); // XXX
status_t err = mGroup->acquire_buffer(&mBuffer);
if (err != OK) {
CHECK(mBuffer == NULL);
ALOGV("acquire_buffer returned %d", err);
return err;
}
}
const Sample *smpl = &mCurrentSamples[mCurrentSampleIndex];
const sp<MetaData> bufmeta = mBuffer->meta_data();
bufmeta->clear();
if (smpl->encryptedsizes.size()) {
bufmeta->setData(kKeyPlainSizes, 0,
smpl->clearsizes.array(), smpl->clearsizes.size() * 4);
bufmeta->setData(kKeyEncryptedSizes, 0,
smpl->encryptedsizes.array(), smpl->encryptedsizes.size() * 4);
bufmeta->setData(kKeyCryptoIV, 0, smpl->iv, 16); // use 16 or the actual size?
bufmeta->setInt32(kKeyCryptoDefaultIVSize, mDefaultIVSize);
bufmeta->setInt32(kKeyCryptoMode, mCryptoMode);
bufmeta->setData(kKeyCryptoKey, 0, mCryptoKey, 16);
}
if ((!mIsAVC && !mIsHEVC)|| mWantsNALFragments) {
if (newBuffer) {
ssize_t num_bytes_read =
mDataSource->readAt(offset, (uint8_t *)mBuffer->data(), size);
if (num_bytes_read < (ssize_t)size) {
mBuffer->release();
mBuffer = NULL;
ALOGV("i/o error");
return ERROR_IO;
}
CHECK(mBuffer != NULL);
mBuffer->set_range(0, size);
mBuffer->meta_data()->setInt64(
kKeyTime, ((int64_t)cts * 1000000) / mTimescale);
mBuffer->meta_data()->setInt64(
kKeyDuration, ((int64_t)smpl->duration * 1000000) / mTimescale);
if (targetSampleTimeUs >= 0) {
mBuffer->meta_data()->setInt64(
kKeyTargetTime, targetSampleTimeUs);
}
if (isSyncSample) {
mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
}
++mCurrentSampleIndex;
}
if (!mIsAVC && !mIsHEVC) {
*out = mBuffer;
mBuffer = NULL;
return OK;
}
CHECK(mBuffer->range_length() >= mNALLengthSize);
const uint8_t *src =
(const uint8_t *)mBuffer->data() + mBuffer->range_offset();
size_t nal_size = parseNALSize(src);
if (mBuffer->range_length() < mNALLengthSize + nal_size) {
ALOGE("incomplete NAL unit.");
mBuffer->release();
mBuffer = NULL;
return ERROR_MALFORMED;
}
MediaBuffer *clone = mBuffer->clone();
CHECK(clone != NULL);
clone->set_range(mBuffer->range_offset() + mNALLengthSize, nal_size);
CHECK(mBuffer != NULL);
mBuffer->set_range(
mBuffer->range_offset() + mNALLengthSize + nal_size,
mBuffer->range_length() - mNALLengthSize - nal_size);
if (mBuffer->range_length() == 0) {
mBuffer->release();
mBuffer = NULL;
}
*out = clone;
return OK;
} else {
ALOGV("whole NAL");
ssize_t num_bytes_read = 0;
int32_t drm = 0;
bool usesDRM = (mFormat->findInt32(kKeyIsDRM, &drm) && drm != 0);
if (usesDRM) {
num_bytes_read =
mDataSource->readAt(offset, (uint8_t*)mBuffer->data(), size);
} else {
num_bytes_read = mDataSource->readAt(offset, mSrcBuffer, size);
}
if (num_bytes_read < (ssize_t)size) {
mBuffer->release();
mBuffer = NULL;
ALOGV("i/o error");
return ERROR_IO;
}
if (usesDRM) {
CHECK(mBuffer != NULL);
mBuffer->set_range(0, size);
} else {
uint8_t *dstData = (uint8_t *)mBuffer->data();
size_t srcOffset = 0;
size_t dstOffset = 0;
while (srcOffset < size) {
bool isMalFormed = !isInRange((size_t)0u, size, srcOffset, mNALLengthSize);
size_t nalLength = 0;
if (!isMalFormed) {
nalLength = parseNALSize(&mSrcBuffer[srcOffset]);
srcOffset += mNALLengthSize;
isMalFormed = !isInRange((size_t)0u, size, srcOffset, nalLength);
}
if (isMalFormed) {
ALOGE("Video is malformed");
mBuffer->release();
mBuffer = NULL;
return ERROR_MALFORMED;
}
if (nalLength == 0) {
continue;
}
CHECK(dstOffset + 4 <= mBuffer->size());
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 1;
memcpy(&dstData[dstOffset], &mSrcBuffer[srcOffset], nalLength);
srcOffset += nalLength;
dstOffset += nalLength;
}
CHECK_EQ(srcOffset, size);
CHECK(mBuffer != NULL);
mBuffer->set_range(0, dstOffset);
}
mBuffer->meta_data()->setInt64(
kKeyTime, ((int64_t)cts * 1000000) / mTimescale);
mBuffer->meta_data()->setInt64(
kKeyDuration, ((int64_t)smpl->duration * 1000000) / mTimescale);
if (targetSampleTimeUs >= 0) {
mBuffer->meta_data()->setInt64(
kKeyTargetTime, targetSampleTimeUs);
}
if (isSyncSample) {
mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
}
++mCurrentSampleIndex;
*out = mBuffer;
mBuffer = NULL;
return OK;
}
}
| 173,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 ChromeNetworkDelegate::OnCompleted(net::URLRequest* request,
bool started) {
TRACE_EVENT_ASYNC_END0("net", "URLRequest", request);
if (request->status().status() == net::URLRequestStatus::SUCCESS) {
int64 received_content_length = request->received_response_content_length();
bool is_http = request->url().SchemeIs("http");
bool is_https = request->url().SchemeIs("https");
if (!request->was_cached() && // Don't record cached content
received_content_length && // Zero-byte responses aren't useful.
(is_http || is_https)) { // Only record for HTTP or HTTPS urls.
int64 original_content_length =
request->response_info().headers->GetInt64HeaderValue(
"x-original-content-length");
bool via_data_reduction_proxy =
request->response_info().headers->HasHeaderValue(
"via", "1.1 Chrome Compression Proxy");
int64 adjusted_original_content_length = original_content_length;
if (adjusted_original_content_length == -1)
adjusted_original_content_length = received_content_length;
base::TimeDelta freshness_lifetime =
request->response_info().headers->GetFreshnessLifetime(
request->response_info().response_time);
AccumulateContentLength(received_content_length,
adjusted_original_content_length,
via_data_reduction_proxy);
RecordContentLengthHistograms(received_content_length,
original_content_length,
freshness_lifetime);
DVLOG(2) << __FUNCTION__
<< " received content length: " << received_content_length
<< " original content length: " << original_content_length
<< " url: " << request->url();
}
bool is_redirect = request->response_headers() &&
net::HttpResponseHeaders::IsRedirectResponseCode(
request->response_headers()->response_code());
if (!is_redirect) {
ExtensionWebRequestEventRouter::GetInstance()->OnCompleted(
profile_, extension_info_map_.get(), request);
}
} else if (request->status().status() == net::URLRequestStatus::FAILED ||
request->status().status() == net::URLRequestStatus::CANCELED) {
ExtensionWebRequestEventRouter::GetInstance()->OnErrorOccurred(
profile_, extension_info_map_.get(), request, started);
} else {
NOTREACHED();
}
ForwardProxyErrors(request, event_router_.get(), profile_);
ForwardRequestStatus(REQUEST_DONE, request, profile_);
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416 | void ChromeNetworkDelegate::OnCompleted(net::URLRequest* request,
bool started) {
TRACE_EVENT_ASYNC_END0("net", "URLRequest", request);
if (request->status().status() == net::URLRequestStatus::SUCCESS) {
int64 received_content_length = request->received_response_content_length();
bool is_http = request->url().SchemeIs("http");
bool is_https = request->url().SchemeIs("https");
if (!request->was_cached() && // Don't record cached content
received_content_length && // Zero-byte responses aren't useful.
(is_http || is_https)) { // Only record for HTTP or HTTPS urls.
int64 original_content_length =
request->response_info().headers->GetInt64HeaderValue(
"x-original-content-length");
chrome_browser_net::DataReductionRequestType data_reduction_type =
chrome_browser_net::GetDataReductionRequestType(
reinterpret_cast<Profile*>(profile_), request);
base::TimeDelta freshness_lifetime =
request->response_info().headers->GetFreshnessLifetime(
request->response_info().response_time);
int64 adjusted_original_content_length =
chrome_browser_net::GetAdjustedOriginalContentLength(
data_reduction_type, original_content_length,
received_content_length);
AccumulateContentLength(received_content_length,
adjusted_original_content_length,
data_reduction_type);
RecordContentLengthHistograms(received_content_length,
original_content_length,
freshness_lifetime);
DVLOG(2) << __FUNCTION__
<< " received content length: " << received_content_length
<< " original content length: " << original_content_length
<< " url: " << request->url();
}
bool is_redirect = request->response_headers() &&
net::HttpResponseHeaders::IsRedirectResponseCode(
request->response_headers()->response_code());
if (!is_redirect) {
ExtensionWebRequestEventRouter::GetInstance()->OnCompleted(
profile_, extension_info_map_.get(), request);
}
} else if (request->status().status() == net::URLRequestStatus::FAILED ||
request->status().status() == net::URLRequestStatus::CANCELED) {
ExtensionWebRequestEventRouter::GetInstance()->OnErrorOccurred(
profile_, extension_info_map_.get(), request, started);
} else {
NOTREACHED();
}
ForwardProxyErrors(request, event_router_.get(), profile_);
ForwardRequestStatus(REQUEST_DONE, request, profile_);
}
| 171,332 |
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_connection (GsmXSMPClient *client)
{
GIOChannel *channel;
int fd;
g_debug ("GsmXSMPClient: Setting up new connection");
fd = IceConnectionNumber (client->priv->ice_connection);
fcntl (fd, F_SETFD, fcntl (fd, F_GETFD, 0) | FD_CLOEXEC);
channel = g_io_channel_unix_new (fd);
client->priv->watch_id = g_io_add_watch (channel,
G_IO_IN | G_IO_ERR,
(GIOFunc)client_iochannel_watch,
client);
g_io_channel_unref (channel);
client->priv->protocol_timeout = g_timeout_add_seconds (5,
(GSourceFunc)_client_protocol_timeout,
client);
set_description (client);
g_debug ("GsmXSMPClient: New client '%s'", client->priv->description);
}
Commit Message: [gsm] Delay the creation of the GsmXSMPClient until it really exists
We used to create the GsmXSMPClient before the XSMP connection is really
accepted. This can lead to some issues, though. An example is:
https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting:
"What is happening is that a new client (probably metacity in your
case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION
phase, which causes a new GsmXSMPClient to be added to the client
store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client
has had a chance to establish a xsmp connection, which means that
client->priv->conn will not be initialized at the point that xsmp_stop
is called on the new unregistered client."
The fix is to create the GsmXSMPClient object when there's a real XSMP
connection. This implies moving the timeout that makes sure we don't
have an empty client to the XSMP server.
https://bugzilla.gnome.org/show_bug.cgi?id=598211
CWE ID: CWE-835 | setup_connection (GsmXSMPClient *client)
{
GIOChannel *channel;
int fd;
g_debug ("GsmXSMPClient: Setting up new connection");
fd = IceConnectionNumber (client->priv->ice_connection);
fcntl (fd, F_SETFD, fcntl (fd, F_GETFD, 0) | FD_CLOEXEC);
channel = g_io_channel_unix_new (fd);
client->priv->watch_id = g_io_add_watch (channel,
G_IO_IN | G_IO_ERR,
(GIOFunc)client_iochannel_watch,
client);
g_io_channel_unref (channel);
set_description (client);
g_debug ("GsmXSMPClient: New client '%s'", client->priv->description);
}
| 168,051 |
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: ProcessIdToFilterMap* GetProcessIdToFilterMap() {
static base::NoDestructor<ProcessIdToFilterMap> instance;
return instance.get();
}
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155}
CWE ID: CWE-362 | ProcessIdToFilterMap* GetProcessIdToFilterMap() {
| 173,043 |
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: ikev2_vid_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
const u_char *vid;
int i, len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4));
vid = (const u_char *)(ext+1);
len = ntohs(e.len) - 4;
ND_TCHECK2(*vid, len);
for(i=0; i<len; i++) {
if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i]));
else ND_PRINT((ndo, "."));
}
if (2 < ndo->ndo_vflag && 4 < len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | ikev2_vid_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
const u_char *vid;
int i, len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4));
vid = (const u_char *)(ext+1);
len = ntohs(e.len) - 4;
ND_TCHECK2(*vid, len);
for(i=0; i<len; i++) {
if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i]));
else ND_PRINT((ndo, "."));
}
if (2 < ndo->ndo_vflag && 4 < len) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
| 167,803 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2,
int fragmented)
{
char *cp;
const struct icmp *dp;
const struct icmp_ext_t *ext_dp;
const struct ip *ip;
const char *str, *fmt;
const struct ip *oip;
const struct udphdr *ouh;
const uint8_t *obj_tptr;
uint32_t raw_label;
const u_char *snapend_save;
const struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header;
u_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype;
char buf[MAXHOSTNAMELEN + 100];
struct cksum_vec vec[1];
dp = (const struct icmp *)bp;
ext_dp = (const struct icmp_ext_t *)bp;
ip = (const struct ip *)bp2;
str = buf;
ND_TCHECK(dp->icmp_code);
switch (dp->icmp_type) {
case ICMP_ECHO:
case ICMP_ECHOREPLY:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf), "echo %s, id %u, seq %u",
dp->icmp_type == ICMP_ECHO ?
"request" : "reply",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_UNREACH:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_UNREACH_PROTOCOL:
ND_TCHECK(dp->icmp_ip.ip_p);
(void)snprintf(buf, sizeof(buf),
"%s protocol %d unreachable",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
dp->icmp_ip.ip_p);
break;
case ICMP_UNREACH_PORT:
ND_TCHECK(dp->icmp_ip.ip_p);
oip = &dp->icmp_ip;
hlen = IP_HL(oip) * 4;
ouh = (const struct udphdr *)(((const u_char *)oip) + hlen);
ND_TCHECK(ouh->uh_dport);
dport = EXTRACT_16BITS(&ouh->uh_dport);
switch (oip->ip_p) {
case IPPROTO_TCP:
(void)snprintf(buf, sizeof(buf),
"%s tcp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
tcpport_string(ndo, dport));
break;
case IPPROTO_UDP:
(void)snprintf(buf, sizeof(buf),
"%s udp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
udpport_string(ndo, dport));
break;
default:
(void)snprintf(buf, sizeof(buf),
"%s protocol %d port %d unreachable",
ipaddr_string(ndo, &oip->ip_dst),
oip->ip_p, dport);
break;
}
break;
case ICMP_UNREACH_NEEDFRAG:
{
register const struct mtu_discovery *mp;
mp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void;
mtu = EXTRACT_16BITS(&mp->nexthopmtu);
if (mtu) {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag (mtu %d)",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu);
} else {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
}
}
break;
default:
fmt = tok2str(unreach2str, "#%d %%s unreachable",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
break;
}
break;
case ICMP_REDIRECT:
ND_TCHECK(dp->icmp_ip.ip_dst);
fmt = tok2str(type2str, "redirect-#%d %%s to net %%s",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
ipaddr_string(ndo, &dp->icmp_gwaddr));
break;
case ICMP_ROUTERADVERT:
{
register const struct ih_rdiscovery *ihp;
register const struct id_rdiscovery *idp;
u_int lifetime, num, size;
(void)snprintf(buf, sizeof(buf), "router advertisement");
cp = buf + strlen(buf);
ihp = (const struct ih_rdiscovery *)&dp->icmp_void;
ND_TCHECK(*ihp);
(void)strncpy(cp, " lifetime ", sizeof(buf) - (cp - buf));
cp = buf + strlen(buf);
lifetime = EXTRACT_16BITS(&ihp->ird_lifetime);
if (lifetime < 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u",
lifetime);
} else if (lifetime < 60 * 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u",
lifetime / 60, lifetime % 60);
} else {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
"%u:%02u:%02u",
lifetime / 3600,
(lifetime % 3600) / 60,
lifetime % 60);
}
cp = buf + strlen(buf);
num = ihp->ird_addrnum;
(void)snprintf(cp, sizeof(buf) - (cp - buf), " %d:", num);
cp = buf + strlen(buf);
size = ihp->ird_addrsiz;
if (size != 2) {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
" [size %d]", size);
break;
}
idp = (const struct id_rdiscovery *)&dp->icmp_data;
while (num-- > 0) {
ND_TCHECK(*idp);
(void)snprintf(cp, sizeof(buf) - (cp - buf), " {%s %u}",
ipaddr_string(ndo, &idp->ird_addr),
EXTRACT_32BITS(&idp->ird_pref));
cp = buf + strlen(buf);
++idp;
}
}
break;
case ICMP_TIMXCEED:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_TIMXCEED_INTRANS:
str = "time exceeded in-transit";
break;
case ICMP_TIMXCEED_REASS:
str = "ip reassembly time exceeded";
break;
default:
(void)snprintf(buf, sizeof(buf), "time exceeded-#%d",
dp->icmp_code);
break;
}
break;
case ICMP_PARAMPROB:
if (dp->icmp_code)
(void)snprintf(buf, sizeof(buf),
"parameter problem - code %d", dp->icmp_code);
else {
ND_TCHECK(dp->icmp_pptr);
(void)snprintf(buf, sizeof(buf),
"parameter problem - octet %d", dp->icmp_pptr);
}
break;
case ICMP_MASKREPLY:
ND_TCHECK(dp->icmp_mask);
(void)snprintf(buf, sizeof(buf), "address mask is 0x%08x",
EXTRACT_32BITS(&dp->icmp_mask));
break;
case ICMP_TSTAMP:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf),
"time stamp query id %u seq %u",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_TSTAMPREPLY:
ND_TCHECK(dp->icmp_ttime);
(void)snprintf(buf, sizeof(buf),
"time stamp reply id %u seq %u: org %s",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq),
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", recv %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", xmit %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime)));
break;
default:
str = tok2str(icmp2str, "type-#%d", dp->icmp_type);
break;
}
ND_PRINT((ndo, "ICMP %s, length %u", str, plen));
if (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */
uint16_t sum, icmp_sum;
if (ND_TTEST2(*bp, plen)) {
vec[0].ptr = (const uint8_t *)(const void *)dp;
vec[0].len = plen;
sum = in_cksum(vec, 1);
if (sum != 0) {
icmp_sum = EXTRACT_16BITS(&dp->icmp_cksum);
ND_PRINT((ndo, " (wrong icmp cksum %x (->%x)!)",
icmp_sum,
in_cksum_shouldbe(icmp_sum, sum)));
}
}
}
/*
* print the remnants of the IP packet.
* save the snaplength as this may get overidden in the IP printer.
*/
if (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) {
bp += 8;
ND_PRINT((ndo, "\n\t"));
ip = (const struct ip *)bp;
snapend_save = ndo->ndo_snapend;
ip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len));
ndo->ndo_snapend = snapend_save;
}
/*
* Attempt to decode the MPLS extensions only for some ICMP types.
*/
if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) {
ND_TCHECK(*ext_dp);
/*
* Check first if the mpls extension header shows a non-zero length.
* If the length field is not set then silently verify the checksum
* to check if an extension header is present. This is expedient,
* however not all implementations set the length field proper.
*/
if (!ext_dp->icmp_length &&
ND_TTEST2(ext_dp->icmp_ext_version_res, plen - ICMP_EXTD_MINLEN)) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = plen - ICMP_EXTD_MINLEN;
if (in_cksum(vec, 1)) {
return;
}
}
ND_PRINT((ndo, "\n\tMPLS extension v%u",
ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res))));
/*
* Sanity checking of the header.
*/
if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) !=
ICMP_MPLS_EXT_VERSION) {
ND_PRINT((ndo, " packet not supported"));
return;
}
hlen = plen - ICMP_EXTD_MINLEN;
if (ND_TTEST2(ext_dp->icmp_ext_version_res, hlen)) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = hlen;
ND_PRINT((ndo, ", checksum 0x%04x (%scorrect), length %u",
EXTRACT_16BITS(ext_dp->icmp_ext_checksum),
in_cksum(vec, 1) ? "in" : "",
hlen));
}
hlen -= 4; /* subtract common header size */
obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data;
while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) {
icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr;
ND_TCHECK(*icmp_mpls_ext_object_header);
obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length);
obj_class_num = icmp_mpls_ext_object_header->class_num;
obj_ctype = icmp_mpls_ext_object_header->ctype;
obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t);
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %u, length %u",
tok2str(icmp_mpls_ext_obj_values,"unknown",obj_class_num),
obj_class_num,
obj_ctype,
obj_tlen));
hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */
/* infinite loop protection */
if ((obj_class_num == 0) ||
(obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) {
return;
}
obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t);
switch (obj_class_num) {
case 1:
switch(obj_ctype) {
case 1:
ND_TCHECK2(*obj_tptr, 4);
raw_label = EXTRACT_32BITS(obj_tptr);
ND_PRINT((ndo, "\n\t label %u, exp %u", MPLS_LABEL(raw_label), MPLS_EXP(raw_label)));
if (MPLS_STACK(raw_label))
ND_PRINT((ndo, ", [S]"));
ND_PRINT((ndo, ", ttl %u", MPLS_TTL(raw_label)));
break;
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
}
break;
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case 2:
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
break;
}
if (hlen < obj_tlen)
break;
hlen -= obj_tlen;
obj_tptr += obj_tlen;
}
}
return;
trunc:
ND_PRINT((ndo, "[|icmp]"));
}
Commit Message: CVE-2017-13012/ICMP: Add a missing bounds check.
Check before fetching the length from the included packet's IPv4 header.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
CWE ID: CWE-125 | icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2,
int fragmented)
{
char *cp;
const struct icmp *dp;
const struct icmp_ext_t *ext_dp;
const struct ip *ip;
const char *str, *fmt;
const struct ip *oip;
const struct udphdr *ouh;
const uint8_t *obj_tptr;
uint32_t raw_label;
const u_char *snapend_save;
const struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header;
u_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype;
char buf[MAXHOSTNAMELEN + 100];
struct cksum_vec vec[1];
dp = (const struct icmp *)bp;
ext_dp = (const struct icmp_ext_t *)bp;
ip = (const struct ip *)bp2;
str = buf;
ND_TCHECK(dp->icmp_code);
switch (dp->icmp_type) {
case ICMP_ECHO:
case ICMP_ECHOREPLY:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf), "echo %s, id %u, seq %u",
dp->icmp_type == ICMP_ECHO ?
"request" : "reply",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_UNREACH:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_UNREACH_PROTOCOL:
ND_TCHECK(dp->icmp_ip.ip_p);
(void)snprintf(buf, sizeof(buf),
"%s protocol %d unreachable",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
dp->icmp_ip.ip_p);
break;
case ICMP_UNREACH_PORT:
ND_TCHECK(dp->icmp_ip.ip_p);
oip = &dp->icmp_ip;
hlen = IP_HL(oip) * 4;
ouh = (const struct udphdr *)(((const u_char *)oip) + hlen);
ND_TCHECK(ouh->uh_dport);
dport = EXTRACT_16BITS(&ouh->uh_dport);
switch (oip->ip_p) {
case IPPROTO_TCP:
(void)snprintf(buf, sizeof(buf),
"%s tcp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
tcpport_string(ndo, dport));
break;
case IPPROTO_UDP:
(void)snprintf(buf, sizeof(buf),
"%s udp port %s unreachable",
ipaddr_string(ndo, &oip->ip_dst),
udpport_string(ndo, dport));
break;
default:
(void)snprintf(buf, sizeof(buf),
"%s protocol %d port %d unreachable",
ipaddr_string(ndo, &oip->ip_dst),
oip->ip_p, dport);
break;
}
break;
case ICMP_UNREACH_NEEDFRAG:
{
register const struct mtu_discovery *mp;
mp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void;
mtu = EXTRACT_16BITS(&mp->nexthopmtu);
if (mtu) {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag (mtu %d)",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu);
} else {
(void)snprintf(buf, sizeof(buf),
"%s unreachable - need to frag",
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
}
}
break;
default:
fmt = tok2str(unreach2str, "#%d %%s unreachable",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst));
break;
}
break;
case ICMP_REDIRECT:
ND_TCHECK(dp->icmp_ip.ip_dst);
fmt = tok2str(type2str, "redirect-#%d %%s to net %%s",
dp->icmp_code);
(void)snprintf(buf, sizeof(buf), fmt,
ipaddr_string(ndo, &dp->icmp_ip.ip_dst),
ipaddr_string(ndo, &dp->icmp_gwaddr));
break;
case ICMP_ROUTERADVERT:
{
register const struct ih_rdiscovery *ihp;
register const struct id_rdiscovery *idp;
u_int lifetime, num, size;
(void)snprintf(buf, sizeof(buf), "router advertisement");
cp = buf + strlen(buf);
ihp = (const struct ih_rdiscovery *)&dp->icmp_void;
ND_TCHECK(*ihp);
(void)strncpy(cp, " lifetime ", sizeof(buf) - (cp - buf));
cp = buf + strlen(buf);
lifetime = EXTRACT_16BITS(&ihp->ird_lifetime);
if (lifetime < 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u",
lifetime);
} else if (lifetime < 60 * 60) {
(void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u",
lifetime / 60, lifetime % 60);
} else {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
"%u:%02u:%02u",
lifetime / 3600,
(lifetime % 3600) / 60,
lifetime % 60);
}
cp = buf + strlen(buf);
num = ihp->ird_addrnum;
(void)snprintf(cp, sizeof(buf) - (cp - buf), " %d:", num);
cp = buf + strlen(buf);
size = ihp->ird_addrsiz;
if (size != 2) {
(void)snprintf(cp, sizeof(buf) - (cp - buf),
" [size %d]", size);
break;
}
idp = (const struct id_rdiscovery *)&dp->icmp_data;
while (num-- > 0) {
ND_TCHECK(*idp);
(void)snprintf(cp, sizeof(buf) - (cp - buf), " {%s %u}",
ipaddr_string(ndo, &idp->ird_addr),
EXTRACT_32BITS(&idp->ird_pref));
cp = buf + strlen(buf);
++idp;
}
}
break;
case ICMP_TIMXCEED:
ND_TCHECK(dp->icmp_ip.ip_dst);
switch (dp->icmp_code) {
case ICMP_TIMXCEED_INTRANS:
str = "time exceeded in-transit";
break;
case ICMP_TIMXCEED_REASS:
str = "ip reassembly time exceeded";
break;
default:
(void)snprintf(buf, sizeof(buf), "time exceeded-#%d",
dp->icmp_code);
break;
}
break;
case ICMP_PARAMPROB:
if (dp->icmp_code)
(void)snprintf(buf, sizeof(buf),
"parameter problem - code %d", dp->icmp_code);
else {
ND_TCHECK(dp->icmp_pptr);
(void)snprintf(buf, sizeof(buf),
"parameter problem - octet %d", dp->icmp_pptr);
}
break;
case ICMP_MASKREPLY:
ND_TCHECK(dp->icmp_mask);
(void)snprintf(buf, sizeof(buf), "address mask is 0x%08x",
EXTRACT_32BITS(&dp->icmp_mask));
break;
case ICMP_TSTAMP:
ND_TCHECK(dp->icmp_seq);
(void)snprintf(buf, sizeof(buf),
"time stamp query id %u seq %u",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq));
break;
case ICMP_TSTAMPREPLY:
ND_TCHECK(dp->icmp_ttime);
(void)snprintf(buf, sizeof(buf),
"time stamp reply id %u seq %u: org %s",
EXTRACT_16BITS(&dp->icmp_id),
EXTRACT_16BITS(&dp->icmp_seq),
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", recv %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime)));
(void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", xmit %s",
icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime)));
break;
default:
str = tok2str(icmp2str, "type-#%d", dp->icmp_type);
break;
}
ND_PRINT((ndo, "ICMP %s, length %u", str, plen));
if (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */
uint16_t sum, icmp_sum;
if (ND_TTEST2(*bp, plen)) {
vec[0].ptr = (const uint8_t *)(const void *)dp;
vec[0].len = plen;
sum = in_cksum(vec, 1);
if (sum != 0) {
icmp_sum = EXTRACT_16BITS(&dp->icmp_cksum);
ND_PRINT((ndo, " (wrong icmp cksum %x (->%x)!)",
icmp_sum,
in_cksum_shouldbe(icmp_sum, sum)));
}
}
}
/*
* print the remnants of the IP packet.
* save the snaplength as this may get overidden in the IP printer.
*/
if (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) {
bp += 8;
ND_PRINT((ndo, "\n\t"));
ip = (const struct ip *)bp;
snapend_save = ndo->ndo_snapend;
ND_TCHECK_16BITS(&ip->ip_len);
ip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len));
ndo->ndo_snapend = snapend_save;
}
/*
* Attempt to decode the MPLS extensions only for some ICMP types.
*/
if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) {
ND_TCHECK(*ext_dp);
/*
* Check first if the mpls extension header shows a non-zero length.
* If the length field is not set then silently verify the checksum
* to check if an extension header is present. This is expedient,
* however not all implementations set the length field proper.
*/
if (!ext_dp->icmp_length &&
ND_TTEST2(ext_dp->icmp_ext_version_res, plen - ICMP_EXTD_MINLEN)) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = plen - ICMP_EXTD_MINLEN;
if (in_cksum(vec, 1)) {
return;
}
}
ND_PRINT((ndo, "\n\tMPLS extension v%u",
ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res))));
/*
* Sanity checking of the header.
*/
if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) !=
ICMP_MPLS_EXT_VERSION) {
ND_PRINT((ndo, " packet not supported"));
return;
}
hlen = plen - ICMP_EXTD_MINLEN;
if (ND_TTEST2(ext_dp->icmp_ext_version_res, hlen)) {
vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res;
vec[0].len = hlen;
ND_PRINT((ndo, ", checksum 0x%04x (%scorrect), length %u",
EXTRACT_16BITS(ext_dp->icmp_ext_checksum),
in_cksum(vec, 1) ? "in" : "",
hlen));
}
hlen -= 4; /* subtract common header size */
obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data;
while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) {
icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr;
ND_TCHECK(*icmp_mpls_ext_object_header);
obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length);
obj_class_num = icmp_mpls_ext_object_header->class_num;
obj_ctype = icmp_mpls_ext_object_header->ctype;
obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t);
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %u, length %u",
tok2str(icmp_mpls_ext_obj_values,"unknown",obj_class_num),
obj_class_num,
obj_ctype,
obj_tlen));
hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */
/* infinite loop protection */
if ((obj_class_num == 0) ||
(obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) {
return;
}
obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t);
switch (obj_class_num) {
case 1:
switch(obj_ctype) {
case 1:
ND_TCHECK2(*obj_tptr, 4);
raw_label = EXTRACT_32BITS(obj_tptr);
ND_PRINT((ndo, "\n\t label %u, exp %u", MPLS_LABEL(raw_label), MPLS_EXP(raw_label)));
if (MPLS_STACK(raw_label))
ND_PRINT((ndo, ", [S]"));
ND_PRINT((ndo, ", ttl %u", MPLS_TTL(raw_label)));
break;
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
}
break;
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case 2:
default:
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen);
break;
}
if (hlen < obj_tlen)
break;
hlen -= obj_tlen;
obj_tptr += obj_tlen;
}
}
return;
trunc:
ND_PRINT((ndo, "[|icmp]"));
}
| 167,882 |
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 FoFiType1::parse() {
char *line, *line1, *p, *p2;
char buf[256];
char c;
int n, code, i, j;
char *tokptr;
for (i = 1, line = (char *)file;
i <= 100 && line && (!name || !encoding);
++i) {
if (!name && !strncmp(line, "/FontName", 9)) {
strncpy(buf, line, 255);
buf[255] = '\0';
if ((p = strchr(buf+9, '/')) &&
(p = strtok_r(p+1, " \t\n\r", &tokptr))) {
name = copyString(p);
}
line = getNextLine(line);
} else if (!encoding &&
!strncmp(line, "/Encoding StandardEncoding def", 30)) {
encoding = fofiType1StandardEncoding;
} else if (!encoding &&
!strncmp(line, "/Encoding 256 array", 19)) {
encoding = (char **)gmallocn(256, sizeof(char *));
for (j = 0; j < 256; ++j) {
encoding[j] = NULL;
}
for (j = 0, line = getNextLine(line);
j < 300 && line && (line1 = getNextLine(line));
++j, line = line1) {
if ((n = line1 - line) > 255) {
error(-1, "FoFiType1::parse a line has more than 255 characters, we don't support this");
n = 255;
}
strncpy(buf, line, n);
buf[n] = '\0';
for (p = buf; *p == ' ' || *p == '\t'; ++p) ;
if (!strncmp(p, "dup", 3)) {
for (p += 3; *p == ' ' || *p == '\t'; ++p) ;
for (p2 = p; *p2 >= '0' && *p2 <= '9'; ++p2) ;
if (*p2) {
c = *p2; // store it so we can recover it after atoi
*p2 = '\0'; // terminate p so atoi works
code = atoi(p);
*p2 = c;
if (code == 8 && *p2 == '#') {
code = 0;
for (++p2; *p2 >= '0' && *p2 <= '7'; ++p2) {
code = code * 8 + (*p2 - '0');
code = code * 8 + (*p2 - '0');
}
}
if (code < 256) {
for (p = p2; *p == ' ' || *p == '\t'; ++p) ;
if (*p == '/') {
++p;
c = *p2; // store it so we can recover it after copyString
*p2 = '\0'; // terminate p so copyString works
encoding[code] = copyString(p);
*p2 = c;
p = p2;
for (; *p == ' ' || *p == '\t'; ++p); // eat spaces between string and put
if (!strncmp(p, "put", 3)) {
for (p += 3; *p == ' ' || *p == '\t' || *p == '\n' || *p == '\r'; ++p);
if (*p)
{
line1 = &line[p - buf];
}
} else {
error(-1, "FoFiType1::parse no put after dup");
}
}
}
}
} else {
if (strtok_r(buf, " \t", &tokptr) &&
(p = strtok_r(NULL, " \t\n\r", &tokptr)) && !strcmp(p, "def")) {
break;
}
}
}
} else {
line = getNextLine(line);
}
}
parsed = gTrue;
}
Commit Message:
CWE ID: CWE-20 | void FoFiType1::parse() {
char *line, *line1, *p, *p2;
char buf[256];
char c;
int n, code, i, j;
char *tokptr;
for (i = 1, line = (char *)file;
i <= 100 && line && (!name || !encoding);
++i) {
if (!name && !strncmp(line, "/FontName", 9)) {
strncpy(buf, line, 255);
buf[255] = '\0';
if ((p = strchr(buf+9, '/')) &&
(p = strtok_r(p+1, " \t\n\r", &tokptr))) {
name = copyString(p);
}
line = getNextLine(line);
} else if (!encoding &&
!strncmp(line, "/Encoding StandardEncoding def", 30)) {
encoding = fofiType1StandardEncoding;
} else if (!encoding &&
!strncmp(line, "/Encoding 256 array", 19)) {
encoding = (char **)gmallocn(256, sizeof(char *));
for (j = 0; j < 256; ++j) {
encoding[j] = NULL;
}
for (j = 0, line = getNextLine(line);
j < 300 && line && (line1 = getNextLine(line));
++j, line = line1) {
if ((n = line1 - line) > 255) {
error(-1, "FoFiType1::parse a line has more than 255 characters, we don't support this");
n = 255;
}
strncpy(buf, line, n);
buf[n] = '\0';
for (p = buf; *p == ' ' || *p == '\t'; ++p) ;
if (!strncmp(p, "dup", 3)) {
for (p += 3; *p == ' ' || *p == '\t'; ++p) ;
for (p2 = p; *p2 >= '0' && *p2 <= '9'; ++p2) ;
if (*p2) {
c = *p2; // store it so we can recover it after atoi
*p2 = '\0'; // terminate p so atoi works
code = atoi(p);
*p2 = c;
if (code == 8 && *p2 == '#') {
code = 0;
for (++p2; *p2 >= '0' && *p2 <= '7'; ++p2) {
code = code * 8 + (*p2 - '0');
code = code * 8 + (*p2 - '0');
}
}
if (likely(code < 256 && code >= 0)) {
for (p = p2; *p == ' ' || *p == '\t'; ++p) ;
if (*p == '/') {
++p;
c = *p2; // store it so we can recover it after copyString
*p2 = '\0'; // terminate p so copyString works
encoding[code] = copyString(p);
*p2 = c;
p = p2;
for (; *p == ' ' || *p == '\t'; ++p); // eat spaces between string and put
if (!strncmp(p, "put", 3)) {
for (p += 3; *p == ' ' || *p == '\t' || *p == '\n' || *p == '\r'; ++p);
if (*p)
{
line1 = &line[p - buf];
}
} else {
error(-1, "FoFiType1::parse no put after dup");
}
}
}
}
} else {
if (strtok_r(buf, " \t", &tokptr) &&
(p = strtok_r(NULL, " \t\n\r", &tokptr)) && !strcmp(p, "def")) {
break;
}
}
}
} else {
line = getNextLine(line);
}
}
parsed = gTrue;
}
| 164,903 |
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 SUB_STATE_RETURN read_state_machine(SSL *s)
{
OSSL_STATEM *st = &s->statem;
int ret, mt;
unsigned long len = 0;
int (*transition) (SSL *s, int mt);
PACKET pkt;
MSG_PROCESS_RETURN(*process_message) (SSL *s, PACKET *pkt);
WORK_STATE(*post_process_message) (SSL *s, WORK_STATE wst);
unsigned long (*max_message_size) (SSL *s);
void (*cb) (const SSL *ssl, int type, int val) = NULL;
cb = get_callback(s);
if (s->server) {
transition = ossl_statem_server_read_transition;
process_message = ossl_statem_server_process_message;
max_message_size = ossl_statem_server_max_message_size;
post_process_message = ossl_statem_server_post_process_message;
} else {
transition = ossl_statem_client_read_transition;
process_message = ossl_statem_client_process_message;
max_message_size = ossl_statem_client_max_message_size;
post_process_message = ossl_statem_client_post_process_message;
}
if (st->read_state_first_init) {
s->first_packet = 1;
st->read_state_first_init = 0;
}
while (1) {
switch (st->read_state) {
case READ_STATE_HEADER:
/* Get the state the peer wants to move to */
if (SSL_IS_DTLS(s)) {
/*
* In DTLS we get the whole message in one go - header and body
*/
ret = dtls_get_message(s, &mt, &len);
} else {
ret = tls_get_message_header(s, &mt);
}
if (ret == 0) {
/* Could be non-blocking IO */
return SUB_STATE_ERROR;
}
if (cb != NULL) {
/* Notify callback of an impending state change */
if (s->server)
cb(s, SSL_CB_ACCEPT_LOOP, 1);
else
cb(s, SSL_CB_CONNECT_LOOP, 1);
}
/*
* Validate that we are allowed to move to the new state and move
* to that state if so
*/
if (!transition(s, mt)) {
ossl_statem_set_error(s);
return SUB_STATE_ERROR;
}
if (s->s3->tmp.message_size > max_message_size(s)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
return SUB_STATE_ERROR;
}
st->read_state = READ_STATE_BODY;
/* Fall through */
if (!PACKET_buf_init(&pkt, s->init_msg, len)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
return SUB_STATE_ERROR;
}
ret = process_message(s, &pkt);
/* Discard the packet data */
s->init_num = 0;
switch (ret) {
case MSG_PROCESS_ERROR:
return SUB_STATE_ERROR;
case MSG_PROCESS_FINISHED_READING:
if (SSL_IS_DTLS(s)) {
dtls1_stop_timer(s);
}
return SUB_STATE_FINISHED;
case MSG_PROCESS_CONTINUE_PROCESSING:
st->read_state = READ_STATE_POST_PROCESS;
st->read_state_work = WORK_MORE_A;
break;
default:
st->read_state = READ_STATE_HEADER;
break;
}
break;
case READ_STATE_POST_PROCESS:
st->read_state_work = post_process_message(s, st->read_state_work);
switch (st->read_state_work) {
default:
return SUB_STATE_ERROR;
case WORK_FINISHED_CONTINUE:
st->read_state = READ_STATE_HEADER;
break;
case WORK_FINISHED_STOP:
if (SSL_IS_DTLS(s)) {
dtls1_stop_timer(s);
}
return SUB_STATE_FINISHED;
}
break;
default:
/* Shouldn't happen */
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
ossl_statem_set_error(s);
return SUB_STATE_ERROR;
}
}
}
Commit Message:
CWE ID: CWE-400 | static SUB_STATE_RETURN read_state_machine(SSL *s)
{
OSSL_STATEM *st = &s->statem;
int ret, mt;
unsigned long len = 0;
int (*transition) (SSL *s, int mt);
PACKET pkt;
MSG_PROCESS_RETURN(*process_message) (SSL *s, PACKET *pkt);
WORK_STATE(*post_process_message) (SSL *s, WORK_STATE wst);
unsigned long (*max_message_size) (SSL *s);
void (*cb) (const SSL *ssl, int type, int val) = NULL;
cb = get_callback(s);
if (s->server) {
transition = ossl_statem_server_read_transition;
process_message = ossl_statem_server_process_message;
max_message_size = ossl_statem_server_max_message_size;
post_process_message = ossl_statem_server_post_process_message;
} else {
transition = ossl_statem_client_read_transition;
process_message = ossl_statem_client_process_message;
max_message_size = ossl_statem_client_max_message_size;
post_process_message = ossl_statem_client_post_process_message;
}
if (st->read_state_first_init) {
s->first_packet = 1;
st->read_state_first_init = 0;
}
while (1) {
switch (st->read_state) {
case READ_STATE_HEADER:
/* Get the state the peer wants to move to */
if (SSL_IS_DTLS(s)) {
/*
* In DTLS we get the whole message in one go - header and body
*/
ret = dtls_get_message(s, &mt, &len);
} else {
ret = tls_get_message_header(s, &mt);
}
if (ret == 0) {
/* Could be non-blocking IO */
return SUB_STATE_ERROR;
}
if (cb != NULL) {
/* Notify callback of an impending state change */
if (s->server)
cb(s, SSL_CB_ACCEPT_LOOP, 1);
else
cb(s, SSL_CB_CONNECT_LOOP, 1);
}
/*
* Validate that we are allowed to move to the new state and move
* to that state if so
*/
if (!transition(s, mt)) {
ossl_statem_set_error(s);
return SUB_STATE_ERROR;
}
if (s->s3->tmp.message_size > max_message_size(s)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
return SUB_STATE_ERROR;
}
/* dtls_get_message already did this */
if (!SSL_IS_DTLS(s)
&& s->s3->tmp.message_size > 0
&& !BUF_MEM_grow_clean(s->init_buf,
(int)s->s3->tmp.message_size
+ SSL3_HM_HEADER_LENGTH)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, ERR_R_BUF_LIB);
return SUB_STATE_ERROR;
}
st->read_state = READ_STATE_BODY;
/* Fall through */
if (!PACKET_buf_init(&pkt, s->init_msg, len)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
return SUB_STATE_ERROR;
}
ret = process_message(s, &pkt);
/* Discard the packet data */
s->init_num = 0;
switch (ret) {
case MSG_PROCESS_ERROR:
return SUB_STATE_ERROR;
case MSG_PROCESS_FINISHED_READING:
if (SSL_IS_DTLS(s)) {
dtls1_stop_timer(s);
}
return SUB_STATE_FINISHED;
case MSG_PROCESS_CONTINUE_PROCESSING:
st->read_state = READ_STATE_POST_PROCESS;
st->read_state_work = WORK_MORE_A;
break;
default:
st->read_state = READ_STATE_HEADER;
break;
}
break;
case READ_STATE_POST_PROCESS:
st->read_state_work = post_process_message(s, st->read_state_work);
switch (st->read_state_work) {
default:
return SUB_STATE_ERROR;
case WORK_FINISHED_CONTINUE:
st->read_state = READ_STATE_HEADER;
break;
case WORK_FINISHED_STOP:
if (SSL_IS_DTLS(s)) {
dtls1_stop_timer(s);
}
return SUB_STATE_FINISHED;
}
break;
default:
/* Shouldn't happen */
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
ossl_statem_set_error(s);
return SUB_STATE_ERROR;
}
}
}
| 164,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: static void __svc_rdma_free(struct work_struct *work)
{
struct svcxprt_rdma *rdma =
container_of(work, struct svcxprt_rdma, sc_work);
struct svc_xprt *xprt = &rdma->sc_xprt;
dprintk("svcrdma: %s(%p)\n", __func__, rdma);
if (rdma->sc_qp && !IS_ERR(rdma->sc_qp))
ib_drain_qp(rdma->sc_qp);
/* We should only be called from kref_put */
if (kref_read(&xprt->xpt_ref) != 0)
pr_err("svcrdma: sc_xprt still in use? (%d)\n",
kref_read(&xprt->xpt_ref));
/*
* Destroy queued, but not processed read completions. Note
* that this cleanup has to be done before destroying the
* cm_id because the device ptr is needed to unmap the dma in
* svc_rdma_put_context.
*/
while (!list_empty(&rdma->sc_read_complete_q)) {
struct svc_rdma_op_ctxt *ctxt;
ctxt = list_first_entry(&rdma->sc_read_complete_q,
struct svc_rdma_op_ctxt, list);
list_del(&ctxt->list);
svc_rdma_put_context(ctxt, 1);
}
/* Destroy queued, but not processed recv completions */
while (!list_empty(&rdma->sc_rq_dto_q)) {
struct svc_rdma_op_ctxt *ctxt;
ctxt = list_first_entry(&rdma->sc_rq_dto_q,
struct svc_rdma_op_ctxt, list);
list_del(&ctxt->list);
svc_rdma_put_context(ctxt, 1);
}
/* Warn if we leaked a resource or under-referenced */
if (rdma->sc_ctxt_used != 0)
pr_err("svcrdma: ctxt still in use? (%d)\n",
rdma->sc_ctxt_used);
/* Final put of backchannel client transport */
if (xprt->xpt_bc_xprt) {
xprt_put(xprt->xpt_bc_xprt);
xprt->xpt_bc_xprt = NULL;
}
rdma_dealloc_frmr_q(rdma);
svc_rdma_destroy_ctxts(rdma);
svc_rdma_destroy_maps(rdma);
/* Destroy the QP if present (not a listener) */
if (rdma->sc_qp && !IS_ERR(rdma->sc_qp))
ib_destroy_qp(rdma->sc_qp);
if (rdma->sc_sq_cq && !IS_ERR(rdma->sc_sq_cq))
ib_free_cq(rdma->sc_sq_cq);
if (rdma->sc_rq_cq && !IS_ERR(rdma->sc_rq_cq))
ib_free_cq(rdma->sc_rq_cq);
if (rdma->sc_pd && !IS_ERR(rdma->sc_pd))
ib_dealloc_pd(rdma->sc_pd);
/* Destroy the CM ID */
rdma_destroy_id(rdma->sc_cm_id);
kfree(rdma);
}
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 | static void __svc_rdma_free(struct work_struct *work)
{
struct svcxprt_rdma *rdma =
container_of(work, struct svcxprt_rdma, sc_work);
struct svc_xprt *xprt = &rdma->sc_xprt;
dprintk("svcrdma: %s(%p)\n", __func__, rdma);
if (rdma->sc_qp && !IS_ERR(rdma->sc_qp))
ib_drain_qp(rdma->sc_qp);
/* We should only be called from kref_put */
if (kref_read(&xprt->xpt_ref) != 0)
pr_err("svcrdma: sc_xprt still in use? (%d)\n",
kref_read(&xprt->xpt_ref));
/*
* Destroy queued, but not processed read completions. Note
* that this cleanup has to be done before destroying the
* cm_id because the device ptr is needed to unmap the dma in
* svc_rdma_put_context.
*/
while (!list_empty(&rdma->sc_read_complete_q)) {
struct svc_rdma_op_ctxt *ctxt;
ctxt = list_first_entry(&rdma->sc_read_complete_q,
struct svc_rdma_op_ctxt, list);
list_del(&ctxt->list);
svc_rdma_put_context(ctxt, 1);
}
/* Destroy queued, but not processed recv completions */
while (!list_empty(&rdma->sc_rq_dto_q)) {
struct svc_rdma_op_ctxt *ctxt;
ctxt = list_first_entry(&rdma->sc_rq_dto_q,
struct svc_rdma_op_ctxt, list);
list_del(&ctxt->list);
svc_rdma_put_context(ctxt, 1);
}
/* Warn if we leaked a resource or under-referenced */
if (rdma->sc_ctxt_used != 0)
pr_err("svcrdma: ctxt still in use? (%d)\n",
rdma->sc_ctxt_used);
/* Final put of backchannel client transport */
if (xprt->xpt_bc_xprt) {
xprt_put(xprt->xpt_bc_xprt);
xprt->xpt_bc_xprt = NULL;
}
rdma_dealloc_frmr_q(rdma);
svc_rdma_destroy_rw_ctxts(rdma);
svc_rdma_destroy_ctxts(rdma);
/* Destroy the QP if present (not a listener) */
if (rdma->sc_qp && !IS_ERR(rdma->sc_qp))
ib_destroy_qp(rdma->sc_qp);
if (rdma->sc_sq_cq && !IS_ERR(rdma->sc_sq_cq))
ib_free_cq(rdma->sc_sq_cq);
if (rdma->sc_rq_cq && !IS_ERR(rdma->sc_rq_cq))
ib_free_cq(rdma->sc_rq_cq);
if (rdma->sc_pd && !IS_ERR(rdma->sc_pd))
ib_dealloc_pd(rdma->sc_pd);
/* Destroy the CM ID */
rdma_destroy_id(rdma->sc_cm_id);
kfree(rdma);
}
| 168,176 |
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 CancelHandwritingStrokes(int stroke_count) {
if (!initialized_successfully_)
return;
chromeos::CancelHandwriting(input_method_status_connection_, stroke_count);
}
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 CancelHandwritingStrokes(int stroke_count) {
if (!initialized_successfully_)
return;
ibus_controller_->CancelHandwriting(stroke_count);
}
| 170,477 |
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 SoftAMR::onQueueFilled(OMX_U32 /* portIndex */) {
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
while (!inQueue.empty() && !outQueue.empty()) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
return;
}
if (inHeader->nOffset == 0) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumSamplesOutput = 0;
}
const uint8_t *inputPtr = inHeader->pBuffer + inHeader->nOffset;
int32_t numBytesRead;
if (mMode == MODE_NARROW) {
numBytesRead =
AMRDecode(mState,
(Frame_Type_3GPP)((inputPtr[0] >> 3) & 0x0f),
(UWord8 *)&inputPtr[1],
reinterpret_cast<int16_t *>(outHeader->pBuffer),
MIME_IETF);
if (numBytesRead == -1) {
ALOGE("PV AMR decoder AMRDecode() call failed");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
++numBytesRead; // Include the frame type header byte.
if (static_cast<size_t>(numBytesRead) > inHeader->nFilledLen) {
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
} else {
int16 mode = ((inputPtr[0] >> 3) & 0x0f);
if (mode >= 10 && mode <= 13) {
ALOGE("encountered illegal frame type %d in AMR WB content.",
mode);
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
size_t frameSize = getFrameSize(mode);
CHECK_GE(inHeader->nFilledLen, frameSize);
int16_t *outPtr = (int16_t *)outHeader->pBuffer;
if (mode >= 9) {
memset(outPtr, 0, kNumSamplesPerFrameWB * sizeof(int16_t));
} else if (mode < 9) {
int16 frameType;
RX_State_wb rx_state;
mime_unsorting(
const_cast<uint8_t *>(&inputPtr[1]),
mInputSampleBuffer,
&frameType, &mode, 1, &rx_state);
int16_t numSamplesOutput;
pvDecoder_AmrWb(
mode, mInputSampleBuffer,
outPtr,
&numSamplesOutput,
mDecoderBuf, frameType, mDecoderCookie);
CHECK_EQ((int)numSamplesOutput, (int)kNumSamplesPerFrameWB);
for (int i = 0; i < kNumSamplesPerFrameWB; ++i) {
/* Delete the 2 LSBs (14-bit output) */
outPtr[i] &= 0xfffC;
}
}
numBytesRead = frameSize;
}
inHeader->nOffset += numBytesRead;
inHeader->nFilledLen -= numBytesRead;
outHeader->nFlags = 0;
outHeader->nOffset = 0;
if (mMode == MODE_NARROW) {
outHeader->nFilledLen = kNumSamplesPerFrameNB * sizeof(int16_t);
outHeader->nTimeStamp =
mAnchorTimeUs
+ (mNumSamplesOutput * 1000000ll) / kSampleRateNB;
mNumSamplesOutput += kNumSamplesPerFrameNB;
} else {
outHeader->nFilledLen = kNumSamplesPerFrameWB * sizeof(int16_t);
outHeader->nTimeStamp =
mAnchorTimeUs
+ (mNumSamplesOutput * 1000000ll) / kSampleRateWB;
mNumSamplesOutput += kNumSamplesPerFrameWB;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
++mInputBufferCount;
}
}
Commit Message: SoftAMR: check output buffer size to avoid overflow.
Bug: 27662364
Change-Id: I7b26892c41d6f2e690e77478ab855c2fed1ff6b0
CWE ID: CWE-264 | void SoftAMR::onQueueFilled(OMX_U32 /* portIndex */) {
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
while (!inQueue.empty() && !outQueue.empty()) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
return;
}
if (inHeader->nOffset == 0) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumSamplesOutput = 0;
}
const uint8_t *inputPtr = inHeader->pBuffer + inHeader->nOffset;
int32_t numBytesRead;
if (mMode == MODE_NARROW) {
if (outHeader->nAllocLen < kNumSamplesPerFrameNB * sizeof(int16_t)) {
ALOGE("b/27662364: NB expected output buffer %zu bytes vs %u",
kNumSamplesPerFrameNB * sizeof(int16_t), outHeader->nAllocLen);
android_errorWriteLog(0x534e4554, "27662364");
notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL);
mSignalledError = true;
return;
}
numBytesRead =
AMRDecode(mState,
(Frame_Type_3GPP)((inputPtr[0] >> 3) & 0x0f),
(UWord8 *)&inputPtr[1],
reinterpret_cast<int16_t *>(outHeader->pBuffer),
MIME_IETF);
if (numBytesRead == -1) {
ALOGE("PV AMR decoder AMRDecode() call failed");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
++numBytesRead; // Include the frame type header byte.
if (static_cast<size_t>(numBytesRead) > inHeader->nFilledLen) {
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
} else {
if (outHeader->nAllocLen < kNumSamplesPerFrameWB * sizeof(int16_t)) {
ALOGE("b/27662364: WB expected output buffer %zu bytes vs %u",
kNumSamplesPerFrameWB * sizeof(int16_t), outHeader->nAllocLen);
android_errorWriteLog(0x534e4554, "27662364");
notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL);
mSignalledError = true;
return;
}
int16 mode = ((inputPtr[0] >> 3) & 0x0f);
if (mode >= 10 && mode <= 13) {
ALOGE("encountered illegal frame type %d in AMR WB content.",
mode);
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
size_t frameSize = getFrameSize(mode);
CHECK_GE(inHeader->nFilledLen, frameSize);
int16_t *outPtr = (int16_t *)outHeader->pBuffer;
if (mode >= 9) {
memset(outPtr, 0, kNumSamplesPerFrameWB * sizeof(int16_t));
} else if (mode < 9) {
int16 frameType;
RX_State_wb rx_state;
mime_unsorting(
const_cast<uint8_t *>(&inputPtr[1]),
mInputSampleBuffer,
&frameType, &mode, 1, &rx_state);
int16_t numSamplesOutput;
pvDecoder_AmrWb(
mode, mInputSampleBuffer,
outPtr,
&numSamplesOutput,
mDecoderBuf, frameType, mDecoderCookie);
CHECK_EQ((int)numSamplesOutput, (int)kNumSamplesPerFrameWB);
for (int i = 0; i < kNumSamplesPerFrameWB; ++i) {
/* Delete the 2 LSBs (14-bit output) */
outPtr[i] &= 0xfffC;
}
}
numBytesRead = frameSize;
}
inHeader->nOffset += numBytesRead;
inHeader->nFilledLen -= numBytesRead;
outHeader->nFlags = 0;
outHeader->nOffset = 0;
if (mMode == MODE_NARROW) {
outHeader->nFilledLen = kNumSamplesPerFrameNB * sizeof(int16_t);
outHeader->nTimeStamp =
mAnchorTimeUs
+ (mNumSamplesOutput * 1000000ll) / kSampleRateNB;
mNumSamplesOutput += kNumSamplesPerFrameNB;
} else {
outHeader->nFilledLen = kNumSamplesPerFrameWB * sizeof(int16_t);
outHeader->nTimeStamp =
mAnchorTimeUs
+ (mNumSamplesOutput * 1000000ll) / kSampleRateWB;
mNumSamplesOutput += kNumSamplesPerFrameWB;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
++mInputBufferCount;
}
}
| 173,879 |
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 RenderFrameHostManager::EnsureRenderFrameHostVisibilityConsistent() {
if (render_frame_host_->GetView() &&
render_frame_host_->render_view_host()->GetWidget()->is_hidden() !=
delegate_->IsHidden()) {
if (delegate_->IsHidden()) {
render_frame_host_->GetView()->Hide();
} else {
render_frame_host_->GetView()->Show();
}
}
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20 | void RenderFrameHostManager::EnsureRenderFrameHostVisibilityConsistent() {
RenderWidgetHostView* view = GetRenderWidgetHostView();
if (view && static_cast<RenderWidgetHostImpl*>(view->GetRenderWidgetHost())
->is_hidden() != delegate_->IsHidden()) {
if (delegate_->IsHidden()) {
view->Hide();
} else {
view->Show();
}
}
}
| 172,321 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void rng_backend_request_entropy(RngBackend *s, size_t size,
EntropyReceiveFunc *receive_entropy,
void *opaque)
{
RngBackendClass *k = RNG_BACKEND_GET_CLASS(s);
if (k->request_entropy) {
k->request_entropy(s, size, receive_entropy, opaque);
}
}
Commit Message:
CWE ID: CWE-119 | void rng_backend_request_entropy(RngBackend *s, size_t size,
EntropyReceiveFunc *receive_entropy,
void *opaque)
{
RngBackendClass *k = RNG_BACKEND_GET_CLASS(s);
RngRequest *req;
if (k->request_entropy) {
req = g_malloc(sizeof(*req));
req->offset = 0;
req->size = size;
req->receive_entropy = receive_entropy;
req->opaque = opaque;
req->data = g_malloc(req->size);
k->request_entropy(s, req);
s->requests = g_slist_append(s->requests, req);
}
}
| 165,181 |
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 SyncManager::SyncInternal::UpdateEnabledTypes() {
DCHECK(thread_checker_.CalledOnValidThread());
ModelSafeRoutingInfo routes;
registrar_->GetModelSafeRoutingInfo(&routes);
const ModelTypeSet enabled_types = GetRoutingInfoTypes(routes);
sync_notifier_->UpdateEnabledTypes(enabled_types);
if (enable_sync_tabs_for_other_clients_)
MaybeSetSyncTabsInNigoriNode(enabled_types);
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | void SyncManager::SyncInternal::UpdateEnabledTypes() {
DCHECK(thread_checker_.CalledOnValidThread());
ModelSafeRoutingInfo routes;
registrar_->GetModelSafeRoutingInfo(&routes);
const ModelTypeSet enabled_types = GetRoutingInfoTypes(routes);
sync_notifier_->UpdateEnabledTypes(enabled_types);
| 170,798 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE omx_vdec::empty_this_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
OMX_ERRORTYPE ret1 = OMX_ErrorNone;
unsigned int nBufferIndex = drv_ctx.ip_buf.actualcount;
if (m_state == OMX_StateInvalid) {
DEBUG_PRINT_ERROR("Empty this buffer in Invalid State");
return OMX_ErrorInvalidState;
}
if (buffer == NULL) {
DEBUG_PRINT_ERROR("ERROR:ETB Buffer is NULL");
return OMX_ErrorBadParameter;
}
if (!m_inp_bEnabled) {
DEBUG_PRINT_ERROR("ERROR:ETB incorrect state operation, input port is disabled.");
return OMX_ErrorIncorrectStateOperation;
}
if (buffer->nInputPortIndex != OMX_CORE_INPUT_PORT_INDEX) {
DEBUG_PRINT_ERROR("ERROR:ETB invalid port in header %u", (unsigned int)buffer->nInputPortIndex);
return OMX_ErrorBadPortIndex;
}
#ifdef _ANDROID_
if (iDivXDrmDecrypt) {
OMX_ERRORTYPE drmErr = iDivXDrmDecrypt->Decrypt(buffer);
if (drmErr != OMX_ErrorNone) {
DEBUG_PRINT_LOW("ERROR:iDivXDrmDecrypt->Decrypt %d", drmErr);
}
}
#endif //_ANDROID_
if (perf_flag) {
if (!latency) {
dec_time.stop();
latency = dec_time.processing_time_us();
dec_time.start();
}
}
if (arbitrary_bytes) {
nBufferIndex = buffer - m_inp_heap_ptr;
} else {
if (input_use_buffer == true) {
nBufferIndex = buffer - m_inp_heap_ptr;
m_inp_mem_ptr[nBufferIndex].nFilledLen = m_inp_heap_ptr[nBufferIndex].nFilledLen;
m_inp_mem_ptr[nBufferIndex].nTimeStamp = m_inp_heap_ptr[nBufferIndex].nTimeStamp;
m_inp_mem_ptr[nBufferIndex].nFlags = m_inp_heap_ptr[nBufferIndex].nFlags;
buffer = &m_inp_mem_ptr[nBufferIndex];
DEBUG_PRINT_LOW("Non-Arbitrary mode - buffer address is: malloc %p, pmem%p in Index %d, buffer %p of size %u",
&m_inp_heap_ptr[nBufferIndex], &m_inp_mem_ptr[nBufferIndex],nBufferIndex, buffer, (unsigned int)buffer->nFilledLen);
} else {
nBufferIndex = buffer - m_inp_mem_ptr;
}
}
if (nBufferIndex > drv_ctx.ip_buf.actualcount ) {
DEBUG_PRINT_ERROR("ERROR:ETB nBufferIndex is invalid");
return OMX_ErrorBadParameter;
}
if (buffer->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
codec_config_flag = true;
DEBUG_PRINT_LOW("%s: codec_config buffer", __FUNCTION__);
}
DEBUG_PRINT_LOW("[ETB] BHdr(%p) pBuf(%p) nTS(%lld) nFL(%u)",
buffer, buffer->pBuffer, buffer->nTimeStamp, (unsigned int)buffer->nFilledLen);
if (arbitrary_bytes) {
post_event ((unsigned long)hComp,(unsigned long)buffer,
OMX_COMPONENT_GENERATE_ETB_ARBITRARY);
} else {
post_event ((unsigned long)hComp,(unsigned long)buffer,OMX_COMPONENT_GENERATE_ETB);
}
time_stamp_dts.insert_timestamp(buffer);
return OMX_ErrorNone;
}
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27890802
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVdec problem #6)
CRs-Fixed: 1008882
Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e
CWE ID: | OMX_ERRORTYPE omx_vdec::empty_this_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
OMX_ERRORTYPE ret1 = OMX_ErrorNone;
unsigned int nBufferIndex = drv_ctx.ip_buf.actualcount;
if (m_state != OMX_StateExecuting &&
m_state != OMX_StatePause &&
m_state != OMX_StateIdle) {
DEBUG_PRINT_ERROR("Empty this buffer in Invalid State");
return OMX_ErrorInvalidState;
}
if (buffer == NULL) {
DEBUG_PRINT_ERROR("ERROR:ETB Buffer is NULL");
return OMX_ErrorBadParameter;
}
if (!m_inp_bEnabled) {
DEBUG_PRINT_ERROR("ERROR:ETB incorrect state operation, input port is disabled.");
return OMX_ErrorIncorrectStateOperation;
}
if (buffer->nInputPortIndex != OMX_CORE_INPUT_PORT_INDEX) {
DEBUG_PRINT_ERROR("ERROR:ETB invalid port in header %u", (unsigned int)buffer->nInputPortIndex);
return OMX_ErrorBadPortIndex;
}
#ifdef _ANDROID_
if (iDivXDrmDecrypt) {
OMX_ERRORTYPE drmErr = iDivXDrmDecrypt->Decrypt(buffer);
if (drmErr != OMX_ErrorNone) {
DEBUG_PRINT_LOW("ERROR:iDivXDrmDecrypt->Decrypt %d", drmErr);
}
}
#endif //_ANDROID_
if (perf_flag) {
if (!latency) {
dec_time.stop();
latency = dec_time.processing_time_us();
dec_time.start();
}
}
if (arbitrary_bytes) {
nBufferIndex = buffer - m_inp_heap_ptr;
} else {
if (input_use_buffer == true) {
nBufferIndex = buffer - m_inp_heap_ptr;
m_inp_mem_ptr[nBufferIndex].nFilledLen = m_inp_heap_ptr[nBufferIndex].nFilledLen;
m_inp_mem_ptr[nBufferIndex].nTimeStamp = m_inp_heap_ptr[nBufferIndex].nTimeStamp;
m_inp_mem_ptr[nBufferIndex].nFlags = m_inp_heap_ptr[nBufferIndex].nFlags;
buffer = &m_inp_mem_ptr[nBufferIndex];
DEBUG_PRINT_LOW("Non-Arbitrary mode - buffer address is: malloc %p, pmem%p in Index %d, buffer %p of size %u",
&m_inp_heap_ptr[nBufferIndex], &m_inp_mem_ptr[nBufferIndex],nBufferIndex, buffer, (unsigned int)buffer->nFilledLen);
} else {
nBufferIndex = buffer - m_inp_mem_ptr;
}
}
if (nBufferIndex > drv_ctx.ip_buf.actualcount ) {
DEBUG_PRINT_ERROR("ERROR:ETB nBufferIndex is invalid");
return OMX_ErrorBadParameter;
}
if (buffer->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
codec_config_flag = true;
DEBUG_PRINT_LOW("%s: codec_config buffer", __FUNCTION__);
}
DEBUG_PRINT_LOW("[ETB] BHdr(%p) pBuf(%p) nTS(%lld) nFL(%u)",
buffer, buffer->pBuffer, buffer->nTimeStamp, (unsigned int)buffer->nFilledLen);
if (arbitrary_bytes) {
post_event ((unsigned long)hComp,(unsigned long)buffer,
OMX_COMPONENT_GENERATE_ETB_ARBITRARY);
} else {
post_event ((unsigned long)hComp,(unsigned long)buffer,OMX_COMPONENT_GENERATE_ETB);
}
time_stamp_dts.insert_timestamp(buffer);
return OMX_ErrorNone;
}
| 173,749 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: _gnutls_ciphertext2compressed (gnutls_session_t session,
opaque * compress_data,
int compress_size,
gnutls_datum_t ciphertext, uint8_t type)
{
uint8_t MAC[MAX_HASH_SIZE];
uint16_t c_length;
uint8_t pad;
int length;
digest_hd_st td;
uint16_t blocksize;
int ret, i, pad_failed = 0;
uint8_t major, minor;
gnutls_protocol_t ver;
int hash_size =
_gnutls_hash_get_algo_len (session->security_parameters.
read_mac_algorithm);
ver = gnutls_protocol_get_version (session);
minor = _gnutls_version_get_minor (ver);
major = _gnutls_version_get_major (ver);
blocksize = _gnutls_cipher_get_block_size (session->security_parameters.
read_bulk_cipher_algorithm);
/* initialize MAC
*/
ret = mac_init (&td, session->security_parameters.read_mac_algorithm,
session->connection_state.read_mac_secret.data,
session->connection_state.read_mac_secret.size, ver);
if (ret < 0
&& session->security_parameters.read_mac_algorithm != GNUTLS_MAC_NULL)
{
gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
/* actual decryption (inplace)
*/
{
gnutls_assert ();
return ret;
}
length = ciphertext.size - hash_size;
break;
case CIPHER_BLOCK:
if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0))
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
if ((ret = _gnutls_cipher_decrypt (&session->connection_state.
read_cipher_state,
ciphertext.data,
ciphertext.size)) < 0)
{
gnutls_assert ();
return ret;
}
/* ignore the IV in TLS 1.1.
*/
if (session->security_parameters.version >= GNUTLS_TLS1_1)
{
ciphertext.size -= blocksize;
ciphertext.data += blocksize;
if (ciphertext.size == 0)
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
}
pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */
length = ciphertext.size - hash_size - pad;
if (pad > ciphertext.size - hash_size)
{
gnutls_assert ();
pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */
length = ciphertext.size - hash_size - pad;
if (pad > ciphertext.size - hash_size)
{
gnutls_assert ();
/* We do not fail here. We check below for the
*/
if (ver >= GNUTLS_TLS1 && pad_failed == 0)
pad_failed = GNUTLS_E_DECRYPTION_FAILED;
}
/* Check the pading bytes (TLS 1.x)
*/
if (ver >= GNUTLS_TLS1 && pad_failed == 0)
gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
if (length < 0)
length = 0;
c_length = _gnutls_conv_uint16 ((uint16_t) length);
/* Pass the type, version, length and compressed through
* MAC.
*/
if (session->security_parameters.read_mac_algorithm != GNUTLS_MAC_NULL)
{
_gnutls_hmac (&td,
UINT64DATA (session->connection_state.
read_sequence_number), 8);
_gnutls_hmac (&td, &type, 1);
if (ver >= GNUTLS_TLS1)
{ /* TLS 1.x */
_gnutls_hmac (&td, &major, 1);
_gnutls_hmac (&td, &minor, 1);
}
_gnutls_hmac (&td, &c_length, 2);
if (length > 0)
_gnutls_hmac (&td, ciphertext.data, length);
mac_deinit (&td, MAC, ver);
}
/* This one was introduced to avoid a timing attack against the TLS
* 1.0 protocol.
*/
if (pad_failed != 0)
return pad_failed;
/* HMAC was not the same.
*/
if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0)
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
/* copy the decrypted stuff to compress_data.
*/
if (compress_size < length)
{
gnutls_assert ();
return GNUTLS_E_DECOMPRESSION_FAILED;
}
memcpy (compress_data, ciphertext.data, length);
return length;
}
Commit Message:
CWE ID: CWE-189 | _gnutls_ciphertext2compressed (gnutls_session_t session,
opaque * compress_data,
int compress_size,
gnutls_datum_t ciphertext, uint8_t type)
{
uint8_t MAC[MAX_HASH_SIZE];
uint16_t c_length;
uint8_t pad;
int length;
digest_hd_st td;
uint16_t blocksize;
int ret, i, pad_failed = 0;
uint8_t major, minor;
gnutls_protocol_t ver;
int hash_size =
_gnutls_hash_get_algo_len (session->security_parameters.
read_mac_algorithm);
ver = gnutls_protocol_get_version (session);
minor = _gnutls_version_get_minor (ver);
major = _gnutls_version_get_major (ver);
blocksize = _gnutls_cipher_get_block_size (session->security_parameters.
read_bulk_cipher_algorithm);
/* initialize MAC
*/
ret = mac_init (&td, session->security_parameters.read_mac_algorithm,
session->connection_state.read_mac_secret.data,
session->connection_state.read_mac_secret.size, ver);
if (ret < 0
&& session->security_parameters.read_mac_algorithm != GNUTLS_MAC_NULL)
{
gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
if (ciphertext.size < (unsigned) blocksize + hash_size)
{
_gnutls_record_log
("REC[%x]: Short record length %d < %d + %d (under attack?)\n",
session, ciphertext.size, blocksize, hash_size);
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
/* actual decryption (inplace)
*/
{
gnutls_assert ();
return ret;
}
length = ciphertext.size - hash_size;
break;
case CIPHER_BLOCK:
if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0))
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
if ((ret = _gnutls_cipher_decrypt (&session->connection_state.
read_cipher_state,
ciphertext.data,
ciphertext.size)) < 0)
{
gnutls_assert ();
return ret;
}
/* ignore the IV in TLS 1.1.
*/
if (session->security_parameters.version >= GNUTLS_TLS1_1)
{
ciphertext.size -= blocksize;
ciphertext.data += blocksize;
if (ciphertext.size == 0)
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
}
pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */
length = ciphertext.size - hash_size - pad;
if (pad > ciphertext.size - hash_size)
{
gnutls_assert ();
pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */
if ((int)pad > (int)ciphertext.size - hash_size)
{
gnutls_assert ();
/* We do not fail here. We check below for the
*/
if (ver >= GNUTLS_TLS1 && pad_failed == 0)
pad_failed = GNUTLS_E_DECRYPTION_FAILED;
}
length = ciphertext.size - hash_size - pad;
/* Check the pading bytes (TLS 1.x)
*/
if (ver >= GNUTLS_TLS1 && pad_failed == 0)
gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
if (length < 0)
length = 0;
c_length = _gnutls_conv_uint16 ((uint16_t) length);
/* Pass the type, version, length and compressed through
* MAC.
*/
if (session->security_parameters.read_mac_algorithm != GNUTLS_MAC_NULL)
{
_gnutls_hmac (&td,
UINT64DATA (session->connection_state.
read_sequence_number), 8);
_gnutls_hmac (&td, &type, 1);
if (ver >= GNUTLS_TLS1)
{ /* TLS 1.x */
_gnutls_hmac (&td, &major, 1);
_gnutls_hmac (&td, &minor, 1);
}
_gnutls_hmac (&td, &c_length, 2);
if (length > 0)
_gnutls_hmac (&td, ciphertext.data, length);
mac_deinit (&td, MAC, ver);
}
/* This one was introduced to avoid a timing attack against the TLS
* 1.0 protocol.
*/
if (pad_failed != 0)
return pad_failed;
/* HMAC was not the same.
*/
if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0)
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
/* copy the decrypted stuff to compress_data.
*/
if (compress_size < length)
{
gnutls_assert ();
return GNUTLS_E_DECOMPRESSION_FAILED;
}
memcpy (compress_data, ciphertext.data, length);
return length;
}
| 165,146 |
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 gamma_transform_test(png_modifier *pm,
PNG_CONST png_byte colour_type, PNG_CONST png_byte bit_depth,
PNG_CONST int palette_number,
PNG_CONST int interlace_type, PNG_CONST double file_gamma,
PNG_CONST double screen_gamma, PNG_CONST png_byte sbit,
PNG_CONST int use_input_precision, PNG_CONST int scale16)
{
size_t pos = 0;
char name[64];
if (sbit != bit_depth && sbit != 0)
{
pos = safecat(name, sizeof name, pos, "sbit(");
pos = safecatn(name, sizeof name, pos, sbit);
pos = safecat(name, sizeof name, pos, ") ");
}
else
pos = safecat(name, sizeof name, pos, "gamma ");
if (scale16)
pos = safecat(name, sizeof name, pos, "16to8 ");
pos = safecatd(name, sizeof name, pos, file_gamma, 3);
pos = safecat(name, sizeof name, pos, "->");
pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
file_gamma, screen_gamma, sbit, 0, name, use_input_precision,
scale16, pm->test_gamma_expand16, 0 , 0, 0);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | static void gamma_transform_test(png_modifier *pm,
const png_byte colour_type, const png_byte bit_depth,
const int palette_number,
const int interlace_type, const double file_gamma,
const double screen_gamma, const png_byte sbit,
const int use_input_precision, const int scale16)
{
size_t pos = 0;
char name[64];
if (sbit != bit_depth && sbit != 0)
{
pos = safecat(name, sizeof name, pos, "sbit(");
pos = safecatn(name, sizeof name, pos, sbit);
pos = safecat(name, sizeof name, pos, ") ");
}
else
pos = safecat(name, sizeof name, pos, "gamma ");
if (scale16)
pos = safecat(name, sizeof name, pos, "16to8 ");
pos = safecatd(name, sizeof name, pos, file_gamma, 3);
pos = safecat(name, sizeof name, pos, "->");
pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
file_gamma, screen_gamma, sbit, 0, name, use_input_precision,
scale16, pm->test_gamma_expand16, 0 , 0, 0);
}
| 173,615 |
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 ExtensionSettingsHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
RegisterTitle(localized_strings, "extensionSettings",
IDS_MANAGE_EXTENSIONS_SETTING_WINDOWS_TITLE);
localized_strings->SetString("extensionSettingsVisitWebsite",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_VISIT_WEBSITE));
localized_strings->SetString("extensionSettingsDeveloperMode",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_DEVELOPER_MODE_LINK));
localized_strings->SetString("extensionSettingsNoExtensions",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_NONE_INSTALLED));
localized_strings->SetString("extensionSettingsSuggestGallery",
l10n_util::GetStringFUTF16(IDS_EXTENSIONS_NONE_INSTALLED_SUGGEST_GALLERY,
ASCIIToUTF16(google_util::AppendGoogleLocaleParam(
GURL(extension_urls::GetWebstoreLaunchURL())).spec())));
localized_strings->SetString("extensionSettingsGetMoreExtensions",
l10n_util::GetStringFUTF16(IDS_GET_MORE_EXTENSIONS,
ASCIIToUTF16(google_util::AppendGoogleLocaleParam(
GURL(extension_urls::GetWebstoreLaunchURL())).spec())));
localized_strings->SetString("extensionSettingsExtensionId",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_ID));
localized_strings->SetString("extensionSettingsExtensionPath",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_PATH));
localized_strings->SetString("extensionSettingsInspectViews",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_INSPECT_VIEWS));
localized_strings->SetString("viewIncognito",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_VIEW_INCOGNITO));
localized_strings->SetString("extensionSettingsEnable",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE));
localized_strings->SetString("extensionSettingsEnabled",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLED));
localized_strings->SetString("extensionSettingsRemove",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_REMOVE));
localized_strings->SetString("extensionSettingsEnableIncognito",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE_INCOGNITO));
localized_strings->SetString("extensionSettingsAllowFileAccess",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_ALLOW_FILE_ACCESS));
localized_strings->SetString("extensionSettingsIncognitoWarning",
l10n_util::GetStringFUTF16(IDS_EXTENSIONS_INCOGNITO_WARNING,
l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));
localized_strings->SetString("extensionSettingsReload",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_RELOAD));
localized_strings->SetString("extensionSettingsOptions",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_OPTIONS));
localized_strings->SetString("extensionSettingsPolicyControlled",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_POLICY_CONTROLLED));
localized_strings->SetString("extensionSettingsShowButton",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_BUTTON));
localized_strings->SetString("extensionSettingsLoadUnpackedButton",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_UNPACKED_BUTTON));
localized_strings->SetString("extensionSettingsPackButton",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_PACK_BUTTON));
localized_strings->SetString("extensionSettingsUpdateButton",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_UPDATE_BUTTON));
localized_strings->SetString("extensionSettingsCrashMessage",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_CRASHED_EXTENSION));
localized_strings->SetString("extensionSettingsInDevelopment",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_IN_DEVELOPMENT));
localized_strings->SetString("extensionSettingsWarningsTitle",
l10n_util::GetStringUTF16(IDS_EXTENSION_WARNINGS_TITLE));
localized_strings->SetString("extensionSettingsShowDetails",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_DETAILS));
localized_strings->SetString("extensionSettingsHideDetails",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_HIDE_DETAILS));
}
Commit Message: [i18n-fixlet] Make strings branding specific in extension code.
IDS_EXTENSIONS_UNINSTALL
IDS_EXTENSIONS_INCOGNITO_WARNING
IDS_EXTENSION_INSTALLED_HEADING
IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug.
IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE
BUG=NONE
TEST=NONE
Review URL: http://codereview.chromium.org/9107061
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void ExtensionSettingsHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
RegisterTitle(localized_strings, "extensionSettings",
IDS_MANAGE_EXTENSIONS_SETTING_WINDOWS_TITLE);
localized_strings->SetString("extensionSettingsVisitWebsite",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_VISIT_WEBSITE));
localized_strings->SetString("extensionSettingsDeveloperMode",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_DEVELOPER_MODE_LINK));
localized_strings->SetString("extensionSettingsNoExtensions",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_NONE_INSTALLED));
localized_strings->SetString("extensionSettingsSuggestGallery",
l10n_util::GetStringFUTF16(IDS_EXTENSIONS_NONE_INSTALLED_SUGGEST_GALLERY,
ASCIIToUTF16(google_util::AppendGoogleLocaleParam(
GURL(extension_urls::GetWebstoreLaunchURL())).spec())));
localized_strings->SetString("extensionSettingsGetMoreExtensions",
l10n_util::GetStringFUTF16(IDS_GET_MORE_EXTENSIONS,
ASCIIToUTF16(google_util::AppendGoogleLocaleParam(
GURL(extension_urls::GetWebstoreLaunchURL())).spec())));
localized_strings->SetString("extensionSettingsExtensionId",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_ID));
localized_strings->SetString("extensionSettingsExtensionPath",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_PATH));
localized_strings->SetString("extensionSettingsInspectViews",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_INSPECT_VIEWS));
localized_strings->SetString("viewIncognito",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_VIEW_INCOGNITO));
localized_strings->SetString("extensionSettingsEnable",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE));
localized_strings->SetString("extensionSettingsEnabled",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLED));
localized_strings->SetString("extensionSettingsRemove",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_REMOVE));
localized_strings->SetString("extensionSettingsEnableIncognito",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE_INCOGNITO));
localized_strings->SetString("extensionSettingsAllowFileAccess",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_ALLOW_FILE_ACCESS));
localized_strings->SetString("extensionSettingsIncognitoWarning",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_INCOGNITO_WARNING));
localized_strings->SetString("extensionSettingsReload",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_RELOAD));
localized_strings->SetString("extensionSettingsOptions",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_OPTIONS));
localized_strings->SetString("extensionSettingsPolicyControlled",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_POLICY_CONTROLLED));
localized_strings->SetString("extensionSettingsShowButton",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_BUTTON));
localized_strings->SetString("extensionSettingsLoadUnpackedButton",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_UNPACKED_BUTTON));
localized_strings->SetString("extensionSettingsPackButton",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_PACK_BUTTON));
localized_strings->SetString("extensionSettingsUpdateButton",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_UPDATE_BUTTON));
localized_strings->SetString("extensionSettingsCrashMessage",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_CRASHED_EXTENSION));
localized_strings->SetString("extensionSettingsInDevelopment",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_IN_DEVELOPMENT));
localized_strings->SetString("extensionSettingsWarningsTitle",
l10n_util::GetStringUTF16(IDS_EXTENSION_WARNINGS_TITLE));
localized_strings->SetString("extensionSettingsShowDetails",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_DETAILS));
localized_strings->SetString("extensionSettingsHideDetails",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_HIDE_DETAILS));
}
| 170,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: update_info_partition_on_linux_dmmp (Device *device)
{
const gchar *dm_name;
const gchar* const *targets_type;
const gchar* const *targets_params;
gchar *params;
gint linear_slave_major;
gint linear_slave_minor;
guint64 offset_sectors;
Device *linear_slave;
gchar *s;
params = NULL;
dm_name = g_udev_device_get_property (device->priv->d, "DM_NAME");
if (dm_name == NULL)
goto out;
targets_type = g_udev_device_get_property_as_strv (device->priv->d, "UDISKS_DM_TARGETS_TYPE");
if (targets_type == NULL || g_strcmp0 (targets_type[0], "linear") != 0)
goto out;
goto out;
params = decode_udev_encoded_string (targets_params[0]);
if (sscanf (params,
"%d:%d %" G_GUINT64_FORMAT,
&linear_slave_major,
&linear_slave_minor,
&offset_sectors) != 3)
goto out;
linear_slave = daemon_local_find_by_dev (device->priv->daemon,
makedev (linear_slave_major, linear_slave_minor));
if (linear_slave == NULL)
goto out;
if (!linear_slave->priv->device_is_linux_dmmp)
goto out;
/* The Partition* properties has been set as part of
* update_info_partition() by reading UDISKS_PARTITION_*
* properties.. so here we bascially just update the presentation
* device file name and and whether the device is a drive.
*/
s = g_strdup_printf ("/dev/mapper/%s", dm_name);
device_set_device_file_presentation (device, s);
g_free (s);
device_set_device_is_drive (device, FALSE);
out:
g_free (params);
return TRUE;
}
Commit Message:
CWE ID: CWE-200 | update_info_partition_on_linux_dmmp (Device *device)
{
const gchar *dm_name;
const gchar* const *targets_type;
const gchar* const *targets_params;
gchar *params;
gint linear_slave_major;
gint linear_slave_minor;
guint64 offset_sectors;
Device *linear_slave;
gchar *s;
params = NULL;
dm_name = g_udev_device_get_property (device->priv->d, "DM_NAME");
if (dm_name == NULL)
goto out;
targets_type = g_udev_device_get_property_as_strv (device->priv->d, "UDISKS_DM_TARGETS_TYPE");
/* If we ever need this for other types than "linear", remember to update
udisks-dm-export.c as well. */
if (targets_type == NULL || g_strcmp0 (targets_type[0], "linear") != 0)
goto out;
goto out;
params = decode_udev_encoded_string (targets_params[0]);
if (sscanf (params,
"%d:%d %" G_GUINT64_FORMAT,
&linear_slave_major,
&linear_slave_minor,
&offset_sectors) != 3)
goto out;
linear_slave = daemon_local_find_by_dev (device->priv->daemon,
makedev (linear_slave_major, linear_slave_minor));
if (linear_slave == NULL)
goto out;
if (!linear_slave->priv->device_is_linux_dmmp)
goto out;
/* The Partition* properties has been set as part of
* update_info_partition() by reading UDISKS_PARTITION_*
* properties.. so here we bascially just update the presentation
* device file name and and whether the device is a drive.
*/
s = g_strdup_printf ("/dev/mapper/%s", dm_name);
device_set_device_file_presentation (device, s);
g_free (s);
device_set_device_is_drive (device, FALSE);
out:
g_free (params);
return TRUE;
}
| 165,132 |
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 SoftAAC2::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
UCHAR* inBuffer[FILEREAD_MAX_LAYERS];
UINT inBufferLength[FILEREAD_MAX_LAYERS] = {0};
UINT bytesValid[FILEREAD_MAX_LAYERS] = {0};
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while ((!inQueue.empty() || mEndOfInput) && !outQueue.empty()) {
if (!inQueue.empty()) {
INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT];
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
mEndOfInput = (inHeader->nFlags & OMX_BUFFERFLAG_EOS) != 0;
if (mInputBufferCount == 0 && !(inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG)) {
ALOGE("first buffer should have OMX_BUFFERFLAG_CODECCONFIG set");
inHeader->nFlags |= OMX_BUFFERFLAG_CODECCONFIG;
}
if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) != 0) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
inBuffer[0] = inHeader->pBuffer + inHeader->nOffset;
inBufferLength[0] = inHeader->nFilledLen;
AAC_DECODER_ERROR decoderErr =
aacDecoder_ConfigRaw(mAACDecoder,
inBuffer,
inBufferLength);
if (decoderErr != AAC_DEC_OK) {
ALOGW("aacDecoder_ConfigRaw decoderErr = 0x%4.4x", decoderErr);
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
return;
}
mInputBufferCount++;
mOutputBufferCount++; // fake increase of outputBufferCount to keep the counters aligned
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
mLastInHeader = NULL;
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
configureDownmix();
if (mStreamInfo->sampleRate && mStreamInfo->numChannels) {
ALOGI("Initially configuring decoder: %d Hz, %d channels",
mStreamInfo->sampleRate,
mStreamInfo->numChannels);
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
}
return;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
mLastInHeader = NULL;
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
continue;
}
if (mIsADTS) {
size_t adtsHeaderSize = 0;
const uint8_t *adtsHeader = inHeader->pBuffer + inHeader->nOffset;
bool signalError = false;
if (inHeader->nFilledLen < 7) {
ALOGE("Audio data too short to contain even the ADTS header. "
"Got %d bytes.", inHeader->nFilledLen);
hexdump(adtsHeader, inHeader->nFilledLen);
signalError = true;
} else {
bool protectionAbsent = (adtsHeader[1] & 1);
unsigned aac_frame_length =
((adtsHeader[3] & 3) << 11)
| (adtsHeader[4] << 3)
| (adtsHeader[5] >> 5);
if (inHeader->nFilledLen < aac_frame_length) {
ALOGE("Not enough audio data for the complete frame. "
"Got %d bytes, frame size according to the ADTS "
"header is %u bytes.",
inHeader->nFilledLen, aac_frame_length);
hexdump(adtsHeader, inHeader->nFilledLen);
signalError = true;
} else {
adtsHeaderSize = (protectionAbsent ? 7 : 9);
inBuffer[0] = (UCHAR *)adtsHeader + adtsHeaderSize;
inBufferLength[0] = aac_frame_length - adtsHeaderSize;
inHeader->nOffset += adtsHeaderSize;
inHeader->nFilledLen -= adtsHeaderSize;
}
}
if (signalError) {
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorStreamCorrupt, ERROR_MALFORMED, NULL);
return;
}
mBufferSizes.add(inBufferLength[0]);
if (mLastInHeader != inHeader) {
mBufferTimestamps.add(inHeader->nTimeStamp);
mLastInHeader = inHeader;
} else {
int64_t currentTime = mBufferTimestamps.top();
currentTime += mStreamInfo->aacSamplesPerFrame *
1000000ll / mStreamInfo->aacSampleRate;
mBufferTimestamps.add(currentTime);
}
} else {
inBuffer[0] = inHeader->pBuffer + inHeader->nOffset;
inBufferLength[0] = inHeader->nFilledLen;
mLastInHeader = inHeader;
mBufferTimestamps.add(inHeader->nTimeStamp);
mBufferSizes.add(inHeader->nFilledLen);
}
bytesValid[0] = inBufferLength[0];
INT prevSampleRate = mStreamInfo->sampleRate;
INT prevNumChannels = mStreamInfo->numChannels;
aacDecoder_Fill(mAACDecoder,
inBuffer,
inBufferLength,
bytesValid);
mDrcWrap.submitStreamData(mStreamInfo);
mDrcWrap.update();
UINT inBufferUsedLength = inBufferLength[0] - bytesValid[0];
inHeader->nFilledLen -= inBufferUsedLength;
inHeader->nOffset += inBufferUsedLength;
AAC_DECODER_ERROR decoderErr;
int numLoops = 0;
do {
if (outputDelayRingBufferSpaceLeft() <
(mStreamInfo->frameSize * mStreamInfo->numChannels)) {
ALOGV("skipping decode: not enough space left in ringbuffer");
break;
}
int numConsumed = mStreamInfo->numTotalBytes;
decoderErr = aacDecoder_DecodeFrame(mAACDecoder,
tmpOutBuffer,
2048 * MAX_CHANNEL_COUNT,
0 /* flags */);
numConsumed = mStreamInfo->numTotalBytes - numConsumed;
numLoops++;
if (decoderErr == AAC_DEC_NOT_ENOUGH_BITS) {
break;
}
mDecodedSizes.add(numConsumed);
if (decoderErr != AAC_DEC_OK) {
ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr);
}
if (bytesValid[0] != 0) {
ALOGE("bytesValid[0] != 0 should never happen");
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
size_t numOutBytes =
mStreamInfo->frameSize * sizeof(int16_t) * mStreamInfo->numChannels;
if (decoderErr == AAC_DEC_OK) {
if (!outputDelayRingBufferPutSamples(tmpOutBuffer,
mStreamInfo->frameSize * mStreamInfo->numChannels)) {
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
return;
}
} else {
ALOGW("AAC decoder returned error 0x%4.4x, substituting silence", decoderErr);
memset(tmpOutBuffer, 0, numOutBytes); // TODO: check for overflow
if (!outputDelayRingBufferPutSamples(tmpOutBuffer,
mStreamInfo->frameSize * mStreamInfo->numChannels)) {
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
return;
}
if (inHeader) {
inHeader->nFilledLen = 0;
}
aacDecoder_SetParam(mAACDecoder, AAC_TPDEC_CLEAR_BUFFER, 1);
mBufferSizes.pop();
int n = 0;
for (int i = 0; i < numLoops; i++) {
n += mDecodedSizes.itemAt(mDecodedSizes.size() - numLoops + i);
}
mBufferSizes.add(n);
}
/*
* AAC+/eAAC+ streams can be signalled in two ways: either explicitly
* or implicitly, according to MPEG4 spec. AAC+/eAAC+ is a dual
* rate system and the sampling rate in the final output is actually
* doubled compared with the core AAC decoder sampling rate.
*
* Explicit signalling is done by explicitly defining SBR audio object
* type in the bitstream. Implicit signalling is done by embedding
* SBR content in AAC extension payload specific to SBR, and hence
* requires an AAC decoder to perform pre-checks on actual audio frames.
*
* Thus, we could not say for sure whether a stream is
* AAC+/eAAC+ until the first data frame is decoded.
*/
if (mInputBufferCount <= 2 || mOutputBufferCount > 1) { // TODO: <= 1
if (mStreamInfo->sampleRate != prevSampleRate ||
mStreamInfo->numChannels != prevNumChannels) {
ALOGI("Reconfiguring decoder: %d->%d Hz, %d->%d channels",
prevSampleRate, mStreamInfo->sampleRate,
prevNumChannels, mStreamInfo->numChannels);
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
if (inHeader && inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
mInputBufferCount++;
inQueue.erase(inQueue.begin());
mLastInHeader = NULL;
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
return;
}
} else if (!mStreamInfo->sampleRate || !mStreamInfo->numChannels) {
ALOGW("Invalid AAC stream");
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
return;
}
if (inHeader && inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
mInputBufferCount++;
inQueue.erase(inQueue.begin());
mLastInHeader = NULL;
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
} else {
ALOGV("inHeader->nFilledLen = %d", inHeader ? inHeader->nFilledLen : 0);
}
} while (decoderErr == AAC_DEC_OK);
}
int32_t outputDelay = mStreamInfo->outputDelay * mStreamInfo->numChannels;
if (!mEndOfInput && mOutputDelayCompensated < outputDelay) {
int32_t toCompensate = outputDelay - mOutputDelayCompensated;
int32_t discard = outputDelayRingBufferSamplesAvailable();
if (discard > toCompensate) {
discard = toCompensate;
}
int32_t discarded = outputDelayRingBufferGetSamples(0, discard);
mOutputDelayCompensated += discarded;
continue;
}
if (mEndOfInput) {
while (mOutputDelayCompensated > 0) {
INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT];
mDrcWrap.submitStreamData(mStreamInfo);
mDrcWrap.update();
AAC_DECODER_ERROR decoderErr =
aacDecoder_DecodeFrame(mAACDecoder,
tmpOutBuffer,
2048 * MAX_CHANNEL_COUNT,
AACDEC_FLUSH);
if (decoderErr != AAC_DEC_OK) {
ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr);
}
int32_t tmpOutBufferSamples = mStreamInfo->frameSize * mStreamInfo->numChannels;
if (tmpOutBufferSamples > mOutputDelayCompensated) {
tmpOutBufferSamples = mOutputDelayCompensated;
}
outputDelayRingBufferPutSamples(tmpOutBuffer, tmpOutBufferSamples);
mOutputDelayCompensated -= tmpOutBufferSamples;
}
}
while (!outQueue.empty()
&& outputDelayRingBufferSamplesAvailable()
>= mStreamInfo->frameSize * mStreamInfo->numChannels) {
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
if (outHeader->nOffset != 0) {
ALOGE("outHeader->nOffset != 0 is not handled");
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
INT_PCM *outBuffer =
reinterpret_cast<INT_PCM *>(outHeader->pBuffer + outHeader->nOffset);
int samplesize = mStreamInfo->numChannels * sizeof(int16_t);
if (outHeader->nOffset
+ mStreamInfo->frameSize * samplesize
> outHeader->nAllocLen) {
ALOGE("buffer overflow");
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
int available = outputDelayRingBufferSamplesAvailable();
int numSamples = outHeader->nAllocLen / sizeof(int16_t);
if (numSamples > available) {
numSamples = available;
}
int64_t currentTime = 0;
if (available) {
int numFrames = numSamples / (mStreamInfo->frameSize * mStreamInfo->numChannels);
numSamples = numFrames * (mStreamInfo->frameSize * mStreamInfo->numChannels);
ALOGV("%d samples available (%d), or %d frames",
numSamples, available, numFrames);
int64_t *nextTimeStamp = &mBufferTimestamps.editItemAt(0);
currentTime = *nextTimeStamp;
int32_t *currentBufLeft = &mBufferSizes.editItemAt(0);
for (int i = 0; i < numFrames; i++) {
int32_t decodedSize = mDecodedSizes.itemAt(0);
mDecodedSizes.removeAt(0);
ALOGV("decoded %d of %d", decodedSize, *currentBufLeft);
if (*currentBufLeft > decodedSize) {
*currentBufLeft -= decodedSize;
*nextTimeStamp += mStreamInfo->aacSamplesPerFrame *
1000000ll / mStreamInfo->aacSampleRate;
ALOGV("adjusted nextTimeStamp/size to %lld/%d",
(long long) *nextTimeStamp, *currentBufLeft);
} else {
if (mBufferTimestamps.size() > 0) {
mBufferTimestamps.removeAt(0);
nextTimeStamp = &mBufferTimestamps.editItemAt(0);
mBufferSizes.removeAt(0);
currentBufLeft = &mBufferSizes.editItemAt(0);
ALOGV("moved to next time/size: %lld/%d",
(long long) *nextTimeStamp, *currentBufLeft);
}
numFrames = i + 1;
numSamples = numFrames * mStreamInfo->frameSize * mStreamInfo->numChannels;
break;
}
}
ALOGV("getting %d from ringbuffer", numSamples);
int32_t ns = outputDelayRingBufferGetSamples(outBuffer, numSamples);
if (ns != numSamples) {
ALOGE("not a complete frame of samples available");
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
}
outHeader->nFilledLen = numSamples * sizeof(int16_t);
if (mEndOfInput && !outQueue.empty() && outputDelayRingBufferSamplesAvailable() == 0) {
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
mEndOfOutput = true;
} else {
outHeader->nFlags = 0;
}
outHeader->nTimeStamp = currentTime;
mOutputBufferCount++;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
ALOGV("out timestamp %lld / %d", outHeader->nTimeStamp, outHeader->nFilledLen);
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
if (mEndOfInput) {
int ringBufAvail = outputDelayRingBufferSamplesAvailable();
if (!outQueue.empty()
&& ringBufAvail < mStreamInfo->frameSize * mStreamInfo->numChannels) {
if (!mEndOfOutput) {
mEndOfOutput = true;
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
INT_PCM *outBuffer = reinterpret_cast<INT_PCM *>(outHeader->pBuffer
+ outHeader->nOffset);
int32_t ns = outputDelayRingBufferGetSamples(outBuffer, ringBufAvail);
if (ns < 0) {
ns = 0;
}
outHeader->nFilledLen = ns;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outHeader->nTimeStamp = mBufferTimestamps.itemAt(0);
mBufferTimestamps.clear();
mBufferSizes.clear();
mDecodedSizes.clear();
mOutputBufferCount++;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
break; // if outQueue not empty but no more output
}
}
}
}
Commit Message: SoftAAC2: fix crash on all-zero adts buffer
Bug: 29153599
Change-Id: I1cb81c054098b86cf24f024f8479909ca7bc85a6
CWE ID: CWE-20 | void SoftAAC2::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
UCHAR* inBuffer[FILEREAD_MAX_LAYERS];
UINT inBufferLength[FILEREAD_MAX_LAYERS] = {0};
UINT bytesValid[FILEREAD_MAX_LAYERS] = {0};
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while ((!inQueue.empty() || mEndOfInput) && !outQueue.empty()) {
if (!inQueue.empty()) {
INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT];
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
mEndOfInput = (inHeader->nFlags & OMX_BUFFERFLAG_EOS) != 0;
if (mInputBufferCount == 0 && !(inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG)) {
ALOGE("first buffer should have OMX_BUFFERFLAG_CODECCONFIG set");
inHeader->nFlags |= OMX_BUFFERFLAG_CODECCONFIG;
}
if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) != 0) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
inBuffer[0] = inHeader->pBuffer + inHeader->nOffset;
inBufferLength[0] = inHeader->nFilledLen;
AAC_DECODER_ERROR decoderErr =
aacDecoder_ConfigRaw(mAACDecoder,
inBuffer,
inBufferLength);
if (decoderErr != AAC_DEC_OK) {
ALOGW("aacDecoder_ConfigRaw decoderErr = 0x%4.4x", decoderErr);
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
return;
}
mInputBufferCount++;
mOutputBufferCount++; // fake increase of outputBufferCount to keep the counters aligned
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
mLastInHeader = NULL;
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
configureDownmix();
if (mStreamInfo->sampleRate && mStreamInfo->numChannels) {
ALOGI("Initially configuring decoder: %d Hz, %d channels",
mStreamInfo->sampleRate,
mStreamInfo->numChannels);
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
}
return;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
mLastInHeader = NULL;
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
continue;
}
if (mIsADTS) {
size_t adtsHeaderSize = 0;
const uint8_t *adtsHeader = inHeader->pBuffer + inHeader->nOffset;
bool signalError = false;
if (inHeader->nFilledLen < 7) {
ALOGE("Audio data too short to contain even the ADTS header. "
"Got %d bytes.", inHeader->nFilledLen);
hexdump(adtsHeader, inHeader->nFilledLen);
signalError = true;
} else {
bool protectionAbsent = (adtsHeader[1] & 1);
unsigned aac_frame_length =
((adtsHeader[3] & 3) << 11)
| (adtsHeader[4] << 3)
| (adtsHeader[5] >> 5);
if (inHeader->nFilledLen < aac_frame_length) {
ALOGE("Not enough audio data for the complete frame. "
"Got %d bytes, frame size according to the ADTS "
"header is %u bytes.",
inHeader->nFilledLen, aac_frame_length);
hexdump(adtsHeader, inHeader->nFilledLen);
signalError = true;
} else {
adtsHeaderSize = (protectionAbsent ? 7 : 9);
if (aac_frame_length < adtsHeaderSize) {
signalError = true;
} else {
inBuffer[0] = (UCHAR *)adtsHeader + adtsHeaderSize;
inBufferLength[0] = aac_frame_length - adtsHeaderSize;
inHeader->nOffset += adtsHeaderSize;
inHeader->nFilledLen -= adtsHeaderSize;
}
}
}
if (signalError) {
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorStreamCorrupt, ERROR_MALFORMED, NULL);
return;
}
mBufferSizes.add(inBufferLength[0]);
if (mLastInHeader != inHeader) {
mBufferTimestamps.add(inHeader->nTimeStamp);
mLastInHeader = inHeader;
} else {
int64_t currentTime = mBufferTimestamps.top();
currentTime += mStreamInfo->aacSamplesPerFrame *
1000000ll / mStreamInfo->aacSampleRate;
mBufferTimestamps.add(currentTime);
}
} else {
inBuffer[0] = inHeader->pBuffer + inHeader->nOffset;
inBufferLength[0] = inHeader->nFilledLen;
mLastInHeader = inHeader;
mBufferTimestamps.add(inHeader->nTimeStamp);
mBufferSizes.add(inHeader->nFilledLen);
}
bytesValid[0] = inBufferLength[0];
INT prevSampleRate = mStreamInfo->sampleRate;
INT prevNumChannels = mStreamInfo->numChannels;
aacDecoder_Fill(mAACDecoder,
inBuffer,
inBufferLength,
bytesValid);
mDrcWrap.submitStreamData(mStreamInfo);
mDrcWrap.update();
UINT inBufferUsedLength = inBufferLength[0] - bytesValid[0];
inHeader->nFilledLen -= inBufferUsedLength;
inHeader->nOffset += inBufferUsedLength;
AAC_DECODER_ERROR decoderErr;
int numLoops = 0;
do {
if (outputDelayRingBufferSpaceLeft() <
(mStreamInfo->frameSize * mStreamInfo->numChannels)) {
ALOGV("skipping decode: not enough space left in ringbuffer");
break;
}
int numConsumed = mStreamInfo->numTotalBytes;
decoderErr = aacDecoder_DecodeFrame(mAACDecoder,
tmpOutBuffer,
2048 * MAX_CHANNEL_COUNT,
0 /* flags */);
numConsumed = mStreamInfo->numTotalBytes - numConsumed;
numLoops++;
if (decoderErr == AAC_DEC_NOT_ENOUGH_BITS) {
break;
}
mDecodedSizes.add(numConsumed);
if (decoderErr != AAC_DEC_OK) {
ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr);
}
if (bytesValid[0] != 0) {
ALOGE("bytesValid[0] != 0 should never happen");
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
size_t numOutBytes =
mStreamInfo->frameSize * sizeof(int16_t) * mStreamInfo->numChannels;
if (decoderErr == AAC_DEC_OK) {
if (!outputDelayRingBufferPutSamples(tmpOutBuffer,
mStreamInfo->frameSize * mStreamInfo->numChannels)) {
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
return;
}
} else {
ALOGW("AAC decoder returned error 0x%4.4x, substituting silence", decoderErr);
memset(tmpOutBuffer, 0, numOutBytes); // TODO: check for overflow
if (!outputDelayRingBufferPutSamples(tmpOutBuffer,
mStreamInfo->frameSize * mStreamInfo->numChannels)) {
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
return;
}
if (inHeader) {
inHeader->nFilledLen = 0;
}
aacDecoder_SetParam(mAACDecoder, AAC_TPDEC_CLEAR_BUFFER, 1);
mBufferSizes.pop();
int n = 0;
for (int i = 0; i < numLoops; i++) {
n += mDecodedSizes.itemAt(mDecodedSizes.size() - numLoops + i);
}
mBufferSizes.add(n);
}
/*
* AAC+/eAAC+ streams can be signalled in two ways: either explicitly
* or implicitly, according to MPEG4 spec. AAC+/eAAC+ is a dual
* rate system and the sampling rate in the final output is actually
* doubled compared with the core AAC decoder sampling rate.
*
* Explicit signalling is done by explicitly defining SBR audio object
* type in the bitstream. Implicit signalling is done by embedding
* SBR content in AAC extension payload specific to SBR, and hence
* requires an AAC decoder to perform pre-checks on actual audio frames.
*
* Thus, we could not say for sure whether a stream is
* AAC+/eAAC+ until the first data frame is decoded.
*/
if (mInputBufferCount <= 2 || mOutputBufferCount > 1) { // TODO: <= 1
if (mStreamInfo->sampleRate != prevSampleRate ||
mStreamInfo->numChannels != prevNumChannels) {
ALOGI("Reconfiguring decoder: %d->%d Hz, %d->%d channels",
prevSampleRate, mStreamInfo->sampleRate,
prevNumChannels, mStreamInfo->numChannels);
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
if (inHeader && inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
mInputBufferCount++;
inQueue.erase(inQueue.begin());
mLastInHeader = NULL;
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
return;
}
} else if (!mStreamInfo->sampleRate || !mStreamInfo->numChannels) {
ALOGW("Invalid AAC stream");
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
return;
}
if (inHeader && inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
mInputBufferCount++;
inQueue.erase(inQueue.begin());
mLastInHeader = NULL;
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
} else {
ALOGV("inHeader->nFilledLen = %d", inHeader ? inHeader->nFilledLen : 0);
}
} while (decoderErr == AAC_DEC_OK);
}
int32_t outputDelay = mStreamInfo->outputDelay * mStreamInfo->numChannels;
if (!mEndOfInput && mOutputDelayCompensated < outputDelay) {
int32_t toCompensate = outputDelay - mOutputDelayCompensated;
int32_t discard = outputDelayRingBufferSamplesAvailable();
if (discard > toCompensate) {
discard = toCompensate;
}
int32_t discarded = outputDelayRingBufferGetSamples(0, discard);
mOutputDelayCompensated += discarded;
continue;
}
if (mEndOfInput) {
while (mOutputDelayCompensated > 0) {
INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT];
mDrcWrap.submitStreamData(mStreamInfo);
mDrcWrap.update();
AAC_DECODER_ERROR decoderErr =
aacDecoder_DecodeFrame(mAACDecoder,
tmpOutBuffer,
2048 * MAX_CHANNEL_COUNT,
AACDEC_FLUSH);
if (decoderErr != AAC_DEC_OK) {
ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr);
}
int32_t tmpOutBufferSamples = mStreamInfo->frameSize * mStreamInfo->numChannels;
if (tmpOutBufferSamples > mOutputDelayCompensated) {
tmpOutBufferSamples = mOutputDelayCompensated;
}
outputDelayRingBufferPutSamples(tmpOutBuffer, tmpOutBufferSamples);
mOutputDelayCompensated -= tmpOutBufferSamples;
}
}
while (!outQueue.empty()
&& outputDelayRingBufferSamplesAvailable()
>= mStreamInfo->frameSize * mStreamInfo->numChannels) {
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
if (outHeader->nOffset != 0) {
ALOGE("outHeader->nOffset != 0 is not handled");
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
INT_PCM *outBuffer =
reinterpret_cast<INT_PCM *>(outHeader->pBuffer + outHeader->nOffset);
int samplesize = mStreamInfo->numChannels * sizeof(int16_t);
if (outHeader->nOffset
+ mStreamInfo->frameSize * samplesize
> outHeader->nAllocLen) {
ALOGE("buffer overflow");
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
int available = outputDelayRingBufferSamplesAvailable();
int numSamples = outHeader->nAllocLen / sizeof(int16_t);
if (numSamples > available) {
numSamples = available;
}
int64_t currentTime = 0;
if (available) {
int numFrames = numSamples / (mStreamInfo->frameSize * mStreamInfo->numChannels);
numSamples = numFrames * (mStreamInfo->frameSize * mStreamInfo->numChannels);
ALOGV("%d samples available (%d), or %d frames",
numSamples, available, numFrames);
int64_t *nextTimeStamp = &mBufferTimestamps.editItemAt(0);
currentTime = *nextTimeStamp;
int32_t *currentBufLeft = &mBufferSizes.editItemAt(0);
for (int i = 0; i < numFrames; i++) {
int32_t decodedSize = mDecodedSizes.itemAt(0);
mDecodedSizes.removeAt(0);
ALOGV("decoded %d of %d", decodedSize, *currentBufLeft);
if (*currentBufLeft > decodedSize) {
*currentBufLeft -= decodedSize;
*nextTimeStamp += mStreamInfo->aacSamplesPerFrame *
1000000ll / mStreamInfo->aacSampleRate;
ALOGV("adjusted nextTimeStamp/size to %lld/%d",
(long long) *nextTimeStamp, *currentBufLeft);
} else {
if (mBufferTimestamps.size() > 0) {
mBufferTimestamps.removeAt(0);
nextTimeStamp = &mBufferTimestamps.editItemAt(0);
mBufferSizes.removeAt(0);
currentBufLeft = &mBufferSizes.editItemAt(0);
ALOGV("moved to next time/size: %lld/%d",
(long long) *nextTimeStamp, *currentBufLeft);
}
numFrames = i + 1;
numSamples = numFrames * mStreamInfo->frameSize * mStreamInfo->numChannels;
break;
}
}
ALOGV("getting %d from ringbuffer", numSamples);
int32_t ns = outputDelayRingBufferGetSamples(outBuffer, numSamples);
if (ns != numSamples) {
ALOGE("not a complete frame of samples available");
mSignalledError = true;
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
}
outHeader->nFilledLen = numSamples * sizeof(int16_t);
if (mEndOfInput && !outQueue.empty() && outputDelayRingBufferSamplesAvailable() == 0) {
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
mEndOfOutput = true;
} else {
outHeader->nFlags = 0;
}
outHeader->nTimeStamp = currentTime;
mOutputBufferCount++;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
ALOGV("out timestamp %lld / %d", outHeader->nTimeStamp, outHeader->nFilledLen);
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
if (mEndOfInput) {
int ringBufAvail = outputDelayRingBufferSamplesAvailable();
if (!outQueue.empty()
&& ringBufAvail < mStreamInfo->frameSize * mStreamInfo->numChannels) {
if (!mEndOfOutput) {
mEndOfOutput = true;
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
INT_PCM *outBuffer = reinterpret_cast<INT_PCM *>(outHeader->pBuffer
+ outHeader->nOffset);
int32_t ns = outputDelayRingBufferGetSamples(outBuffer, ringBufAvail);
if (ns < 0) {
ns = 0;
}
outHeader->nFilledLen = ns;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outHeader->nTimeStamp = mBufferTimestamps.itemAt(0);
mBufferTimestamps.clear();
mBufferSizes.clear();
mDecodedSizes.clear();
mOutputBufferCount++;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
break; // if outQueue not empty but no more output
}
}
}
}
| 173,513 |
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 ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
const struct iovec *iov, loff_t offset,
unsigned long nr_segs)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
ssize_t ret;
size_t count = iov_length(iov, nr_segs);
loff_t final_size = offset + count;
if (rw == WRITE && final_size <= inode->i_size) {
/*
* We could direct write to holes and fallocate.
*
* Allocated blocks to fill the hole are marked as uninitialized
* to prevent paralel buffered read to expose the stale data
* before DIO complete the data IO.
*
* As to previously fallocated extents, ext4 get_block
* will just simply mark the buffer mapped but still
* keep the extents uninitialized.
*
* for non AIO case, we will convert those unwritten extents
* to written after return back from blockdev_direct_IO.
*
* for async DIO, the conversion needs to be defered when
* the IO is completed. The ext4 end_io callback function
* will be called to take care of the conversion work.
* Here for async case, we allocate an io_end structure to
* hook to the iocb.
*/
iocb->private = NULL;
EXT4_I(inode)->cur_aio_dio = NULL;
if (!is_sync_kiocb(iocb)) {
iocb->private = ext4_init_io_end(inode);
if (!iocb->private)
return -ENOMEM;
/*
* we save the io structure for current async
* direct IO, so that later ext4_get_blocks()
* could flag the io structure whether there
* is a unwritten extents needs to be converted
* when IO is completed.
*/
EXT4_I(inode)->cur_aio_dio = iocb->private;
}
ret = blockdev_direct_IO(rw, iocb, inode,
inode->i_sb->s_bdev, iov,
offset, nr_segs,
ext4_get_block_write,
ext4_end_io_dio);
if (iocb->private)
EXT4_I(inode)->cur_aio_dio = NULL;
/*
* The io_end structure takes a reference to the inode,
* that structure needs to be destroyed and the
* reference to the inode need to be dropped, when IO is
* complete, even with 0 byte write, or failed.
*
* In the successful AIO DIO case, the io_end structure will be
* desctroyed and the reference to the inode will be dropped
* after the end_io call back function is called.
*
* In the case there is 0 byte write, or error case, since
* VFS direct IO won't invoke the end_io call back function,
* we need to free the end_io structure here.
*/
if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
ext4_free_io_end(iocb->private);
iocb->private = NULL;
} else if (ret > 0 && ext4_test_inode_state(inode,
EXT4_STATE_DIO_UNWRITTEN)) {
int err;
/*
* for non AIO case, since the IO is already
* completed, we could do the convertion right here
*/
err = ext4_convert_unwritten_extents(inode,
offset, ret);
if (err < 0)
ret = err;
ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
}
return ret;
}
/* for write the the end of file case, we fall back to old way */
return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID: | static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
const struct iovec *iov, loff_t offset,
unsigned long nr_segs)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
ssize_t ret;
size_t count = iov_length(iov, nr_segs);
loff_t final_size = offset + count;
if (rw == WRITE && final_size <= inode->i_size) {
/*
* We could direct write to holes and fallocate.
*
* Allocated blocks to fill the hole are marked as uninitialized
* to prevent paralel buffered read to expose the stale data
* before DIO complete the data IO.
*
* As to previously fallocated extents, ext4 get_block
* will just simply mark the buffer mapped but still
* keep the extents uninitialized.
*
* for non AIO case, we will convert those unwritten extents
* to written after return back from blockdev_direct_IO.
*
* for async DIO, the conversion needs to be defered when
* the IO is completed. The ext4 end_io callback function
* will be called to take care of the conversion work.
* Here for async case, we allocate an io_end structure to
* hook to the iocb.
*/
iocb->private = NULL;
EXT4_I(inode)->cur_aio_dio = NULL;
if (!is_sync_kiocb(iocb)) {
iocb->private = ext4_init_io_end(inode, GFP_NOFS);
if (!iocb->private)
return -ENOMEM;
/*
* we save the io structure for current async
* direct IO, so that later ext4_get_blocks()
* could flag the io structure whether there
* is a unwritten extents needs to be converted
* when IO is completed.
*/
EXT4_I(inode)->cur_aio_dio = iocb->private;
}
ret = blockdev_direct_IO(rw, iocb, inode,
inode->i_sb->s_bdev, iov,
offset, nr_segs,
ext4_get_block_write,
ext4_end_io_dio);
if (iocb->private)
EXT4_I(inode)->cur_aio_dio = NULL;
/*
* The io_end structure takes a reference to the inode,
* that structure needs to be destroyed and the
* reference to the inode need to be dropped, when IO is
* complete, even with 0 byte write, or failed.
*
* In the successful AIO DIO case, the io_end structure will be
* desctroyed and the reference to the inode will be dropped
* after the end_io call back function is called.
*
* In the case there is 0 byte write, or error case, since
* VFS direct IO won't invoke the end_io call back function,
* we need to free the end_io structure here.
*/
if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
ext4_free_io_end(iocb->private);
iocb->private = NULL;
} else if (ret > 0 && ext4_test_inode_state(inode,
EXT4_STATE_DIO_UNWRITTEN)) {
int err;
/*
* for non AIO case, since the IO is already
* completed, we could do the convertion right here
*/
err = ext4_convert_unwritten_extents(inode,
offset, ret);
if (err < 0)
ret = err;
ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
}
return ret;
}
/* for write the the end of file case, we fall back to old way */
return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
}
| 167,543 |
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 install_thread_keyring(void)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
BUG_ON(new->thread_keyring);
ret = install_thread_keyring_to_cred(new);
if (ret < 0) {
abort_creds(new);
return ret;
}
return commit_creds(new);
}
Commit Message: KEYS: fix keyctl_set_reqkey_keyring() to not leak thread keyrings
This fixes CVE-2017-7472.
Running the following program as an unprivileged user exhausts kernel
memory by leaking thread keyrings:
#include <keyutils.h>
int main()
{
for (;;)
keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_THREAD_KEYRING);
}
Fix it by only creating a new thread keyring if there wasn't one before.
To make things more consistent, make install_thread_keyring_to_cred()
and install_process_keyring_to_cred() both return 0 if the corresponding
keyring is already present.
Fixes: d84f4f992cbd ("CRED: Inaugurate COW credentials")
Cc: [email protected] # 2.6.29+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
CWE ID: CWE-404 | static int install_thread_keyring(void)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
ret = install_thread_keyring_to_cred(new);
if (ret < 0) {
abort_creds(new);
return ret;
}
return commit_creds(new);
}
| 168,276 |
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 udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len, int noblock, int flags, int *addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
bool slow;
/*
* Check any passed addresses
*/
if (addr_len)
*addr_len = sizeof(*sin);
if (flags & MSG_ERRQUEUE)
return ip_recv_error(sk, msg, len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
if (udp_lib_checksum_complete(skb))
goto csum_copy_err;
}
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr),
msg->msg_iov, copied);
else {
err = skb_copy_and_csum_datagram_iovec(skb,
sizeof(struct udphdr),
msg->msg_iov);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udp_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
goto out_free;
}
if (!peeked)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (sin) {
sin->sin_family = AF_INET;
sin->sin_port = udp_hdr(skb)->source;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
}
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
}
unlock_sock_fast(sk, slow);
if (noblock)
return -EAGAIN;
/* starting over for a new packet */
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
Commit Message: inet: prevent leakage of uninitialized memory to user in recv syscalls
Only update *addr_len when we actually fill in sockaddr, otherwise we
can return uninitialized memory from the stack to the caller in the
recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL)
checks because we only get called with a valid addr_len pointer either
from sock_common_recvmsg or inet_recvmsg.
If a blocking read waits on a socket which is concurrently shut down we
now return zero and set msg_msgnamelen to 0.
Reported-by: mpb <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len, int noblock, int flags, int *addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
bool slow;
if (flags & MSG_ERRQUEUE)
return ip_recv_error(sk, msg, len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
if (udp_lib_checksum_complete(skb))
goto csum_copy_err;
}
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr),
msg->msg_iov, copied);
else {
err = skb_copy_and_csum_datagram_iovec(skb,
sizeof(struct udphdr),
msg->msg_iov);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udp_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
goto out_free;
}
if (!peeked)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (sin) {
sin->sin_family = AF_INET;
sin->sin_port = udp_hdr(skb)->source;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
*addr_len = sizeof(*sin);
}
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
}
unlock_sock_fast(sk, slow);
if (noblock)
return -EAGAIN;
/* starting over for a new packet */
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
| 166,479 |
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: FT_Bitmap_Convert( FT_Library library,
const FT_Bitmap *source,
FT_Bitmap *target,
FT_Int alignment )
{
FT_Error error = FT_Err_Ok;
FT_Memory memory;
FT_Int source_pitch, target_pitch;
if ( !library )
return FT_THROW( Invalid_Library_Handle );
memory = library->memory;
switch ( source->pixel_mode )
{
case FT_PIXEL_MODE_MONO:
case FT_PIXEL_MODE_GRAY:
case FT_PIXEL_MODE_GRAY2:
case FT_PIXEL_MODE_GRAY4:
case FT_PIXEL_MODE_LCD:
case FT_PIXEL_MODE_LCD_V:
case FT_PIXEL_MODE_LCD_V:
case FT_PIXEL_MODE_BGRA:
{
FT_Int pad, old_target_pitch;
FT_Long old_size;
old_target_pitch = target->pitch;
old_target_pitch = -old_target_pitch;
old_size = target->rows * old_target_pitch;
target->pixel_mode = FT_PIXEL_MODE_GRAY;
target->rows = source->rows;
target->width = source->width;
pad = 0;
if ( alignment > 0 )
{
pad = source->width % alignment;
if ( pad != 0 )
pad = alignment - pad;
}
target_pitch = source->width + pad;
if ( target_pitch > 0 &&
(FT_ULong)target->rows > FT_ULONG_MAX / target_pitch )
return FT_THROW( Invalid_Argument );
if ( target->rows * target_pitch > old_size &&
FT_QREALLOC( target->buffer,
old_size, target->rows * target_pitch ) )
return error;
target->pitch = target->pitch < 0 ? -target_pitch : target_pitch;
}
break;
default:
error = FT_THROW( Invalid_Argument );
}
source_pitch = source->pitch;
if ( source_pitch < 0 )
source_pitch = -source_pitch;
switch ( source->pixel_mode )
{
case FT_PIXEL_MODE_MONO:
{
FT_Byte* s = source->buffer;
FT_Byte* t = target->buffer;
FT_Int i;
target->num_grays = 2;
for ( i = source->rows; i > 0; i-- )
{
FT_Byte* ss = s;
FT_Byte* tt = t;
FT_Int j;
/* get the full bytes */
for ( j = source->width >> 3; j > 0; j-- )
{
FT_Int val = ss[0]; /* avoid a byte->int cast on each line */
tt[0] = (FT_Byte)( ( val & 0x80 ) >> 7 );
tt[1] = (FT_Byte)( ( val & 0x40 ) >> 6 );
tt[2] = (FT_Byte)( ( val & 0x20 ) >> 5 );
tt[3] = (FT_Byte)( ( val & 0x10 ) >> 4 );
tt[4] = (FT_Byte)( ( val & 0x08 ) >> 3 );
tt[5] = (FT_Byte)( ( val & 0x04 ) >> 2 );
tt[6] = (FT_Byte)( ( val & 0x02 ) >> 1 );
tt[7] = (FT_Byte)( val & 0x01 );
tt += 8;
ss += 1;
}
/* get remaining pixels (if any) */
j = source->width & 7;
if ( j > 0 )
{
FT_Int val = *ss;
for ( ; j > 0; j-- )
{
tt[0] = (FT_Byte)( ( val & 0x80 ) >> 7);
val <<= 1;
tt += 1;
}
}
s += source_pitch;
t += target_pitch;
}
}
break;
case FT_PIXEL_MODE_GRAY:
case FT_PIXEL_MODE_LCD:
case FT_PIXEL_MODE_LCD_V:
{
FT_Int width = source->width;
FT_Byte* s = source->buffer;
FT_Byte* t = target->buffer;
FT_Int i;
target->num_grays = 256;
for ( i = source->rows; i > 0; i-- )
{
FT_ARRAY_COPY( t, s, width );
s += source_pitch;
t += target_pitch;
}
}
break;
case FT_PIXEL_MODE_GRAY2:
{
FT_Byte* s = source->buffer;
FT_Byte* t = target->buffer;
FT_Int i;
target->num_grays = 4;
for ( i = source->rows; i > 0; i-- )
{
FT_Byte* ss = s;
FT_Byte* tt = t;
FT_Int j;
/* get the full bytes */
for ( j = source->width >> 2; j > 0; j-- )
{
FT_Int val = ss[0];
tt[0] = (FT_Byte)( ( val & 0xC0 ) >> 6 );
tt[1] = (FT_Byte)( ( val & 0x30 ) >> 4 );
tt[2] = (FT_Byte)( ( val & 0x0C ) >> 2 );
tt[3] = (FT_Byte)( ( val & 0x03 ) );
ss += 1;
tt += 4;
}
j = source->width & 3;
if ( j > 0 )
{
FT_Int val = ss[0];
for ( ; j > 0; j-- )
{
tt[0] = (FT_Byte)( ( val & 0xC0 ) >> 6 );
val <<= 2;
tt += 1;
}
}
s += source_pitch;
t += target_pitch;
}
}
break;
case FT_PIXEL_MODE_GRAY4:
{
FT_Byte* s = source->buffer;
FT_Byte* t = target->buffer;
FT_Int i;
target->num_grays = 16;
for ( i = source->rows; i > 0; i-- )
{
FT_Byte* ss = s;
FT_Byte* tt = t;
FT_Int j;
/* get the full bytes */
for ( j = source->width >> 1; j > 0; j-- )
{
FT_Int val = ss[0];
tt[0] = (FT_Byte)( ( val & 0xF0 ) >> 4 );
tt[1] = (FT_Byte)( ( val & 0x0F ) );
ss += 1;
tt += 2;
}
if ( source->width & 1 )
tt[0] = (FT_Byte)( ( ss[0] & 0xF0 ) >> 4 );
s += source_pitch;
t += target_pitch;
}
}
break;
case FT_PIXEL_MODE_BGRA:
{
FT_Byte* s = source->buffer;
FT_Byte* t = target->buffer;
FT_Int i;
target->num_grays = 256;
for ( i = source->rows; i > 0; i-- )
{
FT_Byte* ss = s;
FT_Byte* tt = t;
FT_Int j;
for ( j = source->width; j > 0; j-- )
{
tt[0] = ft_gray_for_premultiplied_srgb_bgra( ss );
ss += 4;
tt += 1;
}
s += source_pitch;
t += target_pitch;
}
}
break;
default:
;
}
return error;
}
Commit Message:
CWE ID: CWE-119 | FT_Bitmap_Convert( FT_Library library,
const FT_Bitmap *source,
FT_Bitmap *target,
FT_Int alignment )
{
FT_Error error = FT_Err_Ok;
FT_Memory memory;
FT_Int source_pitch, target_pitch;
if ( !library )
return FT_THROW( Invalid_Library_Handle );
memory = library->memory;
switch ( source->pixel_mode )
{
case FT_PIXEL_MODE_MONO:
case FT_PIXEL_MODE_GRAY:
case FT_PIXEL_MODE_GRAY2:
case FT_PIXEL_MODE_GRAY4:
case FT_PIXEL_MODE_LCD:
case FT_PIXEL_MODE_LCD_V:
case FT_PIXEL_MODE_LCD_V:
case FT_PIXEL_MODE_BGRA:
{
FT_Int pad, old_target_pitch;
FT_ULong old_size;
old_target_pitch = target->pitch;
old_target_pitch = -old_target_pitch;
old_size = target->rows * old_target_pitch;
target->pixel_mode = FT_PIXEL_MODE_GRAY;
target->rows = source->rows;
target->width = source->width;
pad = 0;
if ( alignment > 0 )
{
pad = source->width % alignment;
if ( pad != 0 )
pad = alignment - pad;
}
target_pitch = source->width + pad;
if ( target_pitch > 0 &&
(FT_ULong)target->rows > FT_ULONG_MAX / target_pitch )
return FT_THROW( Invalid_Argument );
if ( target->rows * target_pitch > old_size &&
FT_QREALLOC( target->buffer,
old_size, target->rows * target_pitch ) )
return error;
target->pitch = target->pitch < 0 ? -target_pitch : target_pitch;
}
break;
default:
error = FT_THROW( Invalid_Argument );
}
source_pitch = source->pitch;
if ( source_pitch < 0 )
source_pitch = -source_pitch;
switch ( source->pixel_mode )
{
case FT_PIXEL_MODE_MONO:
{
FT_Byte* s = source->buffer;
FT_Byte* t = target->buffer;
FT_Int i;
target->num_grays = 2;
for ( i = source->rows; i > 0; i-- )
{
FT_Byte* ss = s;
FT_Byte* tt = t;
FT_Int j;
/* get the full bytes */
for ( j = source->width >> 3; j > 0; j-- )
{
FT_Int val = ss[0]; /* avoid a byte->int cast on each line */
tt[0] = (FT_Byte)( ( val & 0x80 ) >> 7 );
tt[1] = (FT_Byte)( ( val & 0x40 ) >> 6 );
tt[2] = (FT_Byte)( ( val & 0x20 ) >> 5 );
tt[3] = (FT_Byte)( ( val & 0x10 ) >> 4 );
tt[4] = (FT_Byte)( ( val & 0x08 ) >> 3 );
tt[5] = (FT_Byte)( ( val & 0x04 ) >> 2 );
tt[6] = (FT_Byte)( ( val & 0x02 ) >> 1 );
tt[7] = (FT_Byte)( val & 0x01 );
tt += 8;
ss += 1;
}
/* get remaining pixels (if any) */
j = source->width & 7;
if ( j > 0 )
{
FT_Int val = *ss;
for ( ; j > 0; j-- )
{
tt[0] = (FT_Byte)( ( val & 0x80 ) >> 7);
val <<= 1;
tt += 1;
}
}
s += source_pitch;
t += target_pitch;
}
}
break;
case FT_PIXEL_MODE_GRAY:
case FT_PIXEL_MODE_LCD:
case FT_PIXEL_MODE_LCD_V:
{
FT_Int width = source->width;
FT_Byte* s = source->buffer;
FT_Byte* t = target->buffer;
FT_Int i;
target->num_grays = 256;
for ( i = source->rows; i > 0; i-- )
{
FT_ARRAY_COPY( t, s, width );
s += source_pitch;
t += target_pitch;
}
}
break;
case FT_PIXEL_MODE_GRAY2:
{
FT_Byte* s = source->buffer;
FT_Byte* t = target->buffer;
FT_Int i;
target->num_grays = 4;
for ( i = source->rows; i > 0; i-- )
{
FT_Byte* ss = s;
FT_Byte* tt = t;
FT_Int j;
/* get the full bytes */
for ( j = source->width >> 2; j > 0; j-- )
{
FT_Int val = ss[0];
tt[0] = (FT_Byte)( ( val & 0xC0 ) >> 6 );
tt[1] = (FT_Byte)( ( val & 0x30 ) >> 4 );
tt[2] = (FT_Byte)( ( val & 0x0C ) >> 2 );
tt[3] = (FT_Byte)( ( val & 0x03 ) );
ss += 1;
tt += 4;
}
j = source->width & 3;
if ( j > 0 )
{
FT_Int val = ss[0];
for ( ; j > 0; j-- )
{
tt[0] = (FT_Byte)( ( val & 0xC0 ) >> 6 );
val <<= 2;
tt += 1;
}
}
s += source_pitch;
t += target_pitch;
}
}
break;
case FT_PIXEL_MODE_GRAY4:
{
FT_Byte* s = source->buffer;
FT_Byte* t = target->buffer;
FT_Int i;
target->num_grays = 16;
for ( i = source->rows; i > 0; i-- )
{
FT_Byte* ss = s;
FT_Byte* tt = t;
FT_Int j;
/* get the full bytes */
for ( j = source->width >> 1; j > 0; j-- )
{
FT_Int val = ss[0];
tt[0] = (FT_Byte)( ( val & 0xF0 ) >> 4 );
tt[1] = (FT_Byte)( ( val & 0x0F ) );
ss += 1;
tt += 2;
}
if ( source->width & 1 )
tt[0] = (FT_Byte)( ( ss[0] & 0xF0 ) >> 4 );
s += source_pitch;
t += target_pitch;
}
}
break;
case FT_PIXEL_MODE_BGRA:
{
FT_Byte* s = source->buffer;
FT_Byte* t = target->buffer;
FT_Int i;
target->num_grays = 256;
for ( i = source->rows; i > 0; i-- )
{
FT_Byte* ss = s;
FT_Byte* tt = t;
FT_Int j;
for ( j = source->width; j > 0; j-- )
{
tt[0] = ft_gray_for_premultiplied_srgb_bgra( ss );
ss += 4;
tt += 1;
}
s += source_pitch;
t += target_pitch;
}
}
break;
default:
;
}
return error;
}
| 164,847 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(snmp_set_enum_print)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, (int) a1);
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-416 | PHP_FUNCTION(snmp_set_enum_print)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, (int) a1);
RETURN_TRUE;
| 164,970 |
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: InstallVerifyFrame::InstallVerifyFrame(const wxString& lDmodFilePath)
: InstallVerifyFrame_Base(NULL, wxID_ANY, _T(""))
{
mConfig = Config::GetConfig();
prepareDialog();
int flags = wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_REMAINING_TIME;
wxProgressDialog lPrepareProgress(_("Preparing"),
_("The D-Mod archive is being decompressed in a temporary file."), 100, this, flags);
BZip lBZip(lDmodFilePath);
mTarFilePath = lBZip.Extract(&lPrepareProgress);
if (mTarFilePath.Len() != 0)
{
Tar lTar(mTarFilePath);
lTar.ReadHeaders();
wxString lDmodDescription = lTar.getmDmodDescription();
"\n"
"The D-Mod will be installed in subdirectory '%s'."),
lTar.getInstalledDmodDirectory().c_str());
}
else
{
int lBreakChar = lDmodDescription.Find( '\r' );
if ( lBreakChar <= 0 )
{
lBreakChar = lDmodDescription.Find( '\n' );
}
mDmodName = lDmodDescription.SubString( 0, lBreakChar - 1 );
this->SetTitle(_("DFArc - Install D-Mod - ") + mDmodName);
}
mDmodDescription->SetValue(lDmodDescription);
mInstallButton->Enable(true);
}
Commit Message:
CWE ID: CWE-22 | InstallVerifyFrame::InstallVerifyFrame(const wxString& lDmodFilePath)
: InstallVerifyFrame_Base(NULL, wxID_ANY, _T(""))
{
mConfig = Config::GetConfig();
prepareDialog();
int flags = wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_REMAINING_TIME;
wxProgressDialog lPrepareProgress(_("Preparing"),
_("The D-Mod archive is being decompressed in a temporary file."), 100, this, flags);
BZip lBZip(lDmodFilePath);
mTarFilePath = lBZip.Extract(&lPrepareProgress);
if (mTarFilePath.Len() != 0)
{
Tar lTar(mTarFilePath);
if (lTar.ReadHeaders() == 1) {
this->EndModal(wxID_CANCEL);
return;
}
wxString lDmodDescription = lTar.getmDmodDescription();
"\n"
"The D-Mod will be installed in subdirectory '%s'."),
lTar.getInstalledDmodDirectory().c_str());
}
else
{
int lBreakChar = lDmodDescription.Find( '\r' );
if ( lBreakChar <= 0 )
{
lBreakChar = lDmodDescription.Find( '\n' );
}
mDmodName = lDmodDescription.SubString( 0, lBreakChar - 1 );
this->SetTitle(_("DFArc - Install D-Mod - ") + mDmodName);
}
mDmodDescription->SetValue(lDmodDescription);
mInstallButton->Enable(true);
}
| 165,346 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct super_block *alloc_super(struct file_system_type *type, int flags)
{
struct super_block *s = kzalloc(sizeof(struct super_block), GFP_USER);
static const struct super_operations default_op;
int i;
if (!s)
return NULL;
if (security_sb_alloc(s))
goto fail;
#ifdef CONFIG_SMP
s->s_files = alloc_percpu(struct list_head);
if (!s->s_files)
goto fail;
for_each_possible_cpu(i)
INIT_LIST_HEAD(per_cpu_ptr(s->s_files, i));
#else
INIT_LIST_HEAD(&s->s_files);
#endif
for (i = 0; i < SB_FREEZE_LEVELS; i++) {
if (percpu_counter_init(&s->s_writers.counter[i], 0) < 0)
goto fail;
lockdep_init_map(&s->s_writers.lock_map[i], sb_writers_name[i],
&type->s_writers_key[i], 0);
}
init_waitqueue_head(&s->s_writers.wait);
init_waitqueue_head(&s->s_writers.wait_unfrozen);
s->s_flags = flags;
s->s_bdi = &default_backing_dev_info;
INIT_HLIST_NODE(&s->s_instances);
INIT_HLIST_BL_HEAD(&s->s_anon);
INIT_LIST_HEAD(&s->s_inodes);
if (list_lru_init(&s->s_dentry_lru))
goto fail;
if (list_lru_init(&s->s_inode_lru))
goto fail;
INIT_LIST_HEAD(&s->s_mounts);
init_rwsem(&s->s_umount);
lockdep_set_class(&s->s_umount, &type->s_umount_key);
/*
* sget() can have s_umount recursion.
*
* When it cannot find a suitable sb, it allocates a new
* one (this one), and tries again to find a suitable old
* one.
*
* In case that succeeds, it will acquire the s_umount
* lock of the old one. Since these are clearly distrinct
* locks, and this object isn't exposed yet, there's no
* risk of deadlocks.
*
* Annotate this by putting this lock in a different
* subclass.
*/
down_write_nested(&s->s_umount, SINGLE_DEPTH_NESTING);
s->s_count = 1;
atomic_set(&s->s_active, 1);
mutex_init(&s->s_vfs_rename_mutex);
lockdep_set_class(&s->s_vfs_rename_mutex, &type->s_vfs_rename_key);
mutex_init(&s->s_dquot.dqio_mutex);
mutex_init(&s->s_dquot.dqonoff_mutex);
init_rwsem(&s->s_dquot.dqptr_sem);
s->s_maxbytes = MAX_NON_LFS;
s->s_op = &default_op;
s->s_time_gran = 1000000000;
s->cleancache_poolid = -1;
s->s_shrink.seeks = DEFAULT_SEEKS;
s->s_shrink.scan_objects = super_cache_scan;
s->s_shrink.count_objects = super_cache_count;
s->s_shrink.batch = 1024;
s->s_shrink.flags = SHRINKER_NUMA_AWARE;
return s;
fail:
destroy_super(s);
return NULL;
}
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 | static struct super_block *alloc_super(struct file_system_type *type, int flags)
{
struct super_block *s = kzalloc(sizeof(struct super_block), GFP_USER);
static const struct super_operations default_op;
int i;
if (!s)
return NULL;
if (security_sb_alloc(s))
goto fail;
for (i = 0; i < SB_FREEZE_LEVELS; i++) {
if (percpu_counter_init(&s->s_writers.counter[i], 0) < 0)
goto fail;
lockdep_init_map(&s->s_writers.lock_map[i], sb_writers_name[i],
&type->s_writers_key[i], 0);
}
init_waitqueue_head(&s->s_writers.wait);
init_waitqueue_head(&s->s_writers.wait_unfrozen);
s->s_flags = flags;
s->s_bdi = &default_backing_dev_info;
INIT_HLIST_NODE(&s->s_instances);
INIT_HLIST_BL_HEAD(&s->s_anon);
INIT_LIST_HEAD(&s->s_inodes);
if (list_lru_init(&s->s_dentry_lru))
goto fail;
if (list_lru_init(&s->s_inode_lru))
goto fail;
INIT_LIST_HEAD(&s->s_mounts);
init_rwsem(&s->s_umount);
lockdep_set_class(&s->s_umount, &type->s_umount_key);
/*
* sget() can have s_umount recursion.
*
* When it cannot find a suitable sb, it allocates a new
* one (this one), and tries again to find a suitable old
* one.
*
* In case that succeeds, it will acquire the s_umount
* lock of the old one. Since these are clearly distrinct
* locks, and this object isn't exposed yet, there's no
* risk of deadlocks.
*
* Annotate this by putting this lock in a different
* subclass.
*/
down_write_nested(&s->s_umount, SINGLE_DEPTH_NESTING);
s->s_count = 1;
atomic_set(&s->s_active, 1);
mutex_init(&s->s_vfs_rename_mutex);
lockdep_set_class(&s->s_vfs_rename_mutex, &type->s_vfs_rename_key);
mutex_init(&s->s_dquot.dqio_mutex);
mutex_init(&s->s_dquot.dqonoff_mutex);
init_rwsem(&s->s_dquot.dqptr_sem);
s->s_maxbytes = MAX_NON_LFS;
s->s_op = &default_op;
s->s_time_gran = 1000000000;
s->cleancache_poolid = -1;
s->s_shrink.seeks = DEFAULT_SEEKS;
s->s_shrink.scan_objects = super_cache_scan;
s->s_shrink.count_objects = super_cache_count;
s->s_shrink.batch = 1024;
s->s_shrink.flags = SHRINKER_NUMA_AWARE;
return s;
fail:
destroy_super(s);
return NULL;
}
| 166,806 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(pg_trace)
{
char *z_filename, *mode = "w";
int z_filename_len, mode_len;
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
FILE *fp = NULL;
php_stream *stream;
id = PGG(default_link);
if (zend_parse_parameters(argc TSRMLS_CC, "s|sr", &z_filename, &z_filename_len, &mode, &mode_len, &pgsql_link) == FAILURE) {
return;
}
if (argc < 3) {
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
stream = php_stream_open_wrapper(z_filename, mode, REPORT_ERRORS, NULL);
if (!stream) {
RETURN_FALSE;
}
if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) {
php_stream_close(stream);
RETURN_FALSE;
}
php_stream_auto_cleanup(stream);
PQtrace(pgsql, fp);
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-254 | PHP_FUNCTION(pg_trace)
{
char *z_filename, *mode = "w";
int z_filename_len, mode_len;
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
FILE *fp = NULL;
php_stream *stream;
id = PGG(default_link);
if (zend_parse_parameters(argc TSRMLS_CC, "p|sr", &z_filename, &z_filename_len, &mode, &mode_len, &pgsql_link) == FAILURE) {
return;
}
if (argc < 3) {
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
stream = php_stream_open_wrapper(z_filename, mode, REPORT_ERRORS, NULL);
if (!stream) {
RETURN_FALSE;
}
if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) {
php_stream_close(stream);
RETURN_FALSE;
}
php_stream_auto_cleanup(stream);
PQtrace(pgsql, fp);
RETURN_TRUE;
}
| 165,314 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SoftGSM::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = 8000;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftGSM::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = 8000;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 174,207 |
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: TestOpenCallback()
: callback_(
base::Bind(&TestOpenCallback::SetResult, base::Unretained(this))) {}
Commit Message: Update helper classes in usb_device_handle_unittest for OnceCallback
Helper classes in usb_device_handle_unittest.cc don't fit to OnceCallback
migration, as they are copied and passed to others.
This CL updates them to pass new callbacks for each use to avoid the
copy of callbacks.
Bug: 714018
Change-Id: Ifb70901439ae92b6b049b84534283c39ebc40ee0
Reviewed-on: https://chromium-review.googlesource.com/527549
Reviewed-by: Ken Rockot <[email protected]>
Commit-Queue: Taiju Tsuiki <[email protected]>
Cr-Commit-Position: refs/heads/master@{#478549}
CWE ID: | TestOpenCallback()
| 171,976 |
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: load(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity,
char immediate_load)
{
static const int intoffset[] = { 0, 4, 2, 1 };
static const int intjump[] = { 8, 8, 4, 2 };
int rc;
DATA32 *ptr;
GifFileType *gif;
GifRowType *rows;
GifRecordType rec;
ColorMapObject *cmap;
int i, j, done, bg, r, g, b, w = 0, h = 0;
float per = 0.0, per_inc;
int last_per = 0, last_y = 0;
int transp;
int fd;
done = 0;
rows = NULL;
transp = -1;
/* if immediate_load is 1, then dont delay image laoding as below, or */
/* already data in this image - dont load it again */
if (im->data)
return 0;
fd = open(im->real_file, O_RDONLY);
if (fd < 0)
return 0;
#if GIFLIB_MAJOR >= 5
gif = DGifOpenFileHandle(fd, NULL);
#else
gif = DGifOpenFileHandle(fd);
#endif
if (!gif)
{
close(fd);
return 0;
}
rc = 0; /* Failure */
do
{
if (DGifGetRecordType(gif, &rec) == GIF_ERROR)
{
/* PrintGifError(); */
rec = TERMINATE_RECORD_TYPE;
}
if ((rec == IMAGE_DESC_RECORD_TYPE) && (!done))
{
if (DGifGetImageDesc(gif) == GIF_ERROR)
{
/* PrintGifError(); */
rec = TERMINATE_RECORD_TYPE;
break;
}
w = gif->Image.Width;
h = gif->Image.Height;
if (!IMAGE_DIMENSIONS_OK(w, h))
goto quit2;
rows = calloc(h, sizeof(GifRowType *));
if (!rows)
goto quit2;
for (i = 0; i < h; i++)
{
rows[i] = calloc(w, sizeof(GifPixelType));
if (!rows[i])
goto quit;
}
if (gif->Image.Interlace)
{
for (i = 0; i < 4; i++)
{
for (j = intoffset[i]; j < h; j += intjump[i])
{
DGifGetLine(gif, rows[j], w);
}
}
}
else
{
for (i = 0; i < h; i++)
{
DGifGetLine(gif, rows[i], w);
}
}
done = 1;
}
else if (rec == EXTENSION_RECORD_TYPE)
{
int ext_code;
GifByteType *ext;
ext = NULL;
DGifGetExtension(gif, &ext_code, &ext);
while (ext)
{
if ((ext_code == 0xf9) && (ext[1] & 1) && (transp < 0))
{
transp = (int)ext[4];
}
ext = NULL;
DGifGetExtensionNext(gif, &ext);
}
}
}
while (rec != TERMINATE_RECORD_TYPE);
if (transp >= 0)
{
SET_FLAG(im->flags, F_HAS_ALPHA);
}
else
{
UNSET_FLAG(im->flags, F_HAS_ALPHA);
}
if (!rows)
{
goto quit2;
}
/* set the format string member to the lower-case full extension */
/* name for the format - so example names would be: */
/* "png", "jpeg", "tiff", "ppm", "pgm", "pbm", "gif", "xpm" ... */
im->w = w;
im->h = h;
if (!im->format)
im->format = strdup("gif");
if (im->loader || immediate_load || progress)
{
bg = gif->SBackGroundColor;
cmap = (gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap);
im->data = (DATA32 *) malloc(sizeof(DATA32) * w * h);
if (!im->data)
goto quit;
{
r = cmap->Colors[bg].Red;
g = cmap->Colors[bg].Green;
b = cmap->Colors[bg].Blue;
*ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b);
}
else
{
r = cmap->Colors[rows[i][j]].Red;
g = cmap->Colors[rows[i][j]].Green;
b = cmap->Colors[rows[i][j]].Blue;
*ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
{
for (j = 0; j < w; j++)
{
if (rows[i][j] == transp)
{
r = cmap->Colors[bg].Red;
g = cmap->Colors[bg].Green;
b = cmap->Colors[bg].Blue;
*ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b);
}
else
{
r = cmap->Colors[rows[i][j]].Red;
g = cmap->Colors[rows[i][j]].Green;
b = cmap->Colors[rows[i][j]].Blue;
*ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
}
per += per_inc;
if (progress && (((int)per) != last_per)
&& (((int)per) % progress_granularity == 0))
{
rc = 2;
goto quit;
}
last_y = i;
}
}
}
finish:
if (progress)
progress(im, 100, 0, last_y, w, h);
}
rc = 1; /* Success */
quit:
for (i = 0; i < h; i++)
free(rows[i]);
free(rows);
quit2:
#if GIFLIB_MAJOR > 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR >= 1)
DGifCloseFile(gif, NULL);
#else
DGifCloseFile(gif);
#endif
return rc;
}
Commit Message:
CWE ID: CWE-119 | load(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity,
char immediate_load)
{
static const int intoffset[] = { 0, 4, 2, 1 };
static const int intjump[] = { 8, 8, 4, 2 };
int rc;
DATA32 *ptr;
GifFileType *gif;
GifRowType *rows;
GifRecordType rec;
ColorMapObject *cmap;
int i, j, done, bg, r, g, b, w = 0, h = 0;
float per = 0.0, per_inc;
int last_per = 0, last_y = 0;
int transp;
int fd;
done = 0;
rows = NULL;
transp = -1;
/* if immediate_load is 1, then dont delay image laoding as below, or */
/* already data in this image - dont load it again */
if (im->data)
return 0;
fd = open(im->real_file, O_RDONLY);
if (fd < 0)
return 0;
#if GIFLIB_MAJOR >= 5
gif = DGifOpenFileHandle(fd, NULL);
#else
gif = DGifOpenFileHandle(fd);
#endif
if (!gif)
{
close(fd);
return 0;
}
rc = 0; /* Failure */
do
{
if (DGifGetRecordType(gif, &rec) == GIF_ERROR)
{
/* PrintGifError(); */
rec = TERMINATE_RECORD_TYPE;
}
if ((rec == IMAGE_DESC_RECORD_TYPE) && (!done))
{
if (DGifGetImageDesc(gif) == GIF_ERROR)
{
/* PrintGifError(); */
rec = TERMINATE_RECORD_TYPE;
break;
}
w = gif->Image.Width;
h = gif->Image.Height;
if (!IMAGE_DIMENSIONS_OK(w, h))
goto quit2;
rows = calloc(h, sizeof(GifRowType *));
if (!rows)
goto quit2;
for (i = 0; i < h; i++)
{
rows[i] = calloc(w, sizeof(GifPixelType));
if (!rows[i])
goto quit;
}
if (gif->Image.Interlace)
{
for (i = 0; i < 4; i++)
{
for (j = intoffset[i]; j < h; j += intjump[i])
{
DGifGetLine(gif, rows[j], w);
}
}
}
else
{
for (i = 0; i < h; i++)
{
DGifGetLine(gif, rows[i], w);
}
}
done = 1;
}
else if (rec == EXTENSION_RECORD_TYPE)
{
int ext_code;
GifByteType *ext;
ext = NULL;
DGifGetExtension(gif, &ext_code, &ext);
while (ext)
{
if ((ext_code == 0xf9) && (ext[1] & 1) && (transp < 0))
{
transp = (int)ext[4];
}
ext = NULL;
DGifGetExtensionNext(gif, &ext);
}
}
}
while (rec != TERMINATE_RECORD_TYPE);
if (transp >= 0)
{
SET_FLAG(im->flags, F_HAS_ALPHA);
}
else
{
UNSET_FLAG(im->flags, F_HAS_ALPHA);
}
if (!rows)
{
goto quit2;
}
/* set the format string member to the lower-case full extension */
/* name for the format - so example names would be: */
/* "png", "jpeg", "tiff", "ppm", "pgm", "pbm", "gif", "xpm" ... */
im->w = w;
im->h = h;
if (!im->format)
im->format = strdup("gif");
if (im->loader || immediate_load || progress)
{
DATA32 colormap[256];
bg = gif->SBackGroundColor;
cmap = (gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap);
memset (colormap, 0, sizeof(colormap));
if (cmap != NULL)
{
for (i = cmap->ColorCount > 256 ? 256 : cmap->ColorCount; i-- > 0;)
{
r = cmap->Colors[i].Red;
g = cmap->Colors[i].Green;
b = cmap->Colors[i].Blue;
colormap[i] = (0xff << 24) | (r << 16) | (g << 8) | b;
}
/* if bg > cmap->ColorCount, it is transparent black already */
if (transp >= 0 && transp < 256)
colormap[transp] = bg >= 0 && bg < 256 ? colormap[bg] & 0x00ffffff : 0x00000000;
}
im->data = (DATA32 *) malloc(sizeof(DATA32) * w * h);
if (!im->data)
goto quit;
{
r = cmap->Colors[bg].Red;
g = cmap->Colors[bg].Green;
b = cmap->Colors[bg].Blue;
*ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b);
}
else
{
r = cmap->Colors[rows[i][j]].Red;
g = cmap->Colors[rows[i][j]].Green;
b = cmap->Colors[rows[i][j]].Blue;
*ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
{
for (j = 0; j < w; j++)
{
*ptr++ = colormap[rows[i][j]];
per += per_inc;
if (progress && (((int)per) != last_per)
&& (((int)per) % progress_granularity == 0))
{
rc = 2;
goto quit;
}
last_y = i;
}
}
}
finish:
if (progress)
progress(im, 100, 0, last_y, w, h);
}
rc = 1; /* Success */
quit:
for (i = 0; i < h; i++)
free(rows[i]);
free(rows);
quit2:
#if GIFLIB_MAJOR > 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR >= 1)
DGifCloseFile(gif, NULL);
#else
DGifCloseFile(gif);
#endif
return rc;
}
| 165,079 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static long madvise_willneed(struct vm_area_struct *vma,
struct vm_area_struct **prev,
unsigned long start, unsigned long end)
{
struct file *file = vma->vm_file;
#ifdef CONFIG_SWAP
if (!file) {
*prev = vma;
force_swapin_readahead(vma, start, end);
return 0;
}
if (shmem_mapping(file->f_mapping)) {
*prev = vma;
force_shm_swapin_readahead(vma, start, end,
file->f_mapping);
return 0;
}
#else
if (!file)
return -EBADF;
#endif
if (IS_DAX(file_inode(file))) {
/* no bad return value, but ignore advice */
return 0;
}
*prev = vma;
start = ((start - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
if (end > vma->vm_end)
end = vma->vm_end;
end = ((end - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
force_page_cache_readahead(file->f_mapping, file, start, end - start);
return 0;
}
Commit Message: mm/madvise.c: fix madvise() infinite loop under special circumstances
MADVISE_WILLNEED has always been a noop for DAX (formerly XIP) mappings.
Unfortunately madvise_willneed() doesn't communicate this information
properly to the generic madvise syscall implementation. The calling
convention is quite subtle there. madvise_vma() is supposed to either
return an error or update &prev otherwise the main loop will never
advance to the next vma and it will keep looping for ever without a way
to get out of the kernel.
It seems this has been broken since introduction. Nobody has noticed
because nobody seems to be using MADVISE_WILLNEED on these DAX mappings.
[[email protected]: rewrite changelog]
Link: http://lkml.kernel.org/r/[email protected]
Fixes: fe77ba6f4f97 ("[PATCH] xip: madvice/fadvice: execute in place")
Signed-off-by: chenjie <[email protected]>
Signed-off-by: guoxuenan <[email protected]>
Acked-by: Michal Hocko <[email protected]>
Cc: Minchan Kim <[email protected]>
Cc: zhangyi (F) <[email protected]>
Cc: Miao Xie <[email protected]>
Cc: Mike Rapoport <[email protected]>
Cc: Shaohua Li <[email protected]>
Cc: Andrea Arcangeli <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Kirill A. Shutemov <[email protected]>
Cc: David Rientjes <[email protected]>
Cc: Anshuman Khandual <[email protected]>
Cc: Rik van Riel <[email protected]>
Cc: Carsten Otte <[email protected]>
Cc: Dan Williams <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-835 | static long madvise_willneed(struct vm_area_struct *vma,
struct vm_area_struct **prev,
unsigned long start, unsigned long end)
{
struct file *file = vma->vm_file;
*prev = vma;
#ifdef CONFIG_SWAP
if (!file) {
force_swapin_readahead(vma, start, end);
return 0;
}
if (shmem_mapping(file->f_mapping)) {
force_shm_swapin_readahead(vma, start, end,
file->f_mapping);
return 0;
}
#else
if (!file)
return -EBADF;
#endif
if (IS_DAX(file_inode(file))) {
/* no bad return value, but ignore advice */
return 0;
}
start = ((start - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
if (end > vma->vm_end)
end = vma->vm_end;
end = ((end - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
force_page_cache_readahead(file->f_mapping, file, start, end - start);
return 0;
}
| 169,409 |
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 php_handler(request_rec *r)
{
php_struct * volatile ctx;
void *conf;
apr_bucket_brigade * volatile brigade;
apr_bucket *bucket;
apr_status_t rv;
request_rec * volatile parent_req = NULL;
TSRMLS_FETCH();
#define PHPAP_INI_OFF php_apache_ini_dtor(r, parent_req TSRMLS_CC);
conf = ap_get_module_config(r->per_dir_config, &php5_module);
/* apply_config() needs r in some cases, so allocate server_context early */
ctx = SG(server_context);
if (ctx == NULL || (ctx && ctx->request_processed && !strcmp(r->protocol, "INCLUDED"))) {
normal:
ctx = SG(server_context) = apr_pcalloc(r->pool, sizeof(*ctx));
/* register a cleanup so we clear out the SG(server_context)
* after each request. Note: We pass in the pointer to the
* server_context in case this is handled by a different thread.
*/
apr_pool_cleanup_register(r->pool, (void *)&SG(server_context), php_server_context_cleanup, apr_pool_cleanup_null);
ctx->r = r;
ctx = NULL; /* May look weird to null it here, but it is to catch the right case in the first_try later on */
} else {
parent_req = ctx->r;
ctx->r = r;
}
apply_config(conf);
if (strcmp(r->handler, PHP_MAGIC_TYPE) && strcmp(r->handler, PHP_SOURCE_MAGIC_TYPE) && strcmp(r->handler, PHP_SCRIPT)) {
/* Check for xbithack in this case. */
if (!AP2(xbithack) || strcmp(r->handler, "text/html") || !(r->finfo.protection & APR_UEXECUTE)) {
PHPAP_INI_OFF;
return DECLINED;
}
}
/* Give a 404 if PATH_INFO is used but is explicitly disabled in
* the configuration; default behaviour is to accept. */
if (r->used_path_info == AP_REQ_REJECT_PATH_INFO
&& r->path_info && r->path_info[0]) {
PHPAP_INI_OFF;
return HTTP_NOT_FOUND;
}
/* handle situations where user turns the engine off */
if (!AP2(engine)) {
PHPAP_INI_OFF;
return DECLINED;
}
if (r->finfo.filetype == 0) {
php_apache_sapi_log_message_ex("script '%s' not found or unable to stat", r TSRMLS_CC);
PHPAP_INI_OFF;
return HTTP_NOT_FOUND;
}
if (r->finfo.filetype == APR_DIR) {
php_apache_sapi_log_message_ex("attempt to invoke directory '%s' as script", r TSRMLS_CC);
PHPAP_INI_OFF;
return HTTP_FORBIDDEN;
}
/* Setup the CGI variables if this is the main request */
if (r->main == NULL ||
/* .. or if the sub-request environment differs from the main-request. */
r->subprocess_env != r->main->subprocess_env
) {
/* setup standard CGI variables */
ap_add_common_vars(r);
ap_add_cgi_vars(r);
}
zend_first_try {
if (ctx == NULL) {
brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc);
ctx = SG(server_context);
ctx->brigade = brigade;
if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) {
zend_bailout();
}
} else {
if (!parent_req) {
parent_req = ctx->r;
}
if (parent_req && parent_req->handler &&
strcmp(parent_req->handler, PHP_MAGIC_TYPE) &&
strcmp(parent_req->handler, PHP_SOURCE_MAGIC_TYPE) &&
strcmp(parent_req->handler, PHP_SCRIPT)) {
if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) {
zend_bailout();
}
}
/*
* check if coming due to ErrorDocument
* We make a special exception of 413 (Invalid POST request) as the invalidity of the request occurs
* during processing of the request by PHP during POST processing. Therefor we need to re-use the exiting
* PHP instance to handle the request rather then creating a new one.
*/
if (parent_req && parent_req->status != HTTP_OK && parent_req->status != 413 && strcmp(r->protocol, "INCLUDED")) {
parent_req = NULL;
goto normal;
}
ctx->r = r;
brigade = ctx->brigade;
}
if (AP2(last_modified)) {
ap_update_mtime(r, r->finfo.mtime);
ap_set_last_modified(r);
}
/* Determine if we need to parse the file or show the source */
if (strncmp(r->handler, PHP_SOURCE_MAGIC_TYPE, sizeof(PHP_SOURCE_MAGIC_TYPE) - 1) == 0) {
zend_syntax_highlighter_ini syntax_highlighter_ini;
php_get_highlight_struct(&syntax_highlighter_ini);
highlight_file((char *)r->filename, &syntax_highlighter_ini TSRMLS_CC);
} else {
zend_file_handle zfd;
zfd.type = ZEND_HANDLE_FILENAME;
zfd.filename = (char *) r->filename;
zfd.free_filename = 0;
zfd.opened_path = NULL;
if (!parent_req) {
php_execute_script(&zfd TSRMLS_CC);
} else {
zend_execute_scripts(ZEND_INCLUDE TSRMLS_CC, NULL, 1, &zfd);
}
apr_table_set(r->notes, "mod_php_memory_usage",
apr_psprintf(ctx->r->pool, "%" APR_SIZE_T_FMT, zend_memory_peak_usage(1 TSRMLS_CC)));
}
} zend_end_try();
if (!parent_req) {
php_apache_request_dtor(r TSRMLS_CC);
ctx->request_processed = 1;
bucket = apr_bucket_eos_create(r->connection->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(brigade, bucket);
rv = ap_pass_brigade(r->output_filters, brigade);
if (rv != APR_SUCCESS || r->connection->aborted) {
zend_first_try {
php_handle_aborted_connection();
} zend_end_try();
}
apr_brigade_cleanup(brigade);
} else {
ctx->r = parent_req;
}
return OK;
}
Commit Message:
CWE ID: CWE-20 | static int php_handler(request_rec *r)
{
php_struct * volatile ctx;
void *conf;
apr_bucket_brigade * volatile brigade;
apr_bucket *bucket;
apr_status_t rv;
request_rec * volatile parent_req = NULL;
TSRMLS_FETCH();
#define PHPAP_INI_OFF php_apache_ini_dtor(r, parent_req TSRMLS_CC);
conf = ap_get_module_config(r->per_dir_config, &php5_module);
/* apply_config() needs r in some cases, so allocate server_context early */
ctx = SG(server_context);
if (ctx == NULL || (ctx && ctx->request_processed && !strcmp(r->protocol, "INCLUDED"))) {
normal:
ctx = SG(server_context) = apr_pcalloc(r->pool, sizeof(*ctx));
/* register a cleanup so we clear out the SG(server_context)
* after each request. Note: We pass in the pointer to the
* server_context in case this is handled by a different thread.
*/
apr_pool_cleanup_register(r->pool, (void *)&SG(server_context), php_server_context_cleanup, apr_pool_cleanup_null);
ctx->r = r;
ctx = NULL; /* May look weird to null it here, but it is to catch the right case in the first_try later on */
} else {
parent_req = ctx->r;
ctx->r = r;
}
apply_config(conf);
if (strcmp(r->handler, PHP_MAGIC_TYPE) && strcmp(r->handler, PHP_SOURCE_MAGIC_TYPE) && strcmp(r->handler, PHP_SCRIPT)) {
/* Check for xbithack in this case. */
if (!AP2(xbithack) || strcmp(r->handler, "text/html") || !(r->finfo.protection & APR_UEXECUTE)) {
PHPAP_INI_OFF;
return DECLINED;
}
}
/* Give a 404 if PATH_INFO is used but is explicitly disabled in
* the configuration; default behaviour is to accept. */
if (r->used_path_info == AP_REQ_REJECT_PATH_INFO
&& r->path_info && r->path_info[0]) {
PHPAP_INI_OFF;
return HTTP_NOT_FOUND;
}
/* handle situations where user turns the engine off */
if (!AP2(engine)) {
PHPAP_INI_OFF;
return DECLINED;
}
if (r->finfo.filetype == 0) {
php_apache_sapi_log_message_ex("script '%s' not found or unable to stat", r TSRMLS_CC);
PHPAP_INI_OFF;
return HTTP_NOT_FOUND;
}
if (r->finfo.filetype == APR_DIR) {
php_apache_sapi_log_message_ex("attempt to invoke directory '%s' as script", r TSRMLS_CC);
PHPAP_INI_OFF;
return HTTP_FORBIDDEN;
}
/* Setup the CGI variables if this is the main request */
if (r->main == NULL ||
/* .. or if the sub-request environment differs from the main-request. */
r->subprocess_env != r->main->subprocess_env
) {
/* setup standard CGI variables */
ap_add_common_vars(r);
ap_add_cgi_vars(r);
}
zend_first_try {
if (ctx == NULL) {
brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc);
ctx = SG(server_context);
ctx->brigade = brigade;
if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) {
zend_bailout();
}
} else {
if (!parent_req) {
parent_req = ctx->r;
}
if (parent_req && parent_req->handler &&
strcmp(parent_req->handler, PHP_MAGIC_TYPE) &&
strcmp(parent_req->handler, PHP_SOURCE_MAGIC_TYPE) &&
strcmp(parent_req->handler, PHP_SCRIPT)) {
if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) {
zend_bailout();
}
}
/*
* check if coming due to ErrorDocument
* We make a special exception of 413 (Invalid POST request) as the invalidity of the request occurs
* during processing of the request by PHP during POST processing. Therefor we need to re-use the exiting
* PHP instance to handle the request rather then creating a new one.
*/
if (parent_req && parent_req->status != HTTP_OK && parent_req->status != 413 && strcmp(r->protocol, "INCLUDED")) {
parent_req = NULL;
goto normal;
}
ctx->r = r;
brigade = ctx->brigade;
}
if (AP2(last_modified)) {
ap_update_mtime(r, r->finfo.mtime);
ap_set_last_modified(r);
}
/* Determine if we need to parse the file or show the source */
if (strncmp(r->handler, PHP_SOURCE_MAGIC_TYPE, sizeof(PHP_SOURCE_MAGIC_TYPE) - 1) == 0) {
zend_syntax_highlighter_ini syntax_highlighter_ini;
php_get_highlight_struct(&syntax_highlighter_ini);
highlight_file((char *)r->filename, &syntax_highlighter_ini TSRMLS_CC);
} else {
zend_file_handle zfd;
zfd.type = ZEND_HANDLE_FILENAME;
zfd.filename = (char *) r->filename;
zfd.free_filename = 0;
zfd.opened_path = NULL;
if (!parent_req) {
php_execute_script(&zfd TSRMLS_CC);
} else {
zend_execute_scripts(ZEND_INCLUDE TSRMLS_CC, NULL, 1, &zfd);
}
apr_table_set(r->notes, "mod_php_memory_usage",
apr_psprintf(ctx->r->pool, "%" APR_SIZE_T_FMT, zend_memory_peak_usage(1 TSRMLS_CC)));
}
} zend_end_try();
if (!parent_req) {
php_apache_request_dtor(r TSRMLS_CC);
ctx->request_processed = 1;
bucket = apr_bucket_eos_create(r->connection->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(brigade, bucket);
rv = ap_pass_brigade(r->output_filters, brigade);
if (rv != APR_SUCCESS || r->connection->aborted) {
zend_first_try {
php_handle_aborted_connection();
} zend_end_try();
}
apr_brigade_cleanup(brigade);
apr_pool_cleanup_run(r->pool, (void *)&SG(server_context), php_server_context_cleanup);
} else {
ctx->r = parent_req;
}
return OK;
}
| 164,710 |
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: ContentEncoding::ContentEncryption::ContentEncryption()
: algo(0),
key_id(NULL),
key_id_len(0),
signature(NULL),
signature_len(0),
sig_key_id(NULL),
sig_key_id_len(0),
sig_algo(0),
sig_hash_algo(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 | ContentEncoding::ContentEncryption::ContentEncryption()
: algo(0),
key_id(NULL),
key_id_len(0),
signature(NULL),
signature_len(0),
sig_key_id(NULL),
sig_key_id_len(0),
sig_algo(0),
| 174,252 |
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 save_text_if_changed(const char *name, const char *new_value)
{
/* a text value can't be change if the file is not loaded */
/* returns NULL if the name is not found; otherwise nonzero */
if (!g_hash_table_lookup(g_loaded_texts, name))
return;
const char *old_value = g_cd ? problem_data_get_content_or_NULL(g_cd, name) : "";
if (!old_value)
old_value = "";
if (strcmp(new_value, old_value) != 0)
{
struct dump_dir *dd = wizard_open_directory_for_writing(g_dump_dir_name);
if (dd)
dd_save_text(dd, name, new_value);
dd_close(dd);
problem_data_reload_from_dump_dir();
update_gui_state_from_problem_data(/* don't update selected event */ 0);
}
}
Commit Message: wizard: fix save users changes after reviewing dump dir files
If the user reviewed the dump dir's files during reporting the crash, the
changes was thrown away and original data was passed to the bugzilla bug
report.
report-gtk saves the first text view buffer and then reloads data from the
reported problem directory, which causes that the changes made to those text
views are thrown away.
Function save_text_if_changed(), except of saving text, also reload the files
from dump dir and update gui state from the dump dir. The commit moves the
reloading and updating gui functions away from this function.
Related to rhbz#1270235
Signed-off-by: Matej Habrnal <[email protected]>
CWE ID: CWE-200 | static void save_text_if_changed(const char *name, const char *new_value)
{
/* a text value can't be change if the file is not loaded */
/* returns NULL if the name is not found; otherwise nonzero */
if (!g_hash_table_lookup(g_loaded_texts, name))
return;
const char *old_value = g_cd ? problem_data_get_content_or_NULL(g_cd, name) : "";
if (!old_value)
old_value = "";
if (strcmp(new_value, old_value) != 0)
{
struct dump_dir *dd = wizard_open_directory_for_writing(g_dump_dir_name);
if (dd)
dd_save_text(dd, name, new_value);
dd_close(dd);
}
}
| 166,602 |
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: FileBrowserHandlerCustomBindings::FileBrowserHandlerCustomBindings(
ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetExternalFileEntry",
base::Bind(&FileBrowserHandlerCustomBindings::GetExternalFileEntry,
base::Unretained(this)));
RouteFunction("GetEntryURL",
base::Bind(&FileBrowserHandlerCustomBindings::GetEntryURL,
base::Unretained(this)));
}
Commit Message: [Extensions] Add more bindings access checks
BUG=598165
Review URL: https://codereview.chromium.org/1854983002
Cr-Commit-Position: refs/heads/master@{#385282}
CWE ID: | FileBrowserHandlerCustomBindings::FileBrowserHandlerCustomBindings(
ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetExternalFileEntry", "fileBrowserHandler",
base::Bind(
&FileBrowserHandlerCustomBindings::GetExternalFileEntryCallback,
base::Unretained(this)));
}
| 173,271 |
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_many_args (MyObject *obj, guint32 x, const char *str, double trouble, double *d_ret, char **str_ret, GError **error)
{
*d_ret = trouble + (x * 2);
*str_ret = g_ascii_strup (str, -1);
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_many_args (MyObject *obj, guint32 x, const char *str, double trouble, double *d_ret, char **str_ret, GError **error)
| 165,110 |
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 GLSurfaceEGLSurfaceControl::Resize(const gfx::Size& size,
float scale_factor,
ColorSpace color_space,
bool has_alpha) {
return true;
}
Commit Message: gpu/android : Add support for partial swap with surface control.
Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should
allow the display compositor to draw the minimum sub-rect necessary from
the damage tracking in BufferQueue on the client-side, and also to pass
this damage rect to the framework.
[email protected]
Bug: 926020
Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61
Reviewed-on: https://chromium-review.googlesource.com/c/1457467
Commit-Queue: Khushal <[email protected]>
Commit-Queue: Antoine Labour <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Auto-Submit: Khushal <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629852}
CWE ID: | bool GLSurfaceEGLSurfaceControl::Resize(const gfx::Size& size,
float scale_factor,
ColorSpace color_space,
bool has_alpha) {
window_rect_ = gfx::Rect(0, 0, size.width(), size.height());
return true;
}
| 172,110 |
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: ModuleExport size_t RegisterMPCImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CACHE");
entry->description=ConstantString("Magick Persistent Cache image format");
entry->module=ConstantString("MPC");
entry->seekable_stream=MagickTrue;
entry->stealth=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("MPC");
entry->decoder=(DecodeImageHandler *) ReadMPCImage;
entry->encoder=(EncodeImageHandler *) WriteMPCImage;
entry->magick=(IsImageFormatHandler *) IsMPC;
entry->description=ConstantString("Magick Persistent Cache image format");
entry->seekable_stream=MagickTrue;
entry->module=ConstantString("MPC");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
Commit Message: ...
CWE ID: CWE-20 | ModuleExport size_t RegisterMPCImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CACHE");
entry->description=ConstantString("Magick Persistent Cache image format");
entry->module=ConstantString("MPC");
entry->stealth=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("MPC");
entry->decoder=(DecodeImageHandler *) ReadMPCImage;
entry->encoder=(EncodeImageHandler *) WriteMPCImage;
entry->magick=(IsImageFormatHandler *) IsMPC;
entry->description=ConstantString("Magick Persistent Cache image format");
entry->seekable_stream=MagickTrue;
entry->module=ConstantString("MPC");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
| 170,040 |
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: char *M_fs_path_join_parts(const M_list_str_t *path, M_fs_system_t sys_type)
{
M_list_str_t *parts;
const char *part;
char *out;
size_t len;
size_t i;
size_t count;
if (path == NULL) {
return NULL;
}
len = M_list_str_len(path);
if (len == 0) {
return NULL;
}
sys_type = M_fs_path_get_system_type(sys_type);
/* Remove any empty parts (except for the first part which denotes an abs path on Unix
* or a UNC path on Windows). */
parts = M_list_str_duplicate(path);
for (i=len-1; i>0; i--) {
part = M_list_str_at(parts, i);
if (part == NULL || *part == '\0') {
M_list_str_remove_at(parts, i);
}
}
len = M_list_str_len(parts);
/* Join puts the sep between items. If there are no items then the sep
* won't be written. */
part = M_list_str_at(parts, 0);
if (len == 1 && (part == NULL || *part == '\0')) {
M_list_str_destroy(parts);
if (sys_type == M_FS_SYSTEM_WINDOWS) {
return M_strdup("\\\\");
}
return M_strdup("/");
}
/* Handle windows abs path because they need two separators. */
if (sys_type == M_FS_SYSTEM_WINDOWS && len > 0) {
part = M_list_str_at(parts, 0);
/* If we have 1 item we need to add two empties so we get the second separator. */
count = (len == 1) ? 2 : 1;
/* If we're dealing with a unc path add the second sep so we get two separators for the UNC base. */
if (part != NULL && *part == '\0') {
for (i=0; i<count; i++) {
M_list_str_insert_at(parts, "", 0);
}
} else if (M_fs_path_isabs(part, sys_type) && len == 1) {
/* We need to add an empty so we get a separator after the drive. */
M_list_str_insert_at(parts, "", 1);
}
}
out = M_list_str_join(parts, (unsigned char)M_fs_path_get_system_sep(sys_type));
M_list_str_destroy(parts);
return out;
}
Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data.
CWE ID: CWE-732 | char *M_fs_path_join_parts(const M_list_str_t *path, M_fs_system_t sys_type)
{
M_list_str_t *parts;
const char *part;
char *out;
size_t len;
size_t i;
size_t count;
if (path == NULL) {
return NULL;
}
len = M_list_str_len(path);
if (len == 0) {
return NULL;
}
sys_type = M_fs_path_get_system_type(sys_type);
/* Remove any empty parts (except for the first part which denotes an abs path on Unix
* or a UNC path on Windows). */
parts = M_list_str_duplicate(path);
for (i=len-1; i>0; i--) {
part = M_list_str_at(parts, i);
if (part == NULL || *part == '\0') {
M_list_str_remove_at(parts, i);
}
}
len = M_list_str_len(parts);
/* Join puts the sep between items. If there are no items then the sep
* won't be written. */
part = M_list_str_at(parts, 0);
if (len == 1 && (part == NULL || *part == '\0')) {
M_list_str_destroy(parts);
if (sys_type == M_FS_SYSTEM_WINDOWS) {
return M_strdup("\\\\");
}
return M_strdup("/");
}
/* Handle windows abs path because they need two separators. */
if (sys_type == M_FS_SYSTEM_WINDOWS && len > 0) {
part = M_list_str_at(parts, 0);
/* If we have 1 item we need to add two empties so we get the second separator. */
count = (len == 1) ? 2 : 1;
/* If we're dealing with a unc path add the second sep so we get two separators for the UNC base. */
if (part != NULL && *part == '\0') {
for (i=0; i<count; i++) {
M_list_str_insert_at(parts, "", 0);
}
} else if (M_fs_path_isabs(part, sys_type) && len == 1) {
/* We need to add an empty so we get a separator after the drive. */
M_list_str_insert_at(parts, "", 1);
}
}
out = M_list_str_join(parts, (unsigned char)M_fs_path_get_system_sep(sys_type));
M_list_str_destroy(parts);
return out;
}
| 169,146 |
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 jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_qcd_t *qcd = &ms->parms.qcd;
int i;
fprintf(out, "qntsty = %d; numguard = %d; numstepsizes = %d\n",
(int) qcd->compparms.qntsty, qcd->compparms.numguard, qcd->compparms.numstepsizes);
for (i = 0; i < qcd->compparms.numstepsizes; ++i) {
fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n",
i, (unsigned) JPC_QCX_GETEXPN(qcd->compparms.stepsizes[i]),
i, (unsigned) JPC_QCX_GETMANT(qcd->compparms.stepsizes[i]));
}
return 0;
}
Commit Message: Changed the JPC bitstream code to more gracefully handle a request
for a larger sized integer than what can be handled (i.e., return
with an error instead of failing an assert).
CWE ID: | static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_qcd_t *qcd = &ms->parms.qcd;
int i;
fprintf(out, "qntsty = %d; numguard = %d; numstepsizes = %d\n",
(int) qcd->compparms.qntsty, qcd->compparms.numguard, qcd->compparms.numstepsizes);
for (i = 0; i < qcd->compparms.numstepsizes; ++i) {
fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n",
i, JAS_CAST(unsigned, JPC_QCX_GETEXPN(qcd->compparms.stepsizes[i])),
i, JAS_CAST(unsigned, JPC_QCX_GETMANT(qcd->compparms.stepsizes[i])));
}
return 0;
}
| 168,734 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int try_read_command(conn *c) {
assert(c != NULL);
assert(c->rcurr <= (c->rbuf + c->rsize));
assert(c->rbytes > 0);
if (c->protocol == negotiating_prot || c->transport == udp_transport) {
if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) {
c->protocol = binary_prot;
} else {
c->protocol = ascii_prot;
}
if (settings.verbose > 1) {
fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd,
prot_text(c->protocol));
}
}
if (c->protocol == binary_prot) {
/* Do we have the complete packet header? */
if (c->rbytes < sizeof(c->binary_header)) {
/* need more data! */
return 0;
} else {
#ifdef NEED_ALIGN
if (((long)(c->rcurr)) % 8 != 0) {
/* must realign input buffer */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Realign input buffer\n", c->sfd);
}
}
#endif
protocol_binary_request_header* req;
req = (protocol_binary_request_header*)c->rcurr;
if (settings.verbose > 1) {
/* Dump the packet before we convert it to host order */
int ii;
fprintf(stderr, "<%d Read binary protocol data:", c->sfd);
for (ii = 0; ii < sizeof(req->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n<%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", req->bytes[ii]);
}
fprintf(stderr, "\n");
}
c->binary_header = *req;
c->binary_header.request.keylen = ntohs(req->request.keylen);
c->binary_header.request.bodylen = ntohl(req->request.bodylen);
c->binary_header.request.cas = ntohll(req->request.cas);
if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) {
if (settings.verbose) {
fprintf(stderr, "Invalid magic: %x\n",
c->binary_header.request.magic);
}
conn_set_state(c, conn_closing);
return -1;
}
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_string(c, "SERVER_ERROR out of memory");
return 0;
}
c->cmd = c->binary_header.request.opcode;
c->keylen = c->binary_header.request.keylen;
c->opaque = c->binary_header.request.opaque;
/* clear the returned cas value */
c->cas = 0;
dispatch_bin_command(c);
c->rbytes -= sizeof(c->binary_header);
c->rcurr += sizeof(c->binary_header);
}
} else {
char *el, *cont;
if (c->rbytes == 0)
return 0;
el = memchr(c->rcurr, '\n', c->rbytes);
if (!el)
return 0;
cont = el + 1;
if ((el - c->rcurr) > 1 && *(el - 1) == '\r') {
el--;
}
*el = '\0';
assert(cont <= (c->rcurr + c->rbytes));
process_command(c, c->rcurr);
c->rbytes -= (cont - c->rcurr);
c->rcurr = cont;
assert(c->rcurr <= (c->rbuf + c->rsize));
}
return 1;
}
Commit Message: Issue 102: Piping null to the server will crash it
CWE ID: CWE-20 | static int try_read_command(conn *c) {
assert(c != NULL);
assert(c->rcurr <= (c->rbuf + c->rsize));
assert(c->rbytes > 0);
if (c->protocol == negotiating_prot || c->transport == udp_transport) {
if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) {
c->protocol = binary_prot;
} else {
c->protocol = ascii_prot;
}
if (settings.verbose > 1) {
fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd,
prot_text(c->protocol));
}
}
if (c->protocol == binary_prot) {
/* Do we have the complete packet header? */
if (c->rbytes < sizeof(c->binary_header)) {
/* need more data! */
return 0;
} else {
#ifdef NEED_ALIGN
if (((long)(c->rcurr)) % 8 != 0) {
/* must realign input buffer */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Realign input buffer\n", c->sfd);
}
}
#endif
protocol_binary_request_header* req;
req = (protocol_binary_request_header*)c->rcurr;
if (settings.verbose > 1) {
/* Dump the packet before we convert it to host order */
int ii;
fprintf(stderr, "<%d Read binary protocol data:", c->sfd);
for (ii = 0; ii < sizeof(req->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n<%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", req->bytes[ii]);
}
fprintf(stderr, "\n");
}
c->binary_header = *req;
c->binary_header.request.keylen = ntohs(req->request.keylen);
c->binary_header.request.bodylen = ntohl(req->request.bodylen);
c->binary_header.request.cas = ntohll(req->request.cas);
if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) {
if (settings.verbose) {
fprintf(stderr, "Invalid magic: %x\n",
c->binary_header.request.magic);
}
conn_set_state(c, conn_closing);
return -1;
}
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_string(c, "SERVER_ERROR out of memory");
return 0;
}
c->cmd = c->binary_header.request.opcode;
c->keylen = c->binary_header.request.keylen;
c->opaque = c->binary_header.request.opaque;
/* clear the returned cas value */
c->cas = 0;
dispatch_bin_command(c);
c->rbytes -= sizeof(c->binary_header);
c->rcurr += sizeof(c->binary_header);
}
} else {
char *el, *cont;
if (c->rbytes == 0)
return 0;
el = memchr(c->rcurr, '\n', c->rbytes);
if (!el) {
if (c->rbytes > 1024) {
/*
* We didn't have a '\n' in the first k. This _has_ to be a
* large multiget, if not we should just nuke the connection.
*/
char *ptr = c->rcurr;
while (*ptr == ' ') { /* ignore leading whitespaces */
++ptr;
}
if (strcmp(ptr, "get ") && strcmp(ptr, "gets ")) {
conn_set_state(c, conn_closing);
return 1;
}
}
return 0;
}
cont = el + 1;
if ((el - c->rcurr) > 1 && *(el - 1) == '\r') {
el--;
}
*el = '\0';
assert(cont <= (c->rcurr + c->rbytes));
process_command(c, c->rcurr);
c->rbytes -= (cont - c->rcurr);
c->rcurr = cont;
assert(c->rcurr <= (c->rbuf + c->rsize));
}
return 1;
}
| 169,875 |
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 parseOperand(RAsm *a, const char *str, Operand *op, bool isrepop) {
size_t pos, nextpos = 0;
x86newTokenType last_type;
int size_token = 1;
bool explicit_size = false;
int reg_index = 0;
op->type = 0;
while (size_token) {
pos = nextpos;
last_type = getToken (str, &pos, &nextpos);
if (!r_str_ncasecmp (str + pos, "ptr", 3)) {
continue;
} else if (!r_str_ncasecmp (str + pos, "byte", 4)) {
op->type |= OT_MEMORY | OT_BYTE;
op->dest_size = OT_BYTE;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "word", 4)) {
op->type |= OT_MEMORY | OT_WORD;
op->dest_size = OT_WORD;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "dword", 5)) {
op->type |= OT_MEMORY | OT_DWORD;
op->dest_size = OT_DWORD;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "qword", 5)) {
op->type |= OT_MEMORY | OT_QWORD;
op->dest_size = OT_QWORD;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "oword", 5)) {
op->type |= OT_MEMORY | OT_OWORD;
op->dest_size = OT_OWORD;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "tbyte", 5)) {
op->type |= OT_MEMORY | OT_TBYTE;
op->dest_size = OT_TBYTE;
explicit_size = true;
} else { // the current token doesn't denote a size
size_token = 0;
}
}
if (str[pos] == '[') {
if (!op->type) {
op->type = OT_MEMORY;
}
op->offset = op->scale[0] = op->scale[1] = 0;
ut64 temp = 1;
Register reg = X86R_UNDEFINED;
bool first_reg = true;
while (str[pos] != ']') {
if (pos > nextpos) {
break;
}
pos = nextpos;
if (!str[pos]) {
break;
}
last_type = getToken (str, &pos, &nextpos);
if (last_type == TT_SPECIAL) {
if (str[pos] == '+' || str[pos] == '-' || str[pos] == ']') {
if (reg != X86R_UNDEFINED) {
op->regs[reg_index] = reg;
op->scale[reg_index] = temp;
++reg_index;
} else {
op->offset += temp;
op->regs[reg_index] = X86R_UNDEFINED;
}
temp = 1;
reg = X86R_UNDEFINED;
} else if (str[pos] == '*') {
}
}
else if (last_type == TT_WORD) {
ut32 reg_type = 0;
if (reg != X86R_UNDEFINED) {
op->type = 0; // Make the result invalid
}
nextpos = pos;
reg = parseReg (a, str, &nextpos, ®_type);
if (first_reg) {
op->extended = false;
if (reg > 8) {
op->extended = true;
op->reg = reg - 9;
}
first_reg = false;
} else if (reg > 8) {
op->reg = reg - 9;
}
if (reg_type & OT_REGTYPE & OT_SEGMENTREG) {
op->reg = reg;
op->type = reg_type;
parse_segment_offset (a, str, &nextpos, op, reg_index);
return nextpos;
}
if (!explicit_size) {
op->type |= reg_type;
}
op->reg_size = reg_type;
op->explicit_size = explicit_size;
if (!(reg_type & OT_GPREG)) {
op->type = 0; // Make the result invalid
}
}
else {
char *p = strchr (str, '+');
op->offset_sign = 1;
if (!p) {
p = strchr (str, '-');
if (p) {
op->offset_sign = -1;
}
}
char * plus = strchr (str, '+');
char * minus = strchr (str, '-');
char * closeB = strchr (str, ']');
if (plus && minus && plus < closeB && minus < closeB) {
op->offset_sign = -1;
}
char *tmp;
tmp = malloc (strlen (str + pos) + 1);
strcpy (tmp, str + pos);
strtok (tmp, "+-");
st64 read = getnum (a, tmp);
free (tmp);
temp *= read;
}
}
} else if (last_type == TT_WORD) { // register
nextpos = pos;
RFlagItem *flag;
if (isrepop) {
op->is_good_flag = false;
strncpy (op->rep_op, str, MAX_REPOP_LENGTH - 1);
op->rep_op[MAX_REPOP_LENGTH - 1] = '\0';
return nextpos;
}
op->reg = parseReg (a, str, &nextpos, &op->type);
op->extended = false;
if (op->reg > 8) {
op->extended = true;
op->reg -= 9;
}
if (op->type & OT_REGTYPE & OT_SEGMENTREG) {
parse_segment_offset (a, str, &nextpos, op, reg_index);
return nextpos;
}
if (op->reg == X86R_UNDEFINED) {
op->is_good_flag = false;
if (a->num && a->num->value == 0) {
return nextpos;
}
op->type = OT_CONSTANT;
RCore *core = a->num? (RCore *)(a->num->userptr): NULL;
if (core && (flag = r_flag_get (core->flags, str))) {
op->is_good_flag = true;
}
char *p = strchr (str, '-');
if (p) {
op->sign = -1;
str = ++p;
}
op->immediate = getnum (a, str);
} else if (op->reg < X86R_UNDEFINED) {
strncpy (op->rep_op, str, MAX_REPOP_LENGTH - 1);
op->rep_op[MAX_REPOP_LENGTH - 1] = '\0';
}
} else { // immediate
op->type = OT_CONSTANT;
op->sign = 1;
char *p = strchr (str, '-');
if (p) {
op->sign = -1;
str = ++p;
}
op->immediate = getnum (a, str);
}
return nextpos;
}
Commit Message: Fix #12372 and #12373 - Crash in x86 assembler (#12380)
0 ,0,[bP-bL-bP-bL-bL-r-bL-bP-bL-bL-
mov ,0,[ax+Bx-ax+Bx-ax+ax+Bx-ax+Bx--
leA ,0,[bP-bL-bL-bP-bL-bP-bL-60@bL-
leA ,0,[bP-bL-r-bP-bL-bP-bL-60@bL-
mov ,0,[ax+Bx-ax+Bx-ax+ax+Bx-ax+Bx--
CWE ID: CWE-125 | static int parseOperand(RAsm *a, const char *str, Operand *op, bool isrepop) {
size_t pos, nextpos = 0;
x86newTokenType last_type;
int size_token = 1;
bool explicit_size = false;
int reg_index = 0;
op->type = 0;
while (size_token) {
pos = nextpos;
last_type = getToken (str, &pos, &nextpos);
if (!r_str_ncasecmp (str + pos, "ptr", 3)) {
continue;
} else if (!r_str_ncasecmp (str + pos, "byte", 4)) {
op->type |= OT_MEMORY | OT_BYTE;
op->dest_size = OT_BYTE;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "word", 4)) {
op->type |= OT_MEMORY | OT_WORD;
op->dest_size = OT_WORD;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "dword", 5)) {
op->type |= OT_MEMORY | OT_DWORD;
op->dest_size = OT_DWORD;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "qword", 5)) {
op->type |= OT_MEMORY | OT_QWORD;
op->dest_size = OT_QWORD;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "oword", 5)) {
op->type |= OT_MEMORY | OT_OWORD;
op->dest_size = OT_OWORD;
explicit_size = true;
} else if (!r_str_ncasecmp (str + pos, "tbyte", 5)) {
op->type |= OT_MEMORY | OT_TBYTE;
op->dest_size = OT_TBYTE;
explicit_size = true;
} else { // the current token doesn't denote a size
size_token = 0;
}
}
if (str[pos] == '[') {
if (!op->type) {
op->type = OT_MEMORY;
}
op->offset = op->scale[0] = op->scale[1] = 0;
ut64 temp = 1;
Register reg = X86R_UNDEFINED;
bool first_reg = true;
while (str[pos] != ']') {
if (pos > nextpos) {
break;
}
pos = nextpos;
if (!str[pos]) {
break;
}
last_type = getToken (str, &pos, &nextpos);
if (last_type == TT_SPECIAL) {
if (str[pos] == '+' || str[pos] == '-' || str[pos] == ']') {
if (reg != X86R_UNDEFINED) {
if (reg_index < 2) {
op->regs[reg_index] = reg;
op->scale[reg_index] = temp;
}
++reg_index;
} else {
op->offset += temp;
if (reg_index < 2) {
op->regs[reg_index] = X86R_UNDEFINED;
}
}
temp = 1;
reg = X86R_UNDEFINED;
} else if (str[pos] == '*') {
}
}
else if (last_type == TT_WORD) {
ut32 reg_type = 0;
if (reg != X86R_UNDEFINED) {
op->type = 0; // Make the result invalid
}
nextpos = pos;
reg = parseReg (a, str, &nextpos, ®_type);
if (first_reg) {
op->extended = false;
if (reg > 8) {
op->extended = true;
op->reg = reg - 9;
}
first_reg = false;
} else if (reg > 8) {
op->reg = reg - 9;
}
if (reg_type & OT_REGTYPE & OT_SEGMENTREG) {
op->reg = reg;
op->type = reg_type;
parse_segment_offset (a, str, &nextpos, op, reg_index);
return nextpos;
}
if (!explicit_size) {
op->type |= reg_type;
}
op->reg_size = reg_type;
op->explicit_size = explicit_size;
if (!(reg_type & OT_GPREG)) {
op->type = 0; // Make the result invalid
}
}
else {
char *p = strchr (str, '+');
op->offset_sign = 1;
if (!p) {
p = strchr (str, '-');
if (p) {
op->offset_sign = -1;
}
}
char * plus = strchr (str, '+');
char * minus = strchr (str, '-');
char * closeB = strchr (str, ']');
if (plus && minus && plus < closeB && minus < closeB) {
op->offset_sign = -1;
}
char *tmp;
tmp = malloc (strlen (str + pos) + 1);
strcpy (tmp, str + pos);
strtok (tmp, "+-");
st64 read = getnum (a, tmp);
free (tmp);
temp *= read;
}
}
} else if (last_type == TT_WORD) { // register
nextpos = pos;
RFlagItem *flag;
if (isrepop) {
op->is_good_flag = false;
strncpy (op->rep_op, str, MAX_REPOP_LENGTH - 1);
op->rep_op[MAX_REPOP_LENGTH - 1] = '\0';
return nextpos;
}
op->reg = parseReg (a, str, &nextpos, &op->type);
op->extended = false;
if (op->reg > 8) {
op->extended = true;
op->reg -= 9;
}
if (op->type & OT_REGTYPE & OT_SEGMENTREG) {
parse_segment_offset (a, str, &nextpos, op, reg_index);
return nextpos;
}
if (op->reg == X86R_UNDEFINED) {
op->is_good_flag = false;
if (a->num && a->num->value == 0) {
return nextpos;
}
op->type = OT_CONSTANT;
RCore *core = a->num? (RCore *)(a->num->userptr): NULL;
if (core && (flag = r_flag_get (core->flags, str))) {
op->is_good_flag = true;
}
char *p = strchr (str, '-');
if (p) {
op->sign = -1;
str = ++p;
}
op->immediate = getnum (a, str);
} else if (op->reg < X86R_UNDEFINED) {
strncpy (op->rep_op, str, MAX_REPOP_LENGTH - 1);
op->rep_op[MAX_REPOP_LENGTH - 1] = '\0';
}
} else { // immediate
op->type = OT_CONSTANT;
op->sign = 1;
char *p = strchr (str, '-');
if (p) {
op->sign = -1;
str = ++p;
}
op->immediate = getnum (a, str);
}
return nextpos;
}
| 168,956 |
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: int32_t DownmixLib_Create(const effect_uuid_t *uuid,
int32_t sessionId,
int32_t ioId,
effect_handle_t *pHandle) {
int ret;
int i;
downmix_module_t *module;
const effect_descriptor_t *desc;
ALOGV("DownmixLib_Create()");
#ifdef DOWNMIX_TEST_CHANNEL_INDEX
ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should work:");
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT |
AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_CENTER);
Downmix_testIndexComputation(CHANNEL_MASK_QUAD_SIDE | CHANNEL_MASK_QUAD_BACK);
Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_SIDE | AUDIO_CHANNEL_OUT_BACK_CENTER);
Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_BACK | AUDIO_CHANNEL_OUT_BACK_CENTER);
ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should NOT work:");
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT |
AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_LEFT);
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT |
AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_SIDE_LEFT);
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT |
AUDIO_CHANNEL_OUT_BACK_LEFT | AUDIO_CHANNEL_OUT_BACK_RIGHT);
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT |
AUDIO_CHANNEL_OUT_SIDE_LEFT | AUDIO_CHANNEL_OUT_SIDE_RIGHT);
#endif
if (pHandle == NULL || uuid == NULL) {
return -EINVAL;
}
for (i = 0 ; i < kNbEffects ; i++) {
desc = gDescriptors[i];
if (memcmp(uuid, &desc->uuid, sizeof(effect_uuid_t)) == 0) {
break;
}
}
if (i == kNbEffects) {
return -ENOENT;
}
module = malloc(sizeof(downmix_module_t));
module->itfe = &gDownmixInterface;
module->context.state = DOWNMIX_STATE_UNINITIALIZED;
ret = Downmix_Init(module);
if (ret < 0) {
ALOGW("DownmixLib_Create() init failed");
free(module);
return ret;
}
*pHandle = (effect_handle_t) module;
ALOGV("DownmixLib_Create() %p , size %zu", module, sizeof(downmix_module_t));
return 0;
}
Commit Message: audio effects: fix heap overflow
Check consistency of effect command reply sizes before
copying to reply address.
Also add null pointer check on reply size.
Also remove unused parameter warning.
Bug: 21953516.
Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4
(cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844)
CWE ID: CWE-119 | int32_t DownmixLib_Create(const effect_uuid_t *uuid,
int32_t sessionId __unused,
int32_t ioId __unused,
effect_handle_t *pHandle) {
int ret;
int i;
downmix_module_t *module;
const effect_descriptor_t *desc;
ALOGV("DownmixLib_Create()");
#ifdef DOWNMIX_TEST_CHANNEL_INDEX
ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should work:");
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT |
AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_CENTER);
Downmix_testIndexComputation(CHANNEL_MASK_QUAD_SIDE | CHANNEL_MASK_QUAD_BACK);
Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_SIDE | AUDIO_CHANNEL_OUT_BACK_CENTER);
Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_BACK | AUDIO_CHANNEL_OUT_BACK_CENTER);
ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should NOT work:");
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT |
AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_LEFT);
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT |
AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_SIDE_LEFT);
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT |
AUDIO_CHANNEL_OUT_BACK_LEFT | AUDIO_CHANNEL_OUT_BACK_RIGHT);
Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT |
AUDIO_CHANNEL_OUT_SIDE_LEFT | AUDIO_CHANNEL_OUT_SIDE_RIGHT);
#endif
if (pHandle == NULL || uuid == NULL) {
return -EINVAL;
}
for (i = 0 ; i < kNbEffects ; i++) {
desc = gDescriptors[i];
if (memcmp(uuid, &desc->uuid, sizeof(effect_uuid_t)) == 0) {
break;
}
}
if (i == kNbEffects) {
return -ENOENT;
}
module = malloc(sizeof(downmix_module_t));
module->itfe = &gDownmixInterface;
module->context.state = DOWNMIX_STATE_UNINITIALIZED;
ret = Downmix_Init(module);
if (ret < 0) {
ALOGW("DownmixLib_Create() init failed");
free(module);
return ret;
}
*pHandle = (effect_handle_t) module;
ALOGV("DownmixLib_Create() %p , size %zu", module, sizeof(downmix_module_t));
return 0;
}
| 173,343 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.