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: static Image *ReadSCTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
magick[2];
Image
*image;
MagickBooleanType
status;
MagickRealType
height,
width;
Quantum
pixel;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
count,
y;
unsigned char
buffer[768];
size_t
separations,
separations_mask,
units;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read control block.
*/
count=ReadBlob(image,80,buffer);
(void) count;
count=ReadBlob(image,2,(unsigned char *) magick);
if ((LocaleNCompare((char *) magick,"CT",2) != 0) &&
(LocaleNCompare((char *) magick,"LW",2) != 0) &&
(LocaleNCompare((char *) magick,"BM",2) != 0) &&
(LocaleNCompare((char *) magick,"PG",2) != 0) &&
(LocaleNCompare((char *) magick,"TX",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((LocaleNCompare((char *) magick,"LW",2) == 0) ||
(LocaleNCompare((char *) magick,"BM",2) == 0) ||
(LocaleNCompare((char *) magick,"PG",2) == 0) ||
(LocaleNCompare((char *) magick,"TX",2) == 0))
ThrowReaderException(CoderError,"OnlyContinuousTonePictureSupported");
count=ReadBlob(image,174,buffer);
count=ReadBlob(image,768,buffer);
/*
Read paramter block.
*/
units=1UL*ReadBlobByte(image);
if (units == 0)
image->units=PixelsPerCentimeterResolution;
separations=1UL*ReadBlobByte(image);
separations_mask=ReadBlobMSBShort(image);
count=ReadBlob(image,14,buffer);
buffer[14]='\0';
height=StringToDouble((char *) buffer,(char **) NULL);
count=ReadBlob(image,14,buffer);
width=StringToDouble((char *) buffer,(char **) NULL);
count=ReadBlob(image,12,buffer);
buffer[12]='\0';
image->rows=StringToUnsignedLong((char *) buffer);
count=ReadBlob(image,12,buffer);
image->columns=StringToUnsignedLong((char *) buffer);
count=ReadBlob(image,200,buffer);
count=ReadBlob(image,768,buffer);
if (separations_mask == 0x0f)
SetImageColorspace(image,CMYKColorspace);
image->x_resolution=1.0*image->columns/width;
image->y_resolution=1.0*image->rows/height;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Convert SCT raster image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
for (i=0; i < (ssize_t) separations; i++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
if (image->colorspace == CMYKColorspace)
pixel=(Quantum) (QuantumRange-pixel);
switch (i)
{
case 0:
{
SetPixelRed(q,pixel);
SetPixelGreen(q,pixel);
SetPixelBlue(q,pixel);
break;
}
case 1:
{
SetPixelGreen(q,pixel);
break;
}
case 2:
{
SetPixelBlue(q,pixel);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(indexes+x,pixel);
break;
}
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if ((image->columns % 2) != 0)
(void) ReadBlobByte(image); /* pad */
}
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadSCTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
magick[2];
Image
*image;
MagickBooleanType
status;
MagickRealType
height,
width;
Quantum
pixel;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
count,
y;
unsigned char
buffer[768];
size_t
separations,
separations_mask,
units;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read control block.
*/
count=ReadBlob(image,80,buffer);
(void) count;
count=ReadBlob(image,2,(unsigned char *) magick);
if ((LocaleNCompare((char *) magick,"CT",2) != 0) &&
(LocaleNCompare((char *) magick,"LW",2) != 0) &&
(LocaleNCompare((char *) magick,"BM",2) != 0) &&
(LocaleNCompare((char *) magick,"PG",2) != 0) &&
(LocaleNCompare((char *) magick,"TX",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((LocaleNCompare((char *) magick,"LW",2) == 0) ||
(LocaleNCompare((char *) magick,"BM",2) == 0) ||
(LocaleNCompare((char *) magick,"PG",2) == 0) ||
(LocaleNCompare((char *) magick,"TX",2) == 0))
ThrowReaderException(CoderError,"OnlyContinuousTonePictureSupported");
count=ReadBlob(image,174,buffer);
count=ReadBlob(image,768,buffer);
/*
Read paramter block.
*/
units=1UL*ReadBlobByte(image);
if (units == 0)
image->units=PixelsPerCentimeterResolution;
separations=1UL*ReadBlobByte(image);
separations_mask=ReadBlobMSBShort(image);
count=ReadBlob(image,14,buffer);
buffer[14]='\0';
height=StringToDouble((char *) buffer,(char **) NULL);
count=ReadBlob(image,14,buffer);
width=StringToDouble((char *) buffer,(char **) NULL);
count=ReadBlob(image,12,buffer);
buffer[12]='\0';
image->rows=StringToUnsignedLong((char *) buffer);
count=ReadBlob(image,12,buffer);
image->columns=StringToUnsignedLong((char *) buffer);
count=ReadBlob(image,200,buffer);
count=ReadBlob(image,768,buffer);
if (separations_mask == 0x0f)
SetImageColorspace(image,CMYKColorspace);
image->x_resolution=1.0*image->columns/width;
image->y_resolution=1.0*image->rows/height;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Convert SCT raster image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
for (i=0; i < (ssize_t) separations; i++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
if (image->colorspace == CMYKColorspace)
pixel=(Quantum) (QuantumRange-pixel);
switch (i)
{
case 0:
{
SetPixelRed(q,pixel);
SetPixelGreen(q,pixel);
SetPixelBlue(q,pixel);
break;
}
case 1:
{
SetPixelGreen(q,pixel);
break;
}
case 2:
{
SetPixelBlue(q,pixel);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(indexes+x,pixel);
break;
}
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if ((image->columns % 2) != 0)
(void) ReadBlobByte(image); /* pad */
}
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,603 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PeopleHandler::HandlePauseSync(const base::ListValue* args) {
DCHECK(AccountConsistencyModeManager::IsDiceEnabledForProfile(profile_));
SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile_);
DCHECK(signin_manager->IsAuthenticated());
ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)->UpdateCredentials(
signin_manager->GetAuthenticatedAccountId(),
OAuth2TokenServiceDelegate::kInvalidRefreshToken);
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20 | void PeopleHandler::HandlePauseSync(const base::ListValue* args) {
DCHECK(AccountConsistencyModeManager::IsDiceEnabledForProfile(profile_));
SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile_);
DCHECK(signin_manager->IsAuthenticated());
ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)->UpdateCredentials(
signin_manager->GetAuthenticatedAccountId(),
OAuth2TokenServiceDelegate::kInvalidRefreshToken,
signin_metrics::SourceForRefreshTokenOperation::kSettings_PauseSync);
}
| 172,572 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int ldsem_cmpxchg(long *old, long new, struct ld_semaphore *sem)
{
long tmp = *old;
*old = atomic_long_cmpxchg(&sem->count, *old, new);
return *old == tmp;
}
Commit Message: tty: Fix hang at ldsem_down_read()
When a controlling tty is being hung up and the hang up is
waiting for a just-signalled tty reader or writer to exit, and a new tty
reader/writer tries to acquire an ldisc reference concurrently with the
ldisc reference release from the signalled reader/writer, the hangup
can hang. The new reader/writer is sleeping in ldsem_down_read() and the
hangup is sleeping in ldsem_down_write() [1].
The new reader/writer fails to wakeup the waiting hangup because the
wrong lock count value is checked (the old lock count rather than the new
lock count) to see if the lock is unowned.
Change helper function to return the new lock count if the cmpxchg was
successful; document this behavior.
[1] edited dmesg log from reporter
SysRq : Show Blocked State
task PC stack pid father
systemd D ffff88040c4f0000 0 1 0 0x00000000
ffff88040c49fbe0 0000000000000046 ffff88040c4a0000 ffff88040c49ffd8
00000000001d3980 00000000001d3980 ffff88040c4a0000 ffff88040593d840
ffff88040c49fb40 ffffffff810a4cc0 0000000000000006 0000000000000023
Call Trace:
[<ffffffff810a4cc0>] ? sched_clock_cpu+0x9f/0xe4
[<ffffffff810a4cc0>] ? sched_clock_cpu+0x9f/0xe4
[<ffffffff810a4cc0>] ? sched_clock_cpu+0x9f/0xe4
[<ffffffff810a4cc0>] ? sched_clock_cpu+0x9f/0xe4
[<ffffffff817a6649>] schedule+0x24/0x5e
[<ffffffff817a588b>] schedule_timeout+0x15b/0x1ec
[<ffffffff810a4cc0>] ? sched_clock_cpu+0x9f/0xe4
[<ffffffff817aa691>] ? _raw_spin_unlock_irq+0x24/0x26
[<ffffffff817aa10c>] down_read_failed+0xe3/0x1b9
[<ffffffff817aa26d>] ldsem_down_read+0x8b/0xa5
[<ffffffff8142b5ca>] ? tty_ldisc_ref_wait+0x1b/0x44
[<ffffffff8142b5ca>] tty_ldisc_ref_wait+0x1b/0x44
[<ffffffff81423f5b>] tty_write+0x7d/0x28a
[<ffffffff814241f5>] redirected_tty_write+0x8d/0x98
[<ffffffff81424168>] ? tty_write+0x28a/0x28a
[<ffffffff8115d03f>] do_loop_readv_writev+0x56/0x79
[<ffffffff8115e604>] do_readv_writev+0x1b0/0x1ff
[<ffffffff8116ea0b>] ? do_vfs_ioctl+0x32a/0x489
[<ffffffff81167d9d>] ? final_putname+0x1d/0x3a
[<ffffffff8115e6c7>] vfs_writev+0x2e/0x49
[<ffffffff8115e7d3>] SyS_writev+0x47/0xaa
[<ffffffff817ab822>] system_call_fastpath+0x16/0x1b
bash D ffffffff81c104c0 0 5469 5302 0x00000082
ffff8800cf817ac0 0000000000000046 ffff8804086b22a0 ffff8800cf817fd8
00000000001d3980 00000000001d3980 ffff8804086b22a0 ffff8800cf817a48
000000000000b9a0 ffff8800cf817a78 ffffffff81004675 ffff8800cf817a44
Call Trace:
[<ffffffff81004675>] ? dump_trace+0x165/0x29c
[<ffffffff810a4cc0>] ? sched_clock_cpu+0x9f/0xe4
[<ffffffff8100edda>] ? save_stack_trace+0x26/0x41
[<ffffffff817a6649>] schedule+0x24/0x5e
[<ffffffff817a588b>] schedule_timeout+0x15b/0x1ec
[<ffffffff810a4cc0>] ? sched_clock_cpu+0x9f/0xe4
[<ffffffff817a9f03>] ? down_write_failed+0xa3/0x1c9
[<ffffffff817aa691>] ? _raw_spin_unlock_irq+0x24/0x26
[<ffffffff817a9f0b>] down_write_failed+0xab/0x1c9
[<ffffffff817aa300>] ldsem_down_write+0x79/0xb1
[<ffffffff817aada3>] ? tty_ldisc_lock_pair_timeout+0xa5/0xd9
[<ffffffff817aada3>] tty_ldisc_lock_pair_timeout+0xa5/0xd9
[<ffffffff8142bf33>] tty_ldisc_hangup+0xc4/0x218
[<ffffffff81423ab3>] __tty_hangup+0x2e2/0x3ed
[<ffffffff81424a76>] disassociate_ctty+0x63/0x226
[<ffffffff81078aa7>] do_exit+0x79f/0xa11
[<ffffffff81086bdb>] ? get_signal_to_deliver+0x206/0x62f
[<ffffffff810b4bfb>] ? lock_release_holdtime.part.8+0xf/0x16e
[<ffffffff81079b05>] do_group_exit+0x47/0xb5
[<ffffffff81086c16>] get_signal_to_deliver+0x241/0x62f
[<ffffffff810020a7>] do_signal+0x43/0x59d
[<ffffffff810f2af7>] ? __audit_syscall_exit+0x21a/0x2a8
[<ffffffff810b4bfb>] ? lock_release_holdtime.part.8+0xf/0x16e
[<ffffffff81002655>] do_notify_resume+0x54/0x6c
[<ffffffff817abaf8>] int_signal+0x12/0x17
Reported-by: Sami Farin <[email protected]>
Cc: <[email protected]> # 3.12.x
Signed-off-by: Peter Hurley <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-362 | static inline int ldsem_cmpxchg(long *old, long new, struct ld_semaphore *sem)
{
long tmp = atomic_long_cmpxchg(&sem->count, *old, new);
if (tmp == *old) {
*old = new;
return 1;
} else {
*old = tmp;
return 0;
}
}
| 167,566 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 add_ballooned_pages(int nr_pages)
{
enum bp_state st;
if (xen_hotplug_unpopulated) {
st = reserve_additional_memory();
if (st != BP_ECANCELED) {
mutex_unlock(&balloon_mutex);
wait_event(balloon_wq,
!list_empty(&ballooned_pages));
mutex_lock(&balloon_mutex);
return 0;
}
}
st = decrease_reservation(nr_pages, GFP_USER);
if (st != BP_DONE)
return -ENOMEM;
return 0;
}
Commit Message: xen: let alloc_xenballooned_pages() fail if not enough memory free
commit a1078e821b605813b63bf6bca414a85f804d5c66 upstream.
Instead of trying to allocate pages with GFP_USER in
add_ballooned_pages() check the available free memory via
si_mem_available(). GFP_USER is far less limiting memory exhaustion
than the test via si_mem_available().
This will avoid dom0 running out of memory due to excessive foreign
page mappings especially on ARM and on x86 in PVH mode, as those don't
have a pre-ballooned area which can be used for foreign mappings.
As the normal ballooning suffers from the same problem don't balloon
down more than si_mem_available() pages in one iteration. At the same
time limit the default maximum number of retries.
This is part of XSA-300.
Signed-off-by: Juergen Gross <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-400 | static int add_ballooned_pages(int nr_pages)
{
enum bp_state st;
if (xen_hotplug_unpopulated) {
st = reserve_additional_memory();
if (st != BP_ECANCELED) {
mutex_unlock(&balloon_mutex);
wait_event(balloon_wq,
!list_empty(&ballooned_pages));
mutex_lock(&balloon_mutex);
return 0;
}
}
if (si_mem_available() < nr_pages)
return -ENOMEM;
st = decrease_reservation(nr_pages, GFP_USER);
if (st != BP_DONE)
return -ENOMEM;
return 0;
}
| 169,492 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc,
int normalize)
{
xmlChar limit = 0;
const xmlChar *in = NULL, *start, *end, *last;
xmlChar *ret = NULL;
GROW;
in = (xmlChar *) CUR_PTR;
if (*in != '"' && *in != '\'') {
xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL);
return (NULL);
}
ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE;
/*
* try to handle in this routine the most common case where no
* allocation of a new string is required and where content is
* pure ASCII.
*/
limit = *in++;
end = ctxt->input->end;
start = in;
if (in >= end) {
const xmlChar *oldbase = ctxt->input->base;
GROW;
if (oldbase != ctxt->input->base) {
long delta = ctxt->input->base - oldbase;
start = start + delta;
in = in + delta;
}
end = ctxt->input->end;
}
if (normalize) {
/*
* Skip any leading spaces
*/
while ((in < end) && (*in != limit) &&
((*in == 0x20) || (*in == 0x9) ||
(*in == 0xA) || (*in == 0xD))) {
in++;
start = in;
if (in >= end) {
const xmlChar *oldbase = ctxt->input->base;
GROW;
if (oldbase != ctxt->input->base) {
long delta = ctxt->input->base - oldbase;
start = start + delta;
in = in + delta;
}
end = ctxt->input->end;
}
}
while ((in < end) && (*in != limit) && (*in >= 0x20) &&
(*in <= 0x7f) && (*in != '&') && (*in != '<')) {
if ((*in++ == 0x20) && (*in == 0x20)) break;
if (in >= end) {
const xmlChar *oldbase = ctxt->input->base;
GROW;
if (oldbase != ctxt->input->base) {
long delta = ctxt->input->base - oldbase;
start = start + delta;
in = in + delta;
}
end = ctxt->input->end;
}
}
last = in;
/*
* skip the trailing blanks
*/
while ((last[-1] == 0x20) && (last > start)) last--;
while ((in < end) && (*in != limit) &&
((*in == 0x20) || (*in == 0x9) ||
(*in == 0xA) || (*in == 0xD))) {
in++;
if (in >= end) {
const xmlChar *oldbase = ctxt->input->base;
GROW;
if (oldbase != ctxt->input->base) {
long delta = ctxt->input->base - oldbase;
start = start + delta;
in = in + delta;
last = last + delta;
}
end = ctxt->input->end;
}
}
if (*in != limit) goto need_complex;
} else {
while ((in < end) && (*in != limit) && (*in >= 0x20) &&
(*in <= 0x7f) && (*in != '&') && (*in != '<')) {
in++;
if (in >= end) {
const xmlChar *oldbase = ctxt->input->base;
GROW;
if (oldbase != ctxt->input->base) {
long delta = ctxt->input->base - oldbase;
start = start + delta;
in = in + delta;
}
end = ctxt->input->end;
}
}
last = in;
if (*in != limit) goto need_complex;
}
in++;
if (len != NULL) {
*len = last - start;
ret = (xmlChar *) start;
} else {
if (alloc) *alloc = 1;
ret = xmlStrndup(start, last - start);
}
CUR_PTR = in;
if (alloc) *alloc = 0;
return ret;
need_complex:
if (alloc) *alloc = 1;
return xmlParseAttValueComplex(ctxt, len, normalize);
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc,
int normalize)
{
xmlChar limit = 0;
const xmlChar *in = NULL, *start, *end, *last;
xmlChar *ret = NULL;
GROW;
in = (xmlChar *) CUR_PTR;
if (*in != '"' && *in != '\'') {
xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL);
return (NULL);
}
ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE;
/*
* try to handle in this routine the most common case where no
* allocation of a new string is required and where content is
* pure ASCII.
*/
limit = *in++;
end = ctxt->input->end;
start = in;
if (in >= end) {
const xmlChar *oldbase = ctxt->input->base;
GROW;
if (oldbase != ctxt->input->base) {
long delta = ctxt->input->base - oldbase;
start = start + delta;
in = in + delta;
}
end = ctxt->input->end;
}
if (normalize) {
/*
* Skip any leading spaces
*/
while ((in < end) && (*in != limit) &&
((*in == 0x20) || (*in == 0x9) ||
(*in == 0xA) || (*in == 0xD))) {
in++;
start = in;
if (in >= end) {
const xmlChar *oldbase = ctxt->input->base;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
if (oldbase != ctxt->input->base) {
long delta = ctxt->input->base - oldbase;
start = start + delta;
in = in + delta;
}
end = ctxt->input->end;
}
}
while ((in < end) && (*in != limit) && (*in >= 0x20) &&
(*in <= 0x7f) && (*in != '&') && (*in != '<')) {
if ((*in++ == 0x20) && (*in == 0x20)) break;
if (in >= end) {
const xmlChar *oldbase = ctxt->input->base;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
if (oldbase != ctxt->input->base) {
long delta = ctxt->input->base - oldbase;
start = start + delta;
in = in + delta;
}
end = ctxt->input->end;
}
}
last = in;
/*
* skip the trailing blanks
*/
while ((last[-1] == 0x20) && (last > start)) last--;
while ((in < end) && (*in != limit) &&
((*in == 0x20) || (*in == 0x9) ||
(*in == 0xA) || (*in == 0xD))) {
in++;
if (in >= end) {
const xmlChar *oldbase = ctxt->input->base;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
if (oldbase != ctxt->input->base) {
long delta = ctxt->input->base - oldbase;
start = start + delta;
in = in + delta;
last = last + delta;
}
end = ctxt->input->end;
}
}
if (*in != limit) goto need_complex;
} else {
while ((in < end) && (*in != limit) && (*in >= 0x20) &&
(*in <= 0x7f) && (*in != '&') && (*in != '<')) {
in++;
if (in >= end) {
const xmlChar *oldbase = ctxt->input->base;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
if (oldbase != ctxt->input->base) {
long delta = ctxt->input->base - oldbase;
start = start + delta;
in = in + delta;
}
end = ctxt->input->end;
}
}
last = in;
if (*in != limit) goto need_complex;
}
in++;
if (len != NULL) {
*len = last - start;
ret = (xmlChar *) start;
} else {
if (alloc) *alloc = 1;
ret = xmlStrndup(start, last - start);
}
CUR_PTR = in;
if (alloc) *alloc = 0;
return ret;
need_complex:
if (alloc) *alloc = 1;
return xmlParseAttValueComplex(ctxt, len, normalize);
}
| 171,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: next_format(png_bytep colour_type, png_bytep bit_depth,
unsigned int* palette_number, int no_low_depth_gray)
{
if (*bit_depth == 0)
{
*colour_type = 0;
if (no_low_depth_gray)
*bit_depth = 8;
else
*bit_depth = 1;
*palette_number = 0;
return 1;
}
if (*colour_type == 3)
{
/* Add multiple palettes for colour type 3. */
if (++*palette_number < PALETTE_COUNT(*bit_depth))
return 1;
*palette_number = 0;
}
*bit_depth = (png_byte)(*bit_depth << 1);
/* Palette images are restricted to 8 bit depth */
if (*bit_depth <= 8
# ifdef DO_16BIT
|| (*colour_type != 3 && *bit_depth <= 16)
# endif
)
return 1;
/* Move to the next color type, or return 0 at the end. */
switch (*colour_type)
{
case 0:
*colour_type = 2;
*bit_depth = 8;
return 1;
case 2:
*colour_type = 3;
*bit_depth = 1;
return 1;
case 3:
*colour_type = 4;
*bit_depth = 8;
return 1;
case 4:
*colour_type = 6;
*bit_depth = 8;
return 1;
default:
return 0;
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | next_format(png_bytep colour_type, png_bytep bit_depth,
unsigned int* palette_number, int low_depth_gray, int tRNS)
{
if (*bit_depth == 0)
{
*colour_type = 0;
if (low_depth_gray)
*bit_depth = 1;
else
*bit_depth = 8;
*palette_number = 0;
return 1;
}
if (*colour_type < 4/*no alpha channel*/)
{
/* Add multiple palettes for colour type 3, one image with tRNS
* and one without for other non-alpha formats:
*/
unsigned int pn = ++*palette_number;
png_byte ct = *colour_type;
if (((ct == 0/*GRAY*/ || ct/*RGB*/ == 2) && tRNS && pn < 2) ||
(ct == 3/*PALETTE*/ && pn < PALETTE_COUNT(*bit_depth)))
return 1;
/* No: next bit depth */
*palette_number = 0;
}
*bit_depth = (png_byte)(*bit_depth << 1);
/* Palette images are restricted to 8 bit depth */
if (*bit_depth <= 8
#ifdef DO_16BIT
|| (*colour_type != 3 && *bit_depth <= 16)
#endif
)
return 1;
/* Move to the next color type, or return 0 at the end. */
switch (*colour_type)
{
case 0:
*colour_type = 2;
*bit_depth = 8;
return 1;
case 2:
*colour_type = 3;
*bit_depth = 1;
return 1;
case 3:
*colour_type = 4;
*bit_depth = 8;
return 1;
case 4:
*colour_type = 6;
*bit_depth = 8;
return 1;
default:
return 0;
}
}
| 173,672 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 host_start(struct ci13xxx *ci)
{
struct usb_hcd *hcd;
struct ehci_hcd *ehci;
int ret;
if (usb_disabled())
return -ENODEV;
hcd = usb_create_hcd(&ci_ehci_hc_driver, ci->dev, dev_name(ci->dev));
if (!hcd)
return -ENOMEM;
dev_set_drvdata(ci->dev, ci);
hcd->rsrc_start = ci->hw_bank.phys;
hcd->rsrc_len = ci->hw_bank.size;
hcd->regs = ci->hw_bank.abs;
hcd->has_tt = 1;
hcd->power_budget = ci->platdata->power_budget;
hcd->phy = ci->transceiver;
ehci = hcd_to_ehci(hcd);
ehci->caps = ci->hw_bank.cap;
ehci->has_hostpc = ci->hw_bank.lpm;
ret = usb_add_hcd(hcd, 0, 0);
if (ret)
usb_put_hcd(hcd);
else
ci->hcd = hcd;
return ret;
}
Commit Message: usb: chipidea: Allow disabling streaming not only in udc mode
When running a scp transfer using a USB/Ethernet adapter the following crash
happens:
$ scp test.tar.gz [email protected]:/home/fabio
[email protected]'s password:
test.tar.gz 0% 0 0.0KB/s --:-- ETA
------------[ cut here ]------------
WARNING: at net/sched/sch_generic.c:255 dev_watchdog+0x2cc/0x2f0()
NETDEV WATCHDOG: eth0 (asix): transmit queue 0 timed out
Modules linked in:
Backtrace:
[<80011c94>] (dump_backtrace+0x0/0x10c) from [<804d3a5c>] (dump_stack+0x18/0x1c)
r6:000000ff r5:80412388 r4:80685dc0 r3:80696cc0
[<804d3a44>] (dump_stack+0x0/0x1c) from [<80021868>]
(warn_slowpath_common+0x54/0x6c)
[<80021814>] (warn_slowpath_common+0x0/0x6c) from [<80021924>]
(warn_slowpath_fmt+0x38/0x40)
...
Setting SDIS (Stream Disable Mode- bit 4 of USBMODE register) fixes the problem.
However, in current code CI13XXX_DISABLE_STREAMING flag is only set in udc mode,
so allow disabling streaming also in host mode.
Tested on a mx6qsabrelite board.
Suggested-by: Peter Chen <[email protected]>
Signed-off-by: Fabio Estevam <[email protected]>
Reviewed-by: Peter Chen <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-119 | static int host_start(struct ci13xxx *ci)
{
struct usb_hcd *hcd;
struct ehci_hcd *ehci;
int ret;
if (usb_disabled())
return -ENODEV;
hcd = usb_create_hcd(&ci_ehci_hc_driver, ci->dev, dev_name(ci->dev));
if (!hcd)
return -ENOMEM;
dev_set_drvdata(ci->dev, ci);
hcd->rsrc_start = ci->hw_bank.phys;
hcd->rsrc_len = ci->hw_bank.size;
hcd->regs = ci->hw_bank.abs;
hcd->has_tt = 1;
hcd->power_budget = ci->platdata->power_budget;
hcd->phy = ci->transceiver;
ehci = hcd_to_ehci(hcd);
ehci->caps = ci->hw_bank.cap;
ehci->has_hostpc = ci->hw_bank.lpm;
ret = usb_add_hcd(hcd, 0, 0);
if (ret)
usb_put_hcd(hcd);
else
ci->hcd = hcd;
if (ci->platdata->flags & CI13XXX_DISABLE_STREAMING)
hw_write(ci, OP_USBMODE, USBMODE_CI_SDIS, USBMODE_CI_SDIS);
return ret;
}
| 166,087 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: XIQueryDevice(Display *dpy, int deviceid, int *ndevices_return)
{
XIDeviceInfo *info = NULL;
xXIQueryDeviceReq *req;
xXIQueryDeviceReq *req;
xXIQueryDeviceReply reply;
char *ptr;
int i;
char *buf;
LockDisplay(dpy);
if (_XiCheckExtInit(dpy, XInput_2_0, extinfo) == -1)
goto error_unlocked;
GetReq(XIQueryDevice, req);
req->reqType = extinfo->codes->major_opcode;
req->ReqType = X_XIQueryDevice;
req->deviceid = deviceid;
if (!_XReply(dpy, (xReply*) &reply, 0, xFalse))
goto error;
if (!_XReply(dpy, (xReply*) &reply, 0, xFalse))
goto error;
*ndevices_return = reply.num_devices;
info = Xmalloc((reply.num_devices + 1) * sizeof(XIDeviceInfo));
if (!info)
goto error;
buf = Xmalloc(reply.length * 4);
_XRead(dpy, buf, reply.length * 4);
ptr = buf;
/* info is a null-terminated array */
info[reply.num_devices].name = NULL;
nclasses = wire->num_classes;
ptr += sizeof(xXIDeviceInfo);
lib->name = Xcalloc(wire->name_len + 1, 1);
XIDeviceInfo *lib = &info[i];
xXIDeviceInfo *wire = (xXIDeviceInfo*)ptr;
lib->deviceid = wire->deviceid;
lib->use = wire->use;
lib->attachment = wire->attachment;
Xfree(buf);
ptr += sizeof(xXIDeviceInfo);
lib->name = Xcalloc(wire->name_len + 1, 1);
strncpy(lib->name, ptr, wire->name_len);
ptr += ((wire->name_len + 3)/4) * 4;
sz = size_classes((xXIAnyInfo*)ptr, nclasses);
lib->classes = Xmalloc(sz);
ptr += copy_classes(lib, (xXIAnyInfo*)ptr, &nclasses);
/* We skip over unused classes */
lib->num_classes = nclasses;
}
Commit Message:
CWE ID: CWE-284 | XIQueryDevice(Display *dpy, int deviceid, int *ndevices_return)
{
XIDeviceInfo *info = NULL;
xXIQueryDeviceReq *req;
xXIQueryDeviceReq *req;
xXIQueryDeviceReply reply;
char *ptr;
char *end;
int i;
char *buf;
LockDisplay(dpy);
if (_XiCheckExtInit(dpy, XInput_2_0, extinfo) == -1)
goto error_unlocked;
GetReq(XIQueryDevice, req);
req->reqType = extinfo->codes->major_opcode;
req->ReqType = X_XIQueryDevice;
req->deviceid = deviceid;
if (!_XReply(dpy, (xReply*) &reply, 0, xFalse))
goto error;
if (!_XReply(dpy, (xReply*) &reply, 0, xFalse))
goto error;
if (reply.length < INT_MAX / 4)
{
*ndevices_return = reply.num_devices;
info = Xmalloc((reply.num_devices + 1) * sizeof(XIDeviceInfo));
}
else
{
*ndevices_return = 0;
info = NULL;
}
if (!info)
goto error;
buf = Xmalloc(reply.length * 4);
_XRead(dpy, buf, reply.length * 4);
ptr = buf;
end = buf + reply.length * 4;
/* info is a null-terminated array */
info[reply.num_devices].name = NULL;
nclasses = wire->num_classes;
ptr += sizeof(xXIDeviceInfo);
lib->name = Xcalloc(wire->name_len + 1, 1);
XIDeviceInfo *lib = &info[i];
xXIDeviceInfo *wire = (xXIDeviceInfo*)ptr;
if (ptr + sizeof(xXIDeviceInfo) > end)
goto error_loop;
lib->deviceid = wire->deviceid;
lib->use = wire->use;
lib->attachment = wire->attachment;
Xfree(buf);
ptr += sizeof(xXIDeviceInfo);
if (ptr + wire->name_len > end)
goto error_loop;
lib->name = Xcalloc(wire->name_len + 1, 1);
if (lib->name == NULL)
goto error_loop;
strncpy(lib->name, ptr, wire->name_len);
lib->name[wire->name_len] = '\0';
ptr += ((wire->name_len + 3)/4) * 4;
sz = size_classes((xXIAnyInfo*)ptr, nclasses);
lib->classes = Xmalloc(sz);
if (lib->classes == NULL)
{
Xfree(lib->name);
goto error_loop;
}
ptr += copy_classes(lib, (xXIAnyInfo*)ptr, &nclasses);
/* We skip over unused classes */
lib->num_classes = nclasses;
}
| 164,920 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ScriptPromise VRDisplay::requestPresent(ScriptState* script_state,
const HeapVector<VRLayer>& layers) {
ExecutionContext* execution_context = ExecutionContext::From(script_state);
UseCounter::Count(execution_context, UseCounter::kVRRequestPresent);
if (!execution_context->IsSecureContext()) {
UseCounter::Count(execution_context,
UseCounter::kVRRequestPresentInsecureOrigin);
}
ReportPresentationResult(PresentationResult::kRequested);
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
if (!capabilities_->canPresent()) {
DOMException* exception =
DOMException::Create(kInvalidStateError, "VRDisplay cannot present.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kVRDisplayCannotPresent);
return promise;
}
bool first_present = !is_presenting_;
if (first_present && !UserGestureIndicator::UtilizeUserGesture() &&
!in_display_activate_) {
DOMException* exception = DOMException::Create(
kInvalidStateError, "API can only be initiated by a user gesture.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kNotInitiatedByUserGesture);
return promise;
}
if (layers.size() == 0 || layers.size() > capabilities_->maxLayers()) {
ForceExitPresent();
DOMException* exception =
DOMException::Create(kInvalidStateError, "Invalid number of layers.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kInvalidNumberOfLayers);
return promise;
}
if (layers[0].source().isNull()) {
ForceExitPresent();
DOMException* exception =
DOMException::Create(kInvalidStateError, "Invalid layer source.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kInvalidLayerSource);
return promise;
}
layer_ = layers[0];
CanvasRenderingContext* rendering_context;
if (layer_.source().isHTMLCanvasElement()) {
rendering_context =
layer_.source().getAsHTMLCanvasElement()->RenderingContext();
} else {
DCHECK(layer_.source().isOffscreenCanvas());
rendering_context =
layer_.source().getAsOffscreenCanvas()->RenderingContext();
}
if (!rendering_context || !rendering_context->Is3d()) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError, "Layer source must have a WebGLRenderingContext");
resolver->Reject(exception);
ReportPresentationResult(
PresentationResult::kLayerSourceMissingWebGLContext);
return promise;
}
rendering_context_ = ToWebGLRenderingContextBase(rendering_context);
context_gl_ = rendering_context_->ContextGL();
if ((layer_.leftBounds().size() != 0 && layer_.leftBounds().size() != 4) ||
(layer_.rightBounds().size() != 0 && layer_.rightBounds().size() != 4)) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError,
"Layer bounds must either be an empty array or have 4 values");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kInvalidLayerBounds);
return promise;
}
if (!pending_present_resolvers_.IsEmpty()) {
pending_present_resolvers_.push_back(resolver);
} else if (first_present) {
bool secure_context =
ExecutionContext::From(script_state)->IsSecureContext();
if (!display_) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError, "The service is no longer active.");
resolver->Reject(exception);
return promise;
}
pending_present_resolvers_.push_back(resolver);
submit_frame_client_binding_.Close();
display_->RequestPresent(
secure_context,
submit_frame_client_binding_.CreateInterfacePtrAndBind(),
ConvertToBaseCallback(
WTF::Bind(&VRDisplay::OnPresentComplete, WrapPersistent(this))));
} else {
UpdateLayerBounds();
resolver->Resolve();
ReportPresentationResult(PresentationResult::kSuccessAlreadyPresenting);
}
return promise;
}
Commit Message: WebVR: fix initial vsync
Applications sometimes use window.rAF while not presenting, then switch to
vrDisplay.rAF after presentation starts. Depending on the animation loop's
timing, this can cause a race condition where presentation has been started
but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync
being processed after presentation starts so that a queued window.rAF
can run and schedule a vrDisplay.rAF.
BUG=711789
Review-Url: https://codereview.chromium.org/2848483003
Cr-Commit-Position: refs/heads/master@{#468167}
CWE ID: | ScriptPromise VRDisplay::requestPresent(ScriptState* script_state,
const HeapVector<VRLayer>& layers) {
DVLOG(1) << __FUNCTION__;
ExecutionContext* execution_context = ExecutionContext::From(script_state);
UseCounter::Count(execution_context, UseCounter::kVRRequestPresent);
if (!execution_context->IsSecureContext()) {
UseCounter::Count(execution_context,
UseCounter::kVRRequestPresentInsecureOrigin);
}
ReportPresentationResult(PresentationResult::kRequested);
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
if (!capabilities_->canPresent()) {
DOMException* exception =
DOMException::Create(kInvalidStateError, "VRDisplay cannot present.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kVRDisplayCannotPresent);
return promise;
}
bool first_present = !is_presenting_;
if (first_present && !UserGestureIndicator::UtilizeUserGesture() &&
!in_display_activate_) {
DOMException* exception = DOMException::Create(
kInvalidStateError, "API can only be initiated by a user gesture.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kNotInitiatedByUserGesture);
return promise;
}
if (layers.size() == 0 || layers.size() > capabilities_->maxLayers()) {
ForceExitPresent();
DOMException* exception =
DOMException::Create(kInvalidStateError, "Invalid number of layers.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kInvalidNumberOfLayers);
return promise;
}
if (layers[0].source().isNull()) {
ForceExitPresent();
DOMException* exception =
DOMException::Create(kInvalidStateError, "Invalid layer source.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kInvalidLayerSource);
return promise;
}
layer_ = layers[0];
CanvasRenderingContext* rendering_context;
if (layer_.source().isHTMLCanvasElement()) {
rendering_context =
layer_.source().getAsHTMLCanvasElement()->RenderingContext();
} else {
DCHECK(layer_.source().isOffscreenCanvas());
rendering_context =
layer_.source().getAsOffscreenCanvas()->RenderingContext();
}
if (!rendering_context || !rendering_context->Is3d()) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError, "Layer source must have a WebGLRenderingContext");
resolver->Reject(exception);
ReportPresentationResult(
PresentationResult::kLayerSourceMissingWebGLContext);
return promise;
}
rendering_context_ = ToWebGLRenderingContextBase(rendering_context);
context_gl_ = rendering_context_->ContextGL();
if ((layer_.leftBounds().size() != 0 && layer_.leftBounds().size() != 4) ||
(layer_.rightBounds().size() != 0 && layer_.rightBounds().size() != 4)) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError,
"Layer bounds must either be an empty array or have 4 values");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kInvalidLayerBounds);
return promise;
}
if (!pending_present_resolvers_.IsEmpty()) {
pending_present_resolvers_.push_back(resolver);
} else if (first_present) {
bool secure_context =
ExecutionContext::From(script_state)->IsSecureContext();
if (!display_) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError, "The service is no longer active.");
resolver->Reject(exception);
return promise;
}
pending_present_resolvers_.push_back(resolver);
submit_frame_client_binding_.Close();
display_->RequestPresent(
secure_context,
submit_frame_client_binding_.CreateInterfacePtrAndBind(),
ConvertToBaseCallback(
WTF::Bind(&VRDisplay::OnPresentComplete, WrapPersistent(this))));
} else {
UpdateLayerBounds();
resolver->Resolve();
ReportPresentationResult(PresentationResult::kSuccessAlreadyPresenting);
}
return promise;
}
| 172,003 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 OomInterventionImpl::Check(TimerBase*) {
DCHECK(host_);
OomInterventionMetrics current_memory = GetCurrentMemoryMetrics();
bool oom_detected = false;
oom_detected |= detection_args_->blink_workload_threshold > 0 &&
current_memory.current_blink_usage_kb * 1024 >
detection_args_->blink_workload_threshold;
oom_detected |= detection_args_->private_footprint_threshold > 0 &&
current_memory.current_private_footprint_kb * 1024 >
detection_args_->private_footprint_threshold;
oom_detected |=
detection_args_->swap_threshold > 0 &&
current_memory.current_swap_kb * 1024 > detection_args_->swap_threshold;
oom_detected |= detection_args_->virtual_memory_thresold > 0 &&
current_memory.current_vm_size_kb * 1024 >
detection_args_->virtual_memory_thresold;
ReportMemoryStats(current_memory);
if (oom_detected) {
if (navigate_ads_enabled_) {
for (const auto& page : Page::OrdinaryPages()) {
if (page->MainFrame()->IsLocalFrame()) {
ToLocalFrame(page->MainFrame())
->GetDocument()
->NavigateLocalAdsFrames();
}
}
}
if (renderer_pause_enabled_) {
pauser_.reset(new ScopedPagePauser);
}
host_->OnHighMemoryUsage();
timer_.Stop();
V8GCForContextDispose::Instance().SetForcePageNavigationGC();
}
}
Commit Message: OomIntervention opt-out should work properly with 'show original'
OomIntervention should not be re-triggered on the same page if the user declines the intervention once.
This CL fixes the bug.
Bug: 889131, 887119
Change-Id: Idb9eebb2bb9f79756b63f0e010fe018ba5c490e8
Reviewed-on: https://chromium-review.googlesource.com/1245019
Commit-Queue: Yuzu Saijo <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Cr-Commit-Position: refs/heads/master@{#594574}
CWE ID: CWE-119 | void OomInterventionImpl::Check(TimerBase*) {
DCHECK(host_);
DCHECK(renderer_pause_enabled_ || navigate_ads_enabled_);
OomInterventionMetrics current_memory = GetCurrentMemoryMetrics();
bool oom_detected = false;
oom_detected |= detection_args_->blink_workload_threshold > 0 &&
current_memory.current_blink_usage_kb * 1024 >
detection_args_->blink_workload_threshold;
oom_detected |= detection_args_->private_footprint_threshold > 0 &&
current_memory.current_private_footprint_kb * 1024 >
detection_args_->private_footprint_threshold;
oom_detected |=
detection_args_->swap_threshold > 0 &&
current_memory.current_swap_kb * 1024 > detection_args_->swap_threshold;
oom_detected |= detection_args_->virtual_memory_thresold > 0 &&
current_memory.current_vm_size_kb * 1024 >
detection_args_->virtual_memory_thresold;
ReportMemoryStats(current_memory);
if (oom_detected) {
if (navigate_ads_enabled_) {
for (const auto& page : Page::OrdinaryPages()) {
if (page->MainFrame()->IsLocalFrame()) {
ToLocalFrame(page->MainFrame())
->GetDocument()
->NavigateLocalAdsFrames();
}
}
}
if (renderer_pause_enabled_) {
pauser_.reset(new ScopedPagePauser);
}
host_->OnHighMemoryUsage();
timer_.Stop();
V8GCForContextDispose::Instance().SetForcePageNavigationGC();
}
}
| 172,115 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */
{
if (intern->u.file.current_line) {
return intern->u.file.current_line_len == 0;
} else if (intern->u.file.current_zval) {
switch(Z_TYPE_P(intern->u.file.current_zval)) {
case IS_STRING:
return Z_STRLEN_P(intern->u.file.current_zval) == 0;
case IS_ARRAY:
if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV)
&& zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) {
zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData;
return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0;
}
return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0;
case IS_NULL:
return 1;
default:
return 0;
}
} else {
return 1;
}
}
/* }}} */
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | static int spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */
{
if (intern->u.file.current_line) {
return intern->u.file.current_line_len == 0;
} else if (intern->u.file.current_zval) {
switch(Z_TYPE_P(intern->u.file.current_zval)) {
case IS_STRING:
return Z_STRLEN_P(intern->u.file.current_zval) == 0;
case IS_ARRAY:
if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV)
&& zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) {
zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData;
return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0;
}
return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0;
case IS_NULL:
return 1;
default:
return 0;
}
} else {
return 1;
}
}
/* }}} */
| 167,074 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_get_mmx_rowbytes_threshold (png_structp png_ptr)
{
/* Obsolete, to be removed from libpng-1.4.0 */
return (png_ptr? 0L: 0L);
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_get_mmx_rowbytes_threshold (png_structp png_ptr)
{
/* Obsolete, to be removed from libpng-1.4.0 */
PNG_UNUSED(png_ptr)
return 0L;
}
| 172,167 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 ovl_setattr(struct dentry *dentry, struct iattr *attr)
{
int err;
struct dentry *upperdentry;
err = ovl_want_write(dentry);
if (err)
goto out;
upperdentry = ovl_dentry_upper(dentry);
if (upperdentry) {
mutex_lock(&upperdentry->d_inode->i_mutex);
err = notify_change(upperdentry, attr, NULL);
mutex_unlock(&upperdentry->d_inode->i_mutex);
} else {
err = ovl_copy_up_last(dentry, attr, false);
}
ovl_drop_write(dentry);
out:
return err;
}
Commit Message: ovl: fix permission checking for setattr
[Al Viro] The bug is in being too enthusiastic about optimizing ->setattr()
away - instead of "copy verbatim with metadata" + "chmod/chown/utimes"
(with the former being always safe and the latter failing in case of
insufficient permissions) it tries to combine these two. Note that copyup
itself will have to do ->setattr() anyway; _that_ is where the elevated
capabilities are right. Having these two ->setattr() (one to set verbatim
copy of metadata, another to do what overlayfs ->setattr() had been asked
to do in the first place) combined is where it breaks.
Signed-off-by: Miklos Szeredi <[email protected]>
Cc: <[email protected]>
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-264 | int ovl_setattr(struct dentry *dentry, struct iattr *attr)
{
int err;
struct dentry *upperdentry;
err = ovl_want_write(dentry);
if (err)
goto out;
err = ovl_copy_up(dentry);
if (!err) {
upperdentry = ovl_dentry_upper(dentry);
mutex_lock(&upperdentry->d_inode->i_mutex);
err = notify_change(upperdentry, attr, NULL);
mutex_unlock(&upperdentry->d_inode->i_mutex);
}
ovl_drop_write(dentry);
out:
return err;
}
| 166,559 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: store_pool_delete(png_store *ps, store_pool *pool)
{
if (pool->list != NULL)
{
fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test,
pool == &ps->read_memory_pool ? "read" : "write",
pool == &ps->read_memory_pool ? (ps->current != NULL ?
ps->current->name : "unknown file") : ps->wname);
++ps->nerrors;
do
{
store_memory *next = pool->list;
pool->list = next->next;
next->next = NULL;
fprintf(stderr, "\t%lu bytes @ %p\n",
(unsigned long)next->size, (PNG_CONST void*)(next+1));
/* The NULL means this will always return, even if the memory is
* corrupted.
*/
store_memory_free(NULL, pool, next);
}
while (pool->list != NULL);
}
/* And reset the other fields too for the next time. */
if (pool->max > pool->max_max) pool->max_max = pool->max;
pool->max = 0;
if (pool->current != 0) /* unexpected internal error */
fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n",
ps->test, pool == &ps->read_memory_pool ? "read" : "write",
pool == &ps->read_memory_pool ? (ps->current != NULL ?
ps->current->name : "unknown file") : ps->wname);
pool->current = 0;
if (pool->limit > pool->max_limit)
pool->max_limit = pool->limit;
pool->limit = 0;
if (pool->total > pool->max_total)
pool->max_total = pool->total;
pool->total = 0;
/* Get a new mark too. */
store_pool_mark(pool->mark);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | store_pool_delete(png_store *ps, store_pool *pool)
{
if (pool->list != NULL)
{
fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test,
pool == &ps->read_memory_pool ? "read" : "write",
pool == &ps->read_memory_pool ? (ps->current != NULL ?
ps->current->name : "unknown file") : ps->wname);
++ps->nerrors;
do
{
store_memory *next = pool->list;
pool->list = next->next;
next->next = NULL;
fprintf(stderr, "\t%lu bytes @ %p\n",
(unsigned long)next->size, (const void*)(next+1));
/* The NULL means this will always return, even if the memory is
* corrupted.
*/
store_memory_free(NULL, pool, next);
}
while (pool->list != NULL);
}
/* And reset the other fields too for the next time. */
if (pool->max > pool->max_max) pool->max_max = pool->max;
pool->max = 0;
if (pool->current != 0) /* unexpected internal error */
fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n",
ps->test, pool == &ps->read_memory_pool ? "read" : "write",
pool == &ps->read_memory_pool ? (ps->current != NULL ?
ps->current->name : "unknown file") : ps->wname);
pool->current = 0;
if (pool->limit > pool->max_limit)
pool->max_limit = pool->limit;
pool->limit = 0;
if (pool->total > pool->max_total)
pool->max_total = pool->total;
pool->total = 0;
/* Get a new mark too. */
store_pool_mark(pool->mark);
}
| 173,707 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 DataReductionProxySettings::IsDataReductionProxyEnabled() const {
if (base::FeatureList::IsEnabled(network::features::kNetworkService) &&
!params::IsEnabledWithNetworkService()) {
return false;
}
return IsDataSaverEnabledByUser();
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Commit-Queue: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119 | bool DataReductionProxySettings::IsDataReductionProxyEnabled() const {
if (base::FeatureList::IsEnabled(network::features::kNetworkService) &&
!params::IsEnabledWithNetworkService()) {
return false;
}
return IsDataSaverEnabledByUser(GetOriginalProfilePrefs());
}
| 172,554 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32 bps = tif->tif_dir.td_bitspersample / 8;
tmsize_t wc = cc / bps;
tmsize_t count = cc;
uint8 *cp = (uint8 *) cp0;
uint8 *tmp = (uint8 *)_TIFFmalloc(cc);
if(cc%(bps*stride)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "fpAcc",
"%s", "cc%(bps*stride))!=0");
return 0;
}
if (!tmp)
return 0;
while (count > stride) {
REPEAT4(stride, cp[stride] =
(unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++)
count -= stride;
}
_TIFFmemcpy(tmp, cp0, cc);
cp = (uint8 *) cp0;
for (count = 0; count < wc; count++) {
uint32 byte;
for (byte = 0; byte < bps; byte++) {
#if WORDS_BIGENDIAN
cp[bps * count + byte] = tmp[byte * wc + count];
#else
cp[bps * count + byte] =
tmp[(bps - byte - 1) * wc + count];
#endif
}
}
_TIFFfree(tmp);
return 1;
}
Commit Message: * libtiff/tif_predic.c: fix memory leaks in error code paths added in
previous commit (fix for MSVR 35105)
CWE ID: CWE-119 | fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32 bps = tif->tif_dir.td_bitspersample / 8;
tmsize_t wc = cc / bps;
tmsize_t count = cc;
uint8 *cp = (uint8 *) cp0;
uint8 *tmp;
if(cc%(bps*stride)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "fpAcc",
"%s", "cc%(bps*stride))!=0");
return 0;
}
tmp = (uint8 *)_TIFFmalloc(cc);
if (!tmp)
return 0;
while (count > stride) {
REPEAT4(stride, cp[stride] =
(unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++)
count -= stride;
}
_TIFFmemcpy(tmp, cp0, cc);
cp = (uint8 *) cp0;
for (count = 0; count < wc; count++) {
uint32 byte;
for (byte = 0; byte < bps; byte++) {
#if WORDS_BIGENDIAN
cp[bps * count + byte] = tmp[byte * wc + count];
#else
cp[bps * count + byte] =
tmp[(bps - byte - 1) * wc + count];
#endif
}
}
_TIFFfree(tmp);
return 1;
}
| 169,938 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 OMXNodeInstance::useBuffer(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
if (params == NULL || buffer == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size()) {
return BAD_VALUE;
}
BufferMeta *buffer_meta = new BufferMeta(params, portIndex);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_UseBuffer(
mHandle, &header, portIndex, buffer_meta,
allottedSize, static_cast<OMX_U8 *>(params->pointer()));
if (err != OMX_ErrorNone) {
CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER(
portIndex, (size_t)allottedSize, params->pointer()));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT(
*buffer, portIndex, "%u(%zu)@%p", allottedSize, params->size(), params->pointer()));
return OK;
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200 | status_t OMXNodeInstance::useBuffer(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
if (params == NULL || buffer == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size() || portIndex >= NELEM(mNumPortBuffers)) {
return BAD_VALUE;
}
// metadata buffers are not connected cross process
// use a backup buffer instead of the actual buffer
BufferMeta *buffer_meta;
bool useBackup = mMetadataType[portIndex] != kMetadataBufferTypeInvalid;
OMX_U8 *data = static_cast<OMX_U8 *>(params->pointer());
// allocate backup buffer
if (useBackup) {
data = new (std::nothrow) OMX_U8[allottedSize];
if (data == NULL) {
return NO_MEMORY;
}
memset(data, 0, allottedSize);
// if we are not connecting the buffers, the sizes must match
if (allottedSize != params->size()) {
CLOG_ERROR(useBuffer, BAD_VALUE, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, data));
delete[] data;
return BAD_VALUE;
}
buffer_meta = new BufferMeta(
params, portIndex, false /* copyToOmx */, false /* copyFromOmx */, data);
} else {
buffer_meta = new BufferMeta(
params, portIndex, false /* copyFromOmx */, false /* copyToOmx */, NULL);
}
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_UseBuffer(
mHandle, &header, portIndex, buffer_meta,
allottedSize, data);
if (err != OMX_ErrorNone) {
CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER(
portIndex, (size_t)allottedSize, data));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT(
*buffer, portIndex, "%u(%zu)@%p", allottedSize, params->size(), params->pointer()));
return OK;
}
| 174,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: void InspectorPageAgent::clearDeviceOrientationOverride(ErrorString* error)
{
setDeviceOrientationOverride(error, 0, 0, 0);
}
Commit Message: DevTools: remove references to modules/device_orientation from core
BUG=340221
Review URL: https://codereview.chromium.org/150913003
git-svn-id: svn://svn.chromium.org/blink/trunk@166493 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void InspectorPageAgent::clearDeviceOrientationOverride(ErrorString* error)
| 171,402 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 FrameLoader::StopAllLoaders() {
if (frame_->GetDocument()->PageDismissalEventBeingDispatched() !=
Document::kNoDismissal)
return;
if (in_stop_all_loaders_)
return;
in_stop_all_loaders_ = true;
for (Frame* child = frame_->Tree().FirstChild(); child;
child = child->Tree().NextSibling()) {
if (child->IsLocalFrame())
ToLocalFrame(child)->Loader().StopAllLoaders();
}
frame_->GetDocument()->CancelParsing();
if (document_loader_)
document_loader_->Fetcher()->StopFetching();
if (!protect_provisional_loader_)
DetachDocumentLoader(provisional_document_loader_);
frame_->GetNavigationScheduler().Cancel();
if (document_loader_ && !document_loader_->SentDidFinishLoad()) {
document_loader_->LoadFailed(
ResourceError::CancelledError(document_loader_->Url()));
}
in_stop_all_loaders_ = false;
TakeObjectSnapshot();
}
Commit Message: Fix detach with open()ed document leaving parent loading indefinitely
Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6
Bug: 803416
Test: fast/loader/document-open-iframe-then-detach.html
Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6
Reviewed-on: https://chromium-review.googlesource.com/887298
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Nate Chapin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532967}
CWE ID: CWE-362 | void FrameLoader::StopAllLoaders() {
if (frame_->GetDocument()->PageDismissalEventBeingDispatched() !=
Document::kNoDismissal)
return;
if (in_stop_all_loaders_)
return;
AutoReset<bool> in_stop_all_loaders(&in_stop_all_loaders_, true);
for (Frame* child = frame_->Tree().FirstChild(); child;
child = child->Tree().NextSibling()) {
if (child->IsLocalFrame())
ToLocalFrame(child)->Loader().StopAllLoaders();
}
frame_->GetDocument()->CancelParsing();
if (document_loader_)
document_loader_->StopLoading();
if (!protect_provisional_loader_)
DetachDocumentLoader(provisional_document_loader_);
frame_->GetNavigationScheduler().Cancel();
DidFinishNavigation();
TakeObjectSnapshot();
}
| 171,852 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%') return;
switch(ctxt->instate) {
case XML_PARSER_CDATA_SECTION:
return;
case XML_PARSER_COMMENT:
return;
case XML_PARSER_START_TAG:
return;
case XML_PARSER_END_TAG:
return;
case XML_PARSER_EOF:
xmlFatalErr(ctxt, XML_ERR_PEREF_AT_EOF, NULL);
return;
case XML_PARSER_PROLOG:
case XML_PARSER_START:
case XML_PARSER_MISC:
xmlFatalErr(ctxt, XML_ERR_PEREF_IN_PROLOG, NULL);
return;
case XML_PARSER_ENTITY_DECL:
case XML_PARSER_CONTENT:
case XML_PARSER_ATTRIBUTE_VALUE:
case XML_PARSER_PI:
case XML_PARSER_SYSTEM_LITERAL:
case XML_PARSER_PUBLIC_LITERAL:
/* we just ignore it there */
return;
case XML_PARSER_EPILOG:
xmlFatalErr(ctxt, XML_ERR_PEREF_IN_EPILOG, NULL);
return;
case XML_PARSER_ENTITY_VALUE:
/*
* NOTE: in the case of entity values, we don't do the
* substitution here since we need the literal
* entity value to be able to save the internal
* subset of the document.
* This will be handled by xmlStringDecodeEntities
*/
return;
case XML_PARSER_DTD:
/*
* [WFC: Well-Formedness Constraint: PEs in Internal Subset]
* In the internal DTD subset, parameter-entity references
* can occur only where markup declarations can occur, not
* within markup declarations.
* In that case this is handled in xmlParseMarkupDecl
*/
if ((ctxt->external == 0) && (ctxt->inputNr == 1))
return;
if (IS_BLANK_CH(NXT(1)) || NXT(1) == 0)
return;
break;
case XML_PARSER_IGNORE:
return;
}
NEXT;
name = xmlParseName(ctxt);
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"PEReference: %s\n", name);
if (name == NULL) {
xmlFatalErr(ctxt, XML_ERR_PEREF_NO_NAME, NULL);
} else {
if (RAW == ';') {
NEXT;
if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n", name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->validate) && (ctxt->vctxt.error != NULL)) {
xmlValidityError(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
} else
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
} else if (ctxt->input->free != deallocblankswrapper) {
input = xmlNewBlanksWrapperInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
} else {
if ((entity->etype == XML_INTERNAL_PARAMETER_ENTITY) ||
(entity->etype == XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlChar start[4];
xmlCharEncoding enc;
/*
* handle the extra spaces added before and after
* c.f. http://www.w3.org/TR/REC-xml#as-PE
* this is done independently.
*/
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
* Note that, since we may have some non-UTF8
* encoding (like UTF16, bug 135229), the 'length'
* is not known, but we can calculate based upon
* the amount of data in the buffer.
*/
GROW
if ((ctxt->input->end - ctxt->input->cur)>=4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
(CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l' )) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
}
} else {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
"PEReference: %s is not a parameter entity\n",
name);
}
}
} else {
xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL);
}
}
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%') return;
switch(ctxt->instate) {
case XML_PARSER_CDATA_SECTION:
return;
case XML_PARSER_COMMENT:
return;
case XML_PARSER_START_TAG:
return;
case XML_PARSER_END_TAG:
return;
case XML_PARSER_EOF:
xmlFatalErr(ctxt, XML_ERR_PEREF_AT_EOF, NULL);
return;
case XML_PARSER_PROLOG:
case XML_PARSER_START:
case XML_PARSER_MISC:
xmlFatalErr(ctxt, XML_ERR_PEREF_IN_PROLOG, NULL);
return;
case XML_PARSER_ENTITY_DECL:
case XML_PARSER_CONTENT:
case XML_PARSER_ATTRIBUTE_VALUE:
case XML_PARSER_PI:
case XML_PARSER_SYSTEM_LITERAL:
case XML_PARSER_PUBLIC_LITERAL:
/* we just ignore it there */
return;
case XML_PARSER_EPILOG:
xmlFatalErr(ctxt, XML_ERR_PEREF_IN_EPILOG, NULL);
return;
case XML_PARSER_ENTITY_VALUE:
/*
* NOTE: in the case of entity values, we don't do the
* substitution here since we need the literal
* entity value to be able to save the internal
* subset of the document.
* This will be handled by xmlStringDecodeEntities
*/
return;
case XML_PARSER_DTD:
/*
* [WFC: Well-Formedness Constraint: PEs in Internal Subset]
* In the internal DTD subset, parameter-entity references
* can occur only where markup declarations can occur, not
* within markup declarations.
* In that case this is handled in xmlParseMarkupDecl
*/
if ((ctxt->external == 0) && (ctxt->inputNr == 1))
return;
if (IS_BLANK_CH(NXT(1)) || NXT(1) == 0)
return;
break;
case XML_PARSER_IGNORE:
return;
}
NEXT;
name = xmlParseName(ctxt);
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"PEReference: %s\n", name);
if (name == NULL) {
xmlFatalErr(ctxt, XML_ERR_PEREF_NO_NAME, NULL);
} else {
if (RAW == ';') {
NEXT;
if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (ctxt->instate == XML_PARSER_EOF)
return;
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n", name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->validate) && (ctxt->vctxt.error != NULL)) {
xmlValidityError(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
} else
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
} else if (ctxt->input->free != deallocblankswrapper) {
input = xmlNewBlanksWrapperInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
} else {
if ((entity->etype == XML_INTERNAL_PARAMETER_ENTITY) ||
(entity->etype == XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlChar start[4];
xmlCharEncoding enc;
/*
* handle the extra spaces added before and after
* c.f. http://www.w3.org/TR/REC-xml#as-PE
* this is done independently.
*/
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
* Note that, since we may have some non-UTF8
* encoding (like UTF16, bug 135229), the 'length'
* is not known, but we can calculate based upon
* the amount of data in the buffer.
*/
GROW
if (ctxt->instate == XML_PARSER_EOF)
return;
if ((ctxt->input->end - ctxt->input->cur)>=4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
(CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l' )) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
}
} else {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
"PEReference: %s is not a parameter entity\n",
name);
}
}
} else {
xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL);
}
}
}
| 171,308 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 blk_rq_map_user_iov(struct request_queue *q, struct request *rq,
struct rq_map_data *map_data,
const struct iov_iter *iter, gfp_t gfp_mask)
{
bool copy = false;
unsigned long align = q->dma_pad_mask | queue_dma_alignment(q);
struct bio *bio = NULL;
struct iov_iter i;
int ret;
if (map_data)
copy = true;
else if (iov_iter_alignment(iter) & align)
copy = true;
else if (queue_virt_boundary(q))
copy = queue_virt_boundary(q) & iov_iter_gap_alignment(iter);
i = *iter;
do {
ret =__blk_rq_map_user_iov(rq, map_data, &i, gfp_mask, copy);
if (ret)
goto unmap_rq;
if (!bio)
bio = rq->bio;
} while (iov_iter_count(&i));
if (!bio_flagged(bio, BIO_USER_MAPPED))
rq->cmd_flags |= REQ_COPY_USER;
return 0;
unmap_rq:
__blk_rq_unmap_user(bio);
rq->bio = NULL;
return -EINVAL;
}
Commit Message: Don't feed anything but regular iovec's to blk_rq_map_user_iov
In theory we could map other things, but there's a reason that function
is called "user_iov". Using anything else (like splice can do) just
confuses it.
Reported-and-tested-by: Johannes Thumshirn <[email protected]>
Cc: Al Viro <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-416 | int blk_rq_map_user_iov(struct request_queue *q, struct request *rq,
struct rq_map_data *map_data,
const struct iov_iter *iter, gfp_t gfp_mask)
{
bool copy = false;
unsigned long align = q->dma_pad_mask | queue_dma_alignment(q);
struct bio *bio = NULL;
struct iov_iter i;
int ret;
if (!iter_is_iovec(iter))
goto fail;
if (map_data)
copy = true;
else if (iov_iter_alignment(iter) & align)
copy = true;
else if (queue_virt_boundary(q))
copy = queue_virt_boundary(q) & iov_iter_gap_alignment(iter);
i = *iter;
do {
ret =__blk_rq_map_user_iov(rq, map_data, &i, gfp_mask, copy);
if (ret)
goto unmap_rq;
if (!bio)
bio = rq->bio;
} while (iov_iter_count(&i));
if (!bio_flagged(bio, BIO_USER_MAPPED))
rq->cmd_flags |= REQ_COPY_USER;
return 0;
unmap_rq:
__blk_rq_unmap_user(bio);
fail:
rq->bio = NULL;
return -EINVAL;
}
| 166,858 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: BGD_DECLARE(void) gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)
{
int lastBorder;
/* Seek left */
int leftLimit, rightLimit;
int i;
int restoreAlphaBleding;
if (border < 0) {
/* Refuse to fill to a non-solid border */
return;
}
leftLimit = (-1);
restoreAlphaBleding = im->alphaBlendingFlag;
im->alphaBlendingFlag = 0;
if (x >= im->sx) {
x = im->sx - 1;
} else if (x < 0) {
x = 0;
}
if (y >= im->sy) {
y = im->sy - 1;
} else if (y < 0) {
y = 0;
}
for (i = x; (i >= 0); i--) {
if (gdImageGetPixel (im, i, y) == border) {
break;
}
gdImageSetPixel (im, i, y, color);
leftLimit = i;
}
if (leftLimit == (-1)) {
im->alphaBlendingFlag = restoreAlphaBleding;
return;
}
/* Seek right */
rightLimit = x;
for (i = (x + 1); (i < im->sx); i++) {
if (gdImageGetPixel (im, i, y) == border) {
break;
}
gdImageSetPixel (im, i, y, color);
rightLimit = i;
}
/* Look at lines above and below and start paints */
/* Above */
if (y > 0) {
lastBorder = 1;
for (i = leftLimit; (i <= rightLimit); i++) {
int c;
c = gdImageGetPixel (im, i, y - 1);
if (lastBorder) {
if ((c != border) && (c != color)) {
gdImageFillToBorder (im, i, y - 1, border, color);
lastBorder = 0;
}
} else if ((c == border) || (c == color)) {
lastBorder = 1;
}
}
}
/* Below */
if (y < ((im->sy) - 1)) {
lastBorder = 1;
for (i = leftLimit; (i <= rightLimit); i++) {
int c = gdImageGetPixel (im, i, y + 1);
if (lastBorder) {
if ((c != border) && (c != color)) {
gdImageFillToBorder (im, i, y + 1, border, color);
lastBorder = 0;
}
} else if ((c == border) || (c == color)) {
lastBorder = 1;
}
}
}
im->alphaBlendingFlag = restoreAlphaBleding;
}
Commit Message: fix #215 gdImageFillToBorder stack-overflow when invalid color is used
CWE ID: CWE-119 | BGD_DECLARE(void) gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)
{
int lastBorder;
/* Seek left */
int leftLimit, rightLimit;
int i;
int restoreAlphaBleding;
if (border < 0 || color < 0) {
/* Refuse to fill to a non-solid border */
return;
}
if (!im->trueColor) {
if ((color > (im->colorsTotal - 1)) || (border > (im->colorsTotal - 1))) {
return;
}
}
leftLimit = (-1);
restoreAlphaBleding = im->alphaBlendingFlag;
im->alphaBlendingFlag = 0;
if (x >= im->sx) {
x = im->sx - 1;
} else if (x < 0) {
x = 0;
}
if (y >= im->sy) {
y = im->sy - 1;
} else if (y < 0) {
y = 0;
}
for (i = x; (i >= 0); i--) {
if (gdImageGetPixel (im, i, y) == border) {
break;
}
gdImageSetPixel (im, i, y, color);
leftLimit = i;
}
if (leftLimit == (-1)) {
im->alphaBlendingFlag = restoreAlphaBleding;
return;
}
/* Seek right */
rightLimit = x;
for (i = (x + 1); (i < im->sx); i++) {
if (gdImageGetPixel (im, i, y) == border) {
break;
}
gdImageSetPixel (im, i, y, color);
rightLimit = i;
}
/* Look at lines above and below and start paints */
/* Above */
if (y > 0) {
lastBorder = 1;
for (i = leftLimit; (i <= rightLimit); i++) {
int c;
c = gdImageGetPixel (im, i, y - 1);
if (lastBorder) {
if ((c != border) && (c != color)) {
gdImageFillToBorder (im, i, y - 1, border, color);
lastBorder = 0;
}
} else if ((c == border) || (c == color)) {
lastBorder = 1;
}
}
}
/* Below */
if (y < ((im->sy) - 1)) {
lastBorder = 1;
for (i = leftLimit; (i <= rightLimit); i++) {
int c = gdImageGetPixel (im, i, y + 1);
if (lastBorder) {
if ((c != border) && (c != color)) {
gdImageFillToBorder (im, i, y + 1, border, color);
lastBorder = 0;
}
} else if ((c == border) || (c == color)) {
lastBorder = 1;
}
}
}
im->alphaBlendingFlag = restoreAlphaBleding;
}
| 170,111 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: spnego_gss_get_mic(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
gss_qop_t qop_req,
const gss_buffer_t message_buffer,
gss_buffer_t message_token)
{
OM_uint32 ret;
ret = gss_get_mic(minor_status,
context_handle,
qop_req,
message_buffer,
message_token);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | spnego_gss_get_mic(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
gss_qop_t qop_req,
const gss_buffer_t message_buffer,
gss_buffer_t message_token)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle;
if (sc->ctx_handle == GSS_C_NO_CONTEXT)
return (GSS_S_NO_CONTEXT);
ret = gss_get_mic(minor_status,
sc->ctx_handle,
qop_req,
message_buffer,
message_token);
return (ret);
}
| 166,656 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WORD32 ixheaacd_qmf_hbe_data_reinit(ia_esbr_hbe_txposer_struct *ptr_hbe_txposer,
WORD16 *p_freq_band_tab[2],
WORD16 *p_num_sfb, WORD32 upsamp_4_flag) {
WORD32 synth_size, sfb, patch, stop_patch;
if (ptr_hbe_txposer != NULL) {
ptr_hbe_txposer->start_band = p_freq_band_tab[LOW][0];
ptr_hbe_txposer->end_band = p_freq_band_tab[LOW][p_num_sfb[LOW]];
ptr_hbe_txposer->synth_size =
4 * ((ptr_hbe_txposer->start_band + 4) / 8 + 1);
ptr_hbe_txposer->k_start =
ixheaacd_start_subband2kL_tbl[ptr_hbe_txposer->start_band];
ptr_hbe_txposer->upsamp_4_flag = upsamp_4_flag;
if (upsamp_4_flag) {
if (ptr_hbe_txposer->k_start + ptr_hbe_txposer->synth_size > 16)
ptr_hbe_txposer->k_start = 16 - ptr_hbe_txposer->synth_size;
} else if (ptr_hbe_txposer->core_frame_length == 768) {
if (ptr_hbe_txposer->k_start + ptr_hbe_txposer->synth_size > 24)
ptr_hbe_txposer->k_start = 24 - ptr_hbe_txposer->synth_size;
}
memset(ptr_hbe_txposer->synth_buf, 0, 1280 * sizeof(FLOAT32));
synth_size = ptr_hbe_txposer->synth_size;
ptr_hbe_txposer->synth_buf_offset = 18 * synth_size;
switch (synth_size) {
case 4:
ptr_hbe_txposer->synth_cos_tab =
(FLOAT32 *)ixheaacd_synth_cos_table_kl_4;
ptr_hbe_txposer->analy_cos_sin_tab =
(FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_8;
ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p2;
ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p2;
break;
case 8:
ptr_hbe_txposer->synth_cos_tab =
(FLOAT32 *)ixheaacd_synth_cos_table_kl_8;
ptr_hbe_txposer->analy_cos_sin_tab =
(FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_16;
ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p2;
ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p2;
break;
case 12:
ptr_hbe_txposer->synth_cos_tab =
(FLOAT32 *)ixheaacd_synth_cos_table_kl_12;
ptr_hbe_txposer->analy_cos_sin_tab =
(FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_24;
ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p3;
ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p3;
break;
case 16:
ptr_hbe_txposer->synth_cos_tab =
(FLOAT32 *)ixheaacd_synth_cos_table_kl_16;
ptr_hbe_txposer->analy_cos_sin_tab =
(FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_32;
ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p2;
ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p2;
break;
case 20:
ptr_hbe_txposer->synth_cos_tab =
(FLOAT32 *)ixheaacd_synth_cos_table_kl_20;
ptr_hbe_txposer->analy_cos_sin_tab =
(FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_40;
break;
default:
ptr_hbe_txposer->synth_cos_tab =
(FLOAT32 *)ixheaacd_synth_cos_table_kl_4;
ptr_hbe_txposer->analy_cos_sin_tab =
(FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_8;
ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p2;
ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p2;
}
ptr_hbe_txposer->synth_wind_coeff = ixheaacd_map_prot_filter(synth_size);
memset(ptr_hbe_txposer->analy_buf, 0, 640 * sizeof(FLOAT32));
synth_size = 2 * ptr_hbe_txposer->synth_size;
ptr_hbe_txposer->analy_wind_coeff = ixheaacd_map_prot_filter(synth_size);
memset(ptr_hbe_txposer->x_over_qmf, 0, MAX_NUM_PATCHES * sizeof(WORD32));
sfb = 0;
if (upsamp_4_flag) {
stop_patch = MAX_NUM_PATCHES;
ptr_hbe_txposer->max_stretch = MAX_STRETCH;
} else {
stop_patch = MAX_STRETCH;
}
for (patch = 1; patch <= stop_patch; patch++) {
while (sfb <= p_num_sfb[LOW] &&
p_freq_band_tab[LOW][sfb] <= patch * ptr_hbe_txposer->start_band)
sfb++;
if (sfb <= p_num_sfb[LOW]) {
if ((patch * ptr_hbe_txposer->start_band -
p_freq_band_tab[LOW][sfb - 1]) <= 3) {
ptr_hbe_txposer->x_over_qmf[patch - 1] =
p_freq_band_tab[LOW][sfb - 1];
} else {
WORD32 sfb = 0;
while (sfb <= p_num_sfb[HIGH] &&
p_freq_band_tab[HIGH][sfb] <=
patch * ptr_hbe_txposer->start_band)
sfb++;
ptr_hbe_txposer->x_over_qmf[patch - 1] =
p_freq_band_tab[HIGH][sfb - 1];
}
} else {
ptr_hbe_txposer->x_over_qmf[patch - 1] = ptr_hbe_txposer->end_band;
ptr_hbe_txposer->max_stretch = min(patch, MAX_STRETCH);
break;
}
}
}
if (ptr_hbe_txposer->k_start < 0) {
return -1;
}
return 0;
}
Commit Message: Fix for stack corruption in esbr
Bug: 110769924
Test: poc from bug before/after
Change-Id: I99c6e89902064849ea1310c271064bdeccf7f20e
(cherry picked from commit 7e90d745c22695236437297cd8167a9312427a4a)
(cherry picked from commit 5464927f0c1fc721fa03d1c5be77b0b43dfffc50)
CWE ID: CWE-787 | WORD32 ixheaacd_qmf_hbe_data_reinit(ia_esbr_hbe_txposer_struct *ptr_hbe_txposer,
WORD16 *p_freq_band_tab[2],
WORD16 *p_num_sfb, WORD32 upsamp_4_flag) {
WORD32 synth_size, sfb, patch, stop_patch;
if (ptr_hbe_txposer != NULL) {
ptr_hbe_txposer->start_band = p_freq_band_tab[LOW][0];
ptr_hbe_txposer->end_band = p_freq_band_tab[LOW][p_num_sfb[LOW]];
ptr_hbe_txposer->synth_size =
4 * ((ptr_hbe_txposer->start_band + 4) / 8 + 1);
ptr_hbe_txposer->k_start =
ixheaacd_start_subband2kL_tbl[ptr_hbe_txposer->start_band];
ptr_hbe_txposer->upsamp_4_flag = upsamp_4_flag;
if (upsamp_4_flag) {
if (ptr_hbe_txposer->k_start + ptr_hbe_txposer->synth_size > 16)
ptr_hbe_txposer->k_start = 16 - ptr_hbe_txposer->synth_size;
} else if (ptr_hbe_txposer->core_frame_length == 768) {
if (ptr_hbe_txposer->k_start + ptr_hbe_txposer->synth_size > 24)
ptr_hbe_txposer->k_start = 24 - ptr_hbe_txposer->synth_size;
}
memset(ptr_hbe_txposer->synth_buf, 0, 1280 * sizeof(FLOAT32));
synth_size = ptr_hbe_txposer->synth_size;
ptr_hbe_txposer->synth_buf_offset = 18 * synth_size;
switch (synth_size) {
case 4:
ptr_hbe_txposer->synth_cos_tab =
(FLOAT32 *)ixheaacd_synth_cos_table_kl_4;
ptr_hbe_txposer->analy_cos_sin_tab =
(FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_8;
ptr_hbe_txposer->ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p2;
ptr_hbe_txposer->ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p2;
break;
case 8:
ptr_hbe_txposer->synth_cos_tab =
(FLOAT32 *)ixheaacd_synth_cos_table_kl_8;
ptr_hbe_txposer->analy_cos_sin_tab =
(FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_16;
ptr_hbe_txposer->ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p2;
ptr_hbe_txposer->ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p2;
break;
case 12:
ptr_hbe_txposer->synth_cos_tab =
(FLOAT32 *)ixheaacd_synth_cos_table_kl_12;
ptr_hbe_txposer->analy_cos_sin_tab =
(FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_24;
ptr_hbe_txposer->ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p3;
ptr_hbe_txposer->ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p3;
break;
case 16:
ptr_hbe_txposer->synth_cos_tab =
(FLOAT32 *)ixheaacd_synth_cos_table_kl_16;
ptr_hbe_txposer->analy_cos_sin_tab =
(FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_32;
ptr_hbe_txposer->ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p2;
ptr_hbe_txposer->ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p2;
break;
case 20:
ptr_hbe_txposer->synth_cos_tab =
(FLOAT32 *)ixheaacd_synth_cos_table_kl_20;
ptr_hbe_txposer->analy_cos_sin_tab =
(FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_40;
break;
default:
ptr_hbe_txposer->synth_cos_tab =
(FLOAT32 *)ixheaacd_synth_cos_table_kl_4;
ptr_hbe_txposer->analy_cos_sin_tab =
(FLOAT32 *)ixheaacd_analy_cos_sin_table_kl_8;
ptr_hbe_txposer->ixheaacd_real_synth_fft = &ixheaacd_real_synth_fft_p2;
ptr_hbe_txposer->ixheaacd_cmplx_anal_fft = &ixheaacd_cmplx_anal_fft_p2;
}
ptr_hbe_txposer->synth_wind_coeff = ixheaacd_map_prot_filter(synth_size);
memset(ptr_hbe_txposer->analy_buf, 0, 640 * sizeof(FLOAT32));
synth_size = 2 * ptr_hbe_txposer->synth_size;
ptr_hbe_txposer->analy_wind_coeff = ixheaacd_map_prot_filter(synth_size);
memset(ptr_hbe_txposer->x_over_qmf, 0, MAX_NUM_PATCHES * sizeof(WORD32));
sfb = 0;
if (upsamp_4_flag) {
stop_patch = MAX_NUM_PATCHES;
ptr_hbe_txposer->max_stretch = MAX_STRETCH;
} else {
stop_patch = MAX_STRETCH;
}
for (patch = 1; patch <= stop_patch; patch++) {
while (sfb <= p_num_sfb[LOW] &&
p_freq_band_tab[LOW][sfb] <= patch * ptr_hbe_txposer->start_band)
sfb++;
if (sfb <= p_num_sfb[LOW]) {
if ((patch * ptr_hbe_txposer->start_band -
p_freq_band_tab[LOW][sfb - 1]) <= 3) {
ptr_hbe_txposer->x_over_qmf[patch - 1] =
p_freq_band_tab[LOW][sfb - 1];
} else {
WORD32 sfb = 0;
while (sfb <= p_num_sfb[HIGH] &&
p_freq_band_tab[HIGH][sfb] <=
patch * ptr_hbe_txposer->start_band)
sfb++;
ptr_hbe_txposer->x_over_qmf[patch - 1] =
p_freq_band_tab[HIGH][sfb - 1];
}
} else {
ptr_hbe_txposer->x_over_qmf[patch - 1] = ptr_hbe_txposer->end_band;
ptr_hbe_txposer->max_stretch = min(patch, MAX_STRETCH);
break;
}
}
if (ptr_hbe_txposer->k_start < 0) {
return -1;
}
}
return 0;
}
| 174,092 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[аысԁеԍһіюјӏорԗԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥกח] > n; œ > ce;"
"[ŧтҭԏ七丅丆丁] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; [ұ丫] > y; [χҳӽӿ乂] > x;"
"[ԃძ] > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[०০੦૦ଠ୦೦] > o;"
"[৭੧૧] > q;"
"[บບ] > u;"
"[θ] > 0;"
"[२২੨੨૨೩೭շ] > 2;"
"[зҙӡउওਤ੩૩౩ဒვპ] > 3;"
"[੫丩ㄐ] > 4;"
"[ճ] > 6;"
"[৪੪୫] > 8;"
"[૭୨౨] > 9;"
"[—一―⸺⸻] > \\-;"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Restrict Latin Small Letter Thorn (U+00FE) to Icelandic domains
This character (þ) can be confused with both b and p when used in a domain
name. IDN spoof checker doesn't have a good way of flagging a character as
confusable with multiple characters, so it can't catch spoofs containing
this character. As a practical fix, this CL restricts this character to
domains under Iceland's ccTLD (.is). With this change, a domain name containing
"þ" with a non-.is TLD will be displayed in punycode in the UI.
This change affects less than 10 real world domains with limited popularity.
Bug: 798892, 843352, 904327, 1017707
Change-Id: Ib07190dcde406bf62ce4413688a4fb4859a51030
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1879992
Commit-Queue: Mustafa Emre Acer <[email protected]>
Reviewed-by: Christopher Thompson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#709309}
CWE ID: | IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[аысԁеԍһіюјӏорԗԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// - {U+03FC (ϼ), U+048F (ҏ)} => p
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [ϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥกח] > n; œ > ce;"
"[ŧтҭԏ七丅丆丁] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; [ұ丫] > y; [χҳӽӿ乂] > x;"
"[ԃძ] > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[०০੦૦ଠ୦೦] > o;"
"[৭੧૧] > q;"
"[บບ] > u;"
"[θ] > 0;"
"[२২੨੨૨೩೭շ] > 2;"
"[зҙӡउওਤ੩૩౩ဒვპ] > 3;"
"[੫丩ㄐ] > 4;"
"[ճ] > 6;"
"[৪੪୫] > 8;"
"[૭୨౨] > 9;"
"[—一―⸺⸻] > \\-;"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 172,726 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void VRDisplay::cancelAnimationFrame(int id) {
if (!scripted_animation_controller_)
return;
scripted_animation_controller_->CancelCallback(id);
}
Commit Message: WebVR: fix initial vsync
Applications sometimes use window.rAF while not presenting, then switch to
vrDisplay.rAF after presentation starts. Depending on the animation loop's
timing, this can cause a race condition where presentation has been started
but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync
being processed after presentation starts so that a queued window.rAF
can run and schedule a vrDisplay.rAF.
BUG=711789
Review-Url: https://codereview.chromium.org/2848483003
Cr-Commit-Position: refs/heads/master@{#468167}
CWE ID: | void VRDisplay::cancelAnimationFrame(int id) {
DVLOG(2) << __FUNCTION__;
if (!scripted_animation_controller_)
return;
scripted_animation_controller_->CancelCallback(id);
}
| 172,000 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int sysMapFile(const char* fn, MemMapping* pMap)
{
memset(pMap, 0, sizeof(*pMap));
if (fn && fn[0] == '@') {
FILE* mapf = fopen(fn+1, "r");
if (mapf == NULL) {
LOGV("Unable to open '%s': %s\n", fn+1, strerror(errno));
return -1;
}
if (sysMapBlockFile(mapf, pMap) != 0) {
LOGW("Map of '%s' failed\n", fn);
return -1;
}
fclose(mapf);
} else {
int fd = open(fn, O_RDONLY, 0);
if (fd < 0) {
LOGE("Unable to open '%s': %s\n", fn, strerror(errno));
return -1;
}
if (sysMapFD(fd, pMap) != 0) {
LOGE("Map of '%s' failed\n", fn);
close(fd);
return -1;
}
close(fd);
}
return 0;
}
Commit Message: Fix integer overflows in recovery procedure.
Bug: 26960931
Change-Id: Ieae45caccfb4728fcf514f0d920976585d8e6caf
(cherry picked from commit 4f2df162c6ab4a71ca86e4b38735b681729c353b)
CWE ID: CWE-189 | int sysMapFile(const char* fn, MemMapping* pMap)
{
memset(pMap, 0, sizeof(*pMap));
if (fn && fn[0] == '@') {
FILE* mapf = fopen(fn+1, "r");
if (mapf == NULL) {
LOGV("Unable to open '%s': %s\n", fn+1, strerror(errno));
return -1;
}
if (sysMapBlockFile(mapf, pMap) != 0) {
LOGW("Map of '%s' failed\n", fn);
fclose(mapf);
return -1;
}
fclose(mapf);
} else {
int fd = open(fn, O_RDONLY, 0);
if (fd < 0) {
LOGE("Unable to open '%s': %s\n", fn, strerror(errno));
return -1;
}
if (sysMapFD(fd, pMap) != 0) {
LOGE("Map of '%s' failed\n", fn);
close(fd);
return -1;
}
close(fd);
}
return 0;
}
| 173,905 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PassRefPtr<RTCSessionDescription> RTCPeerConnection::remoteDescription(ExceptionCode& ec)
{
if (m_readyState == ReadyStateClosing || m_readyState == ReadyStateClosed) {
ec = INVALID_STATE_ERR;
return 0;
}
RefPtr<RTCSessionDescriptionDescriptor> descriptor = m_peerHandler->remoteDescription();
if (!descriptor)
return 0;
RefPtr<RTCSessionDescription> desc = RTCSessionDescription::create(descriptor.release());
return desc.release();
}
Commit Message: Unreviewed, rolling out r127612, r127660, and r127664.
http://trac.webkit.org/changeset/127612
http://trac.webkit.org/changeset/127660
http://trac.webkit.org/changeset/127664
https://bugs.webkit.org/show_bug.cgi?id=95920
Source/Platform:
* Platform.gypi:
* chromium/public/WebRTCPeerConnectionHandler.h:
(WebKit):
(WebRTCPeerConnectionHandler):
* chromium/public/WebRTCVoidRequest.h: Removed.
Source/WebCore:
* CMakeLists.txt:
* GNUmakefile.list.am:
* Modules/mediastream/RTCErrorCallback.h:
(WebCore):
(RTCErrorCallback):
* Modules/mediastream/RTCErrorCallback.idl:
* Modules/mediastream/RTCPeerConnection.cpp:
(WebCore::RTCPeerConnection::createOffer):
* Modules/mediastream/RTCPeerConnection.h:
(WebCore):
(RTCPeerConnection):
* Modules/mediastream/RTCPeerConnection.idl:
* Modules/mediastream/RTCSessionDescriptionCallback.h:
(WebCore):
(RTCSessionDescriptionCallback):
* Modules/mediastream/RTCSessionDescriptionCallback.idl:
* Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp:
(WebCore::RTCSessionDescriptionRequestImpl::create):
(WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl):
(WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded):
(WebCore::RTCSessionDescriptionRequestImpl::requestFailed):
(WebCore::RTCSessionDescriptionRequestImpl::clear):
* Modules/mediastream/RTCSessionDescriptionRequestImpl.h:
(RTCSessionDescriptionRequestImpl):
* Modules/mediastream/RTCVoidRequestImpl.cpp: Removed.
* Modules/mediastream/RTCVoidRequestImpl.h: Removed.
* WebCore.gypi:
* platform/chromium/support/WebRTCVoidRequest.cpp: Removed.
* platform/mediastream/RTCPeerConnectionHandler.cpp:
(RTCPeerConnectionHandlerDummy):
(WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy):
* platform/mediastream/RTCPeerConnectionHandler.h:
(WebCore):
(WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler):
(RTCPeerConnectionHandler):
(WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler):
* platform/mediastream/RTCVoidRequest.h: Removed.
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp:
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h:
(RTCPeerConnectionHandlerChromium):
Tools:
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp:
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask):
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::createOffer):
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h:
(MockWebRTCPeerConnectionHandler):
(SuccessCallbackTask):
(FailureCallbackTask):
LayoutTests:
* fast/mediastream/RTCPeerConnection-createOffer.html:
* fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-localDescription.html: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed.
git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | PassRefPtr<RTCSessionDescription> RTCPeerConnection::remoteDescription(ExceptionCode& ec)
| 170,337 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SYSCALL_DEFINE3(osf_sysinfo, int, command, char __user *, buf, long, count)
{
const char *sysinfo_table[] = {
utsname()->sysname,
utsname()->nodename,
utsname()->release,
utsname()->version,
utsname()->machine,
"alpha", /* instruction set architecture */
"dummy", /* hardware serial number */
"dummy", /* hardware manufacturer */
"dummy", /* secure RPC domain */
};
unsigned long offset;
const char *res;
long len, err = -EINVAL;
offset = command-1;
if (offset >= ARRAY_SIZE(sysinfo_table)) {
/* Digital UNIX has a few unpublished interfaces here */
printk("sysinfo(%d)", command);
goto out;
}
down_read(&uts_sem);
res = sysinfo_table[offset];
len = strlen(res)+1;
if (len > count)
len = count;
if (copy_to_user(buf, res, len))
err = -EFAULT;
else
err = 0;
up_read(&uts_sem);
out:
return err;
}
Commit Message: alpha: fix several security issues
Fix several security issues in Alpha-specific syscalls. Untested, but
mostly trivial.
1. Signedness issue in osf_getdomainname allows copying out-of-bounds
kernel memory to userland.
2. Signedness issue in osf_sysinfo allows copying large amounts of
kernel memory to userland.
3. Typo (?) in osf_getsysinfo bounds minimum instead of maximum copy
size, allowing copying large amounts of kernel memory to userland.
4. Usage of user pointer in osf_wait4 while under KERNEL_DS allows
privilege escalation via writing return value of sys_wait4 to kernel
memory.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: Richard Henderson <[email protected]>
Cc: Ivan Kokshaysky <[email protected]>
Cc: Matt Turner <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | SYSCALL_DEFINE3(osf_sysinfo, int, command, char __user *, buf, long, count)
{
const char *sysinfo_table[] = {
utsname()->sysname,
utsname()->nodename,
utsname()->release,
utsname()->version,
utsname()->machine,
"alpha", /* instruction set architecture */
"dummy", /* hardware serial number */
"dummy", /* hardware manufacturer */
"dummy", /* secure RPC domain */
};
unsigned long offset;
const char *res;
long len, err = -EINVAL;
offset = command-1;
if (offset >= ARRAY_SIZE(sysinfo_table)) {
/* Digital UNIX has a few unpublished interfaces here */
printk("sysinfo(%d)", command);
goto out;
}
down_read(&uts_sem);
res = sysinfo_table[offset];
len = strlen(res)+1;
if ((unsigned long)len > (unsigned long)count)
len = count;
if (copy_to_user(buf, res, len))
err = -EFAULT;
else
err = 0;
up_read(&uts_sem);
out:
return err;
}
| 165,868 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 restore_tm_user_regs(struct pt_regs *regs,
struct mcontext __user *sr,
struct mcontext __user *tm_sr)
{
long err;
unsigned long msr, msr_hi;
#ifdef CONFIG_VSX
int i;
#endif
/*
* restore general registers but not including MSR or SOFTE. Also
* take care of keeping r2 (TLS) intact if not a signal.
* See comment in signal_64.c:restore_tm_sigcontexts();
* TFHAR is restored from the checkpointed NIP; TEXASR and TFIAR
* were set by the signal delivery.
*/
err = restore_general_regs(regs, tm_sr);
err |= restore_general_regs(¤t->thread.ckpt_regs, sr);
err |= __get_user(current->thread.tm_tfhar, &sr->mc_gregs[PT_NIP]);
err |= __get_user(msr, &sr->mc_gregs[PT_MSR]);
if (err)
return 1;
/* Restore the previous little-endian mode */
regs->msr = (regs->msr & ~MSR_LE) | (msr & MSR_LE);
/*
* Do this before updating the thread state in
* current->thread.fpr/vr/evr. That way, if we get preempted
* and another task grabs the FPU/Altivec/SPE, it won't be
* tempted to save the current CPU state into the thread_struct
* and corrupt what we are writing there.
*/
discard_lazy_cpu_state();
#ifdef CONFIG_ALTIVEC
regs->msr &= ~MSR_VEC;
if (msr & MSR_VEC) {
/* restore altivec registers from the stack */
if (__copy_from_user(¤t->thread.vr_state, &sr->mc_vregs,
sizeof(sr->mc_vregs)) ||
__copy_from_user(¤t->thread.transact_vr,
&tm_sr->mc_vregs,
sizeof(sr->mc_vregs)))
return 1;
} else if (current->thread.used_vr) {
memset(¤t->thread.vr_state, 0,
ELF_NVRREG * sizeof(vector128));
memset(¤t->thread.transact_vr, 0,
ELF_NVRREG * sizeof(vector128));
}
/* Always get VRSAVE back */
if (__get_user(current->thread.vrsave,
(u32 __user *)&sr->mc_vregs[32]) ||
__get_user(current->thread.transact_vrsave,
(u32 __user *)&tm_sr->mc_vregs[32]))
return 1;
if (cpu_has_feature(CPU_FTR_ALTIVEC))
mtspr(SPRN_VRSAVE, current->thread.vrsave);
#endif /* CONFIG_ALTIVEC */
regs->msr &= ~(MSR_FP | MSR_FE0 | MSR_FE1);
if (copy_fpr_from_user(current, &sr->mc_fregs) ||
copy_transact_fpr_from_user(current, &tm_sr->mc_fregs))
return 1;
#ifdef CONFIG_VSX
regs->msr &= ~MSR_VSX;
if (msr & MSR_VSX) {
/*
* Restore altivec registers from the stack to a local
* buffer, then write this out to the thread_struct
*/
if (copy_vsx_from_user(current, &sr->mc_vsregs) ||
copy_transact_vsx_from_user(current, &tm_sr->mc_vsregs))
return 1;
} else if (current->thread.used_vsr)
for (i = 0; i < 32 ; i++) {
current->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0;
current->thread.transact_fp.fpr[i][TS_VSRLOWOFFSET] = 0;
}
#endif /* CONFIG_VSX */
#ifdef CONFIG_SPE
/* SPE regs are not checkpointed with TM, so this section is
* simply the same as in restore_user_regs().
*/
regs->msr &= ~MSR_SPE;
if (msr & MSR_SPE) {
if (__copy_from_user(current->thread.evr, &sr->mc_vregs,
ELF_NEVRREG * sizeof(u32)))
return 1;
} else if (current->thread.used_spe)
memset(current->thread.evr, 0, ELF_NEVRREG * sizeof(u32));
/* Always get SPEFSCR back */
if (__get_user(current->thread.spefscr, (u32 __user *)&sr->mc_vregs
+ ELF_NEVRREG))
return 1;
#endif /* CONFIG_SPE */
/* Now, recheckpoint. This loads up all of the checkpointed (older)
* registers, including FP and V[S]Rs. After recheckpointing, the
* transactional versions should be loaded.
*/
tm_enable();
/* Make sure the transaction is marked as failed */
current->thread.tm_texasr |= TEXASR_FS;
/* This loads the checkpointed FP/VEC state, if used */
tm_recheckpoint(¤t->thread, msr);
/* Get the top half of the MSR */
if (__get_user(msr_hi, &tm_sr->mc_gregs[PT_MSR]))
return 1;
/* Pull in MSR TM from user context */
regs->msr = (regs->msr & ~MSR_TS_MASK) | ((msr_hi<<32) & MSR_TS_MASK);
/* This loads the speculative FP/VEC state, if used */
if (msr & MSR_FP) {
do_load_up_transact_fpu(¤t->thread);
regs->msr |= (MSR_FP | current->thread.fpexc_mode);
}
#ifdef CONFIG_ALTIVEC
if (msr & MSR_VEC) {
do_load_up_transact_altivec(¤t->thread);
regs->msr |= MSR_VEC;
}
#endif
return 0;
}
Commit Message: powerpc/tm: Block signal return setting invalid MSR state
Currently we allow both the MSR T and S bits to be set by userspace on
a signal return. Unfortunately this is a reserved configuration and
will cause a TM Bad Thing exception if attempted (via rfid).
This patch checks for this case in both the 32 and 64 bit signals
code. If both T and S are set, we mark the context as invalid.
Found using a syscall fuzzer.
Fixes: 2b0a576d15e0 ("powerpc: Add new transactional memory state to the signal context")
Cc: [email protected] # v3.9+
Signed-off-by: Michael Neuling <[email protected]>
Signed-off-by: Michael Ellerman <[email protected]>
CWE ID: CWE-20 | static long restore_tm_user_regs(struct pt_regs *regs,
struct mcontext __user *sr,
struct mcontext __user *tm_sr)
{
long err;
unsigned long msr, msr_hi;
#ifdef CONFIG_VSX
int i;
#endif
/*
* restore general registers but not including MSR or SOFTE. Also
* take care of keeping r2 (TLS) intact if not a signal.
* See comment in signal_64.c:restore_tm_sigcontexts();
* TFHAR is restored from the checkpointed NIP; TEXASR and TFIAR
* were set by the signal delivery.
*/
err = restore_general_regs(regs, tm_sr);
err |= restore_general_regs(¤t->thread.ckpt_regs, sr);
err |= __get_user(current->thread.tm_tfhar, &sr->mc_gregs[PT_NIP]);
err |= __get_user(msr, &sr->mc_gregs[PT_MSR]);
if (err)
return 1;
/* Restore the previous little-endian mode */
regs->msr = (regs->msr & ~MSR_LE) | (msr & MSR_LE);
/*
* Do this before updating the thread state in
* current->thread.fpr/vr/evr. That way, if we get preempted
* and another task grabs the FPU/Altivec/SPE, it won't be
* tempted to save the current CPU state into the thread_struct
* and corrupt what we are writing there.
*/
discard_lazy_cpu_state();
#ifdef CONFIG_ALTIVEC
regs->msr &= ~MSR_VEC;
if (msr & MSR_VEC) {
/* restore altivec registers from the stack */
if (__copy_from_user(¤t->thread.vr_state, &sr->mc_vregs,
sizeof(sr->mc_vregs)) ||
__copy_from_user(¤t->thread.transact_vr,
&tm_sr->mc_vregs,
sizeof(sr->mc_vregs)))
return 1;
} else if (current->thread.used_vr) {
memset(¤t->thread.vr_state, 0,
ELF_NVRREG * sizeof(vector128));
memset(¤t->thread.transact_vr, 0,
ELF_NVRREG * sizeof(vector128));
}
/* Always get VRSAVE back */
if (__get_user(current->thread.vrsave,
(u32 __user *)&sr->mc_vregs[32]) ||
__get_user(current->thread.transact_vrsave,
(u32 __user *)&tm_sr->mc_vregs[32]))
return 1;
if (cpu_has_feature(CPU_FTR_ALTIVEC))
mtspr(SPRN_VRSAVE, current->thread.vrsave);
#endif /* CONFIG_ALTIVEC */
regs->msr &= ~(MSR_FP | MSR_FE0 | MSR_FE1);
if (copy_fpr_from_user(current, &sr->mc_fregs) ||
copy_transact_fpr_from_user(current, &tm_sr->mc_fregs))
return 1;
#ifdef CONFIG_VSX
regs->msr &= ~MSR_VSX;
if (msr & MSR_VSX) {
/*
* Restore altivec registers from the stack to a local
* buffer, then write this out to the thread_struct
*/
if (copy_vsx_from_user(current, &sr->mc_vsregs) ||
copy_transact_vsx_from_user(current, &tm_sr->mc_vsregs))
return 1;
} else if (current->thread.used_vsr)
for (i = 0; i < 32 ; i++) {
current->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0;
current->thread.transact_fp.fpr[i][TS_VSRLOWOFFSET] = 0;
}
#endif /* CONFIG_VSX */
#ifdef CONFIG_SPE
/* SPE regs are not checkpointed with TM, so this section is
* simply the same as in restore_user_regs().
*/
regs->msr &= ~MSR_SPE;
if (msr & MSR_SPE) {
if (__copy_from_user(current->thread.evr, &sr->mc_vregs,
ELF_NEVRREG * sizeof(u32)))
return 1;
} else if (current->thread.used_spe)
memset(current->thread.evr, 0, ELF_NEVRREG * sizeof(u32));
/* Always get SPEFSCR back */
if (__get_user(current->thread.spefscr, (u32 __user *)&sr->mc_vregs
+ ELF_NEVRREG))
return 1;
#endif /* CONFIG_SPE */
/* Get the top half of the MSR from the user context */
if (__get_user(msr_hi, &tm_sr->mc_gregs[PT_MSR]))
return 1;
msr_hi <<= 32;
/* If TM bits are set to the reserved value, it's an invalid context */
if (MSR_TM_RESV(msr_hi))
return 1;
/* Pull in the MSR TM bits from the user context */
regs->msr = (regs->msr & ~MSR_TS_MASK) | (msr_hi & MSR_TS_MASK);
/* Now, recheckpoint. This loads up all of the checkpointed (older)
* registers, including FP and V[S]Rs. After recheckpointing, the
* transactional versions should be loaded.
*/
tm_enable();
/* Make sure the transaction is marked as failed */
current->thread.tm_texasr |= TEXASR_FS;
/* This loads the checkpointed FP/VEC state, if used */
tm_recheckpoint(¤t->thread, msr);
/* This loads the speculative FP/VEC state, if used */
if (msr & MSR_FP) {
do_load_up_transact_fpu(¤t->thread);
regs->msr |= (MSR_FP | current->thread.fpexc_mode);
}
#ifdef CONFIG_ALTIVEC
if (msr & MSR_VEC) {
do_load_up_transact_altivec(¤t->thread);
regs->msr |= MSR_VEC;
}
#endif
return 0;
}
| 167,481 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Cluster::GetFirst(const BlockEntry*& pFirst) const
{
if (m_entries_count <= 0)
{
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) //error
{
pFirst = NULL;
return status;
}
if (m_entries_count <= 0) //empty cluster
{
pFirst = NULL;
return 0;
}
}
assert(m_entries);
pFirst = m_entries[0];
assert(pFirst);
return 0; //success
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long Cluster::GetFirst(const BlockEntry*& pFirst) const
| 174,320 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 **XListExtensions(
register Display *dpy,
int *nextensions) /* RETURN */
{
xListExtensionsReply rep;
char **list = NULL;
char *ch = NULL;
char *chend;
int count = 0;
register unsigned i;
register int length;
_X_UNUSED register xReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetEmptyReq (ListExtensions, req);
if (! _XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nExtensions) {
list = Xmalloc (rep.nExtensions * sizeof (char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc (rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((!list) || (!ch)) {
Xfree(list);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chend = ch + rlen;
length = *ch;
for (i = 0; i < rep.nExtensions; i++) {
if (ch + length < chend) {
list[i] = ch+1; /* skip over length */
ch += length + 1; /* find next length ... */
length = *ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else
list[i] = NULL;
}
}
*nextensions = count;
UnlockDisplay(dpy);
SyncHandle();
return (list);
}
Commit Message:
CWE ID: CWE-787 | char **XListExtensions(
register Display *dpy,
int *nextensions) /* RETURN */
{
xListExtensionsReply rep;
char **list = NULL;
char *ch = NULL;
char *chend;
int count = 0;
register unsigned i;
register int length;
_X_UNUSED register xReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetEmptyReq (ListExtensions, req);
if (! _XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nExtensions) {
list = Xmalloc (rep.nExtensions * sizeof (char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc (rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((!list) || (!ch)) {
Xfree(list);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chend = ch + rlen;
length = *(unsigned char *)ch;
for (i = 0; i < rep.nExtensions; i++) {
if (ch + length < chend) {
list[i] = ch+1; /* skip over length */
ch += length + 1; /* find next length ... */
length = *(unsigned char *)ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else
list[i] = NULL;
}
}
*nextensions = count;
UnlockDisplay(dpy);
SyncHandle();
return (list);
}
| 164,746 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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* problem_data_save(problem_data_t *pd)
{
load_abrt_conf();
struct dump_dir *dd = create_dump_dir_from_problem_data(pd, g_settings_dump_location);
char *problem_id = NULL;
if (dd)
{
problem_id = xstrdup(dd->dd_dirname);
dd_close(dd);
}
log_info("problem id: '%s'", problem_id);
return problem_id;
}
Commit Message: make the dump directories owned by root by default
It was discovered that the abrt event scripts create a user-readable
copy of a sosreport file in abrt problem directories, and include
excerpts of /var/log/messages selected by the user-controlled process
name, leading to an information disclosure.
This issue was discovered by Florian Weimer of Red Hat Product Security.
Related: #1212868
Signed-off-by: Jakub Filak <[email protected]>
CWE ID: CWE-200 | char* problem_data_save(problem_data_t *pd)
{
load_abrt_conf();
struct dump_dir *dd = NULL;
if (g_settings_privatereports)
dd = create_dump_dir_from_problem_data_ext(pd, g_settings_dump_location, 0);
else
dd = create_dump_dir_from_problem_data(pd, g_settings_dump_location);
char *problem_id = NULL;
if (dd)
{
problem_id = xstrdup(dd->dd_dirname);
dd_close(dd);
}
log_info("problem id: '%s'", problem_id);
return problem_id;
}
| 170,151 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: DisplaySourceCustomBindings::DisplaySourceCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context),
weak_factory_(this) {
RouteFunction("StartSession",
base::Bind(&DisplaySourceCustomBindings::StartSession,
weak_factory_.GetWeakPtr()));
RouteFunction("TerminateSession",
base::Bind(&DisplaySourceCustomBindings::TerminateSession,
weak_factory_.GetWeakPtr()));
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284 | DisplaySourceCustomBindings::DisplaySourceCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context),
weak_factory_(this) {
RouteFunction("StartSession", "displaySource",
base::Bind(&DisplaySourceCustomBindings::StartSession,
weak_factory_.GetWeakPtr()));
RouteFunction("TerminateSession", "displaySource",
base::Bind(&DisplaySourceCustomBindings::TerminateSession,
weak_factory_.GetWeakPtr()));
}
| 172,248 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 nfs4_state *nfs4_do_open(struct inode *dir, struct path *path, int flags, struct iattr *sattr, struct rpc_cred *cred)
{
struct nfs4_exception exception = { };
struct nfs4_state *res;
int status;
do {
status = _nfs4_do_open(dir, path, flags, sattr, cred, &res);
if (status == 0)
break;
/* NOTE: BAD_SEQID means the server and client disagree about the
* book-keeping w.r.t. state-changing operations
* (OPEN/CLOSE/LOCK/LOCKU...)
* It is actually a sign of a bug on the client or on the server.
*
* If we receive a BAD_SEQID error in the particular case of
* doing an OPEN, we assume that nfs_increment_open_seqid() will
* have unhashed the old state_owner for us, and that we can
* therefore safely retry using a new one. We should still warn
* the user though...
*/
if (status == -NFS4ERR_BAD_SEQID) {
printk(KERN_WARNING "NFS: v4 server %s "
" returned a bad sequence-id error!\n",
NFS_SERVER(dir)->nfs_client->cl_hostname);
exception.retry = 1;
continue;
}
/*
* BAD_STATEID on OPEN means that the server cancelled our
* state before it received the OPEN_CONFIRM.
* Recover by retrying the request as per the discussion
* on Page 181 of RFC3530.
*/
if (status == -NFS4ERR_BAD_STATEID) {
exception.retry = 1;
continue;
}
if (status == -EAGAIN) {
/* We must have found a delegation */
exception.retry = 1;
continue;
}
res = ERR_PTR(nfs4_handle_exception(NFS_SERVER(dir),
status, &exception));
} while (exception.retry);
return res;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static struct nfs4_state *nfs4_do_open(struct inode *dir, struct path *path, int flags, struct iattr *sattr, struct rpc_cred *cred)
static struct nfs4_state *nfs4_do_open(struct inode *dir, struct path *path, fmode_t fmode, int flags, struct iattr *sattr, struct rpc_cred *cred)
{
struct nfs4_exception exception = { };
struct nfs4_state *res;
int status;
do {
status = _nfs4_do_open(dir, path, fmode, flags, sattr, cred, &res);
if (status == 0)
break;
/* NOTE: BAD_SEQID means the server and client disagree about the
* book-keeping w.r.t. state-changing operations
* (OPEN/CLOSE/LOCK/LOCKU...)
* It is actually a sign of a bug on the client or on the server.
*
* If we receive a BAD_SEQID error in the particular case of
* doing an OPEN, we assume that nfs_increment_open_seqid() will
* have unhashed the old state_owner for us, and that we can
* therefore safely retry using a new one. We should still warn
* the user though...
*/
if (status == -NFS4ERR_BAD_SEQID) {
printk(KERN_WARNING "NFS: v4 server %s "
" returned a bad sequence-id error!\n",
NFS_SERVER(dir)->nfs_client->cl_hostname);
exception.retry = 1;
continue;
}
/*
* BAD_STATEID on OPEN means that the server cancelled our
* state before it received the OPEN_CONFIRM.
* Recover by retrying the request as per the discussion
* on Page 181 of RFC3530.
*/
if (status == -NFS4ERR_BAD_STATEID) {
exception.retry = 1;
continue;
}
if (status == -EAGAIN) {
/* We must have found a delegation */
exception.retry = 1;
continue;
}
res = ERR_PTR(nfs4_handle_exception(NFS_SERVER(dir),
status, &exception));
} while (exception.retry);
return res;
}
| 165,692 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void sas_probe_devices(struct work_struct *work)
{
struct domain_device *dev, *n;
struct sas_discovery_event *ev = to_sas_discovery_event(work);
struct asd_sas_port *port = ev->port;
clear_bit(DISCE_PROBE, &port->disc.pending);
/* devices must be domain members before link recovery and probe */
list_for_each_entry(dev, &port->disco_list, disco_list_node) {
spin_lock_irq(&port->dev_list_lock);
list_add_tail(&dev->dev_list_node, &port->dev_list);
spin_unlock_irq(&port->dev_list_lock);
}
sas_probe_sata(port);
list_for_each_entry_safe(dev, n, &port->disco_list, disco_list_node) {
int err;
err = sas_rphy_add(dev->rphy);
if (err)
sas_fail_probe(dev, __func__, err);
else
list_del_init(&dev->disco_list_node);
}
}
Commit Message: scsi: libsas: direct call probe and destruct
In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery
competing with ata error handling") introduced disco mutex to prevent
rediscovery competing with ata error handling and put the whole
revalidation in the mutex. But the rphy add/remove needs to wait for the
error handling which also grabs the disco mutex. This may leads to dead
lock.So the probe and destruct event were introduce to do the rphy
add/remove asynchronously and out of the lock.
The asynchronously processed workers makes the whole discovery process
not atomic, the other events may interrupt the process. For example,
if a loss of signal event inserted before the probe event, the
sas_deform_port() is called and the port will be deleted.
And sas_port_delete() may run before the destruct event, but the
port-x:x is the top parent of end device or expander. This leads to
a kernel WARNING such as:
[ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22'
[ 82.042983] ------------[ cut here ]------------
[ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237
sysfs_remove_group+0x94/0xa0
[ 82.043059] Call trace:
[ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0
[ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70
[ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308
[ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60
[ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80
[ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0
[ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50
[ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0
[ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0
[ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490
[ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128
[ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50
Make probe and destruct a direct call in the disco and revalidate function,
but put them outside the lock. The whole discovery or revalidate won't
be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT
event are deleted as a result of the direct call.
Introduce a new list to destruct the sas_port and put the port delete after
the destruct. This makes sure the right order of destroying the sysfs
kobject and fix the warning above.
In sas_ex_revalidate_domain() have a loop to find all broadcasted
device, and sometimes we have a chance to find the same expander twice.
Because the sas_port will be deleted at the end of the whole revalidate
process, sas_port with the same name cannot be added before this.
Otherwise the sysfs will complain of creating duplicate filename. Since
the LLDD will send broadcast for every device change, we can only
process one expander's revalidation.
[mkp: kbuild test robot warning]
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: Johannes Thumshirn <[email protected]>
CC: Ewan Milne <[email protected]>
CC: Christoph Hellwig <[email protected]>
CC: Tomas Henzl <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Hannes Reinecke <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID: | static void sas_probe_devices(struct work_struct *work)
static void sas_probe_devices(struct asd_sas_port *port)
{
struct domain_device *dev, *n;
/* devices must be domain members before link recovery and probe */
list_for_each_entry(dev, &port->disco_list, disco_list_node) {
spin_lock_irq(&port->dev_list_lock);
list_add_tail(&dev->dev_list_node, &port->dev_list);
spin_unlock_irq(&port->dev_list_lock);
}
sas_probe_sata(port);
list_for_each_entry_safe(dev, n, &port->disco_list, disco_list_node) {
int err;
err = sas_rphy_add(dev->rphy);
if (err)
sas_fail_probe(dev, __func__, err);
else
list_del_init(&dev->disco_list_node);
}
}
| 169,388 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xdr_krb5_principal(XDR *xdrs, krb5_principal *objp)
{
int ret;
char *p = NULL;
krb5_principal pr = NULL;
static krb5_context context = NULL;
/* using a static context here is ugly, but should work
ok, and the other solutions are even uglier */
if (!context &&
kadm5_init_krb5_context(&context))
return(FALSE);
switch(xdrs->x_op) {
case XDR_ENCODE:
if (*objp) {
if((ret = krb5_unparse_name(context, *objp, &p)) != 0)
return FALSE;
}
if(!xdr_nullstring(xdrs, &p))
return FALSE;
if (p) free(p);
break;
case XDR_DECODE:
if(!xdr_nullstring(xdrs, &p))
return FALSE;
if (p) {
ret = krb5_parse_name(context, p, &pr);
if(ret != 0)
return FALSE;
*objp = pr;
free(p);
} else
*objp = NULL;
break;
case XDR_FREE:
if(*objp != NULL)
krb5_free_principal(context, *objp);
break;
}
return TRUE;
}
Commit Message: Fix kadm5/gssrpc XDR double free [CVE-2014-9421]
[MITKRB5-SA-2015-001] In auth_gssapi_unwrap_data(), do not free
partial deserialization results upon failure to deserialize. This
responsibility belongs to the callers, svctcp_getargs() and
svcudp_getargs(); doing it in the unwrap function results in freeing
the results twice.
In xdr_krb5_tl_data() and xdr_krb5_principal(), null out the pointers
we are freeing, as other XDR functions such as xdr_bytes() and
xdr_string().
ticket: 8056 (new)
target_version: 1.13.1
tags: pullup
CWE ID: | xdr_krb5_principal(XDR *xdrs, krb5_principal *objp)
{
int ret;
char *p = NULL;
krb5_principal pr = NULL;
static krb5_context context = NULL;
/* using a static context here is ugly, but should work
ok, and the other solutions are even uglier */
if (!context &&
kadm5_init_krb5_context(&context))
return(FALSE);
switch(xdrs->x_op) {
case XDR_ENCODE:
if (*objp) {
if((ret = krb5_unparse_name(context, *objp, &p)) != 0)
return FALSE;
}
if(!xdr_nullstring(xdrs, &p))
return FALSE;
if (p) free(p);
break;
case XDR_DECODE:
if(!xdr_nullstring(xdrs, &p))
return FALSE;
if (p) {
ret = krb5_parse_name(context, p, &pr);
if(ret != 0)
return FALSE;
*objp = pr;
free(p);
} else
*objp = NULL;
break;
case XDR_FREE:
if(*objp != NULL)
krb5_free_principal(context, *objp);
*objp = NULL;
break;
}
return TRUE;
}
| 166,790 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 Cluster::EOS() const
//// long long element_size)
{
return (m_pSegment == NULL);
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | bool Cluster::EOS() const
pEntry = NULL;
if (index < 0)
return -1; // generic error
if (m_entries_count < 0)
return E_BUFFER_NOT_FULL;
assert(m_entries);
assert(m_entries_size > 0);
assert(m_entries_count <= m_entries_size);
if (index < m_entries_count) {
pEntry = m_entries[index];
assert(pEntry);
return 1; // found entry
}
if (m_element_size < 0) // we don't know cluster end yet
return E_BUFFER_NOT_FULL; // underflow
const long long element_stop = m_element_start + m_element_size;
if (m_pos >= element_stop)
return 0; // nothing left to parse
return E_BUFFER_NOT_FULL; // underflow, since more remains to be parsed
}
Cluster* Cluster::Create(Segment* pSegment, long idx, long long off)
//// long long element_size)
{
assert(pSegment);
assert(off >= 0);
const long long element_start = pSegment->m_start + off;
Cluster* const pCluster = new Cluster(pSegment, idx, element_start);
// element_size);
assert(pCluster);
return pCluster;
}
| 174,270 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 __net_random_once_deferred(struct work_struct *w)
{
struct __net_random_once_work *work =
container_of(w, struct __net_random_once_work, work);
if (!static_key_enabled(work->key))
static_key_slow_inc(work->key);
kfree(work);
}
Commit Message: net: avoid dependency of net_get_random_once on nop patching
net_get_random_once depends on the static keys infrastructure to patch up
the branch to the slow path during boot. This was realized by abusing the
static keys api and defining a new initializer to not enable the call
site while still indicating that the branch point should get patched
up. This was needed to have the fast path considered likely by gcc.
The static key initialization during boot up normally walks through all
the registered keys and either patches in ideal nops or enables the jump
site but omitted that step on x86 if ideal nops where already placed at
static_key branch points. Thus net_get_random_once branches not always
became active.
This patch switches net_get_random_once to the ordinary static_key
api and thus places the kernel fast path in the - by gcc considered -
unlikely path. Microbenchmarks on Intel and AMD x86-64 showed that
the unlikely path actually beats the likely path in terms of cycle cost
and that different nop patterns did not make much difference, thus this
switch should not be noticeable.
Fixes: a48e42920ff38b ("net: introduce new macro net_get_random_once")
Reported-by: Tuomas Räsänen <[email protected]>
Cc: Linus Torvalds <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static void __net_random_once_deferred(struct work_struct *w)
{
struct __net_random_once_work *work =
container_of(w, struct __net_random_once_work, work);
BUG_ON(!static_key_enabled(work->key));
static_key_slow_dec(work->key);
kfree(work);
}
| 166,259 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 AXListBoxOption::isEnabled() const {
if (!getNode())
return false;
if (equalIgnoringCase(getAttribute(aria_disabledAttr), "true"))
return false;
if (toElement(getNode())->hasAttribute(disabledAttr))
return false;
return true;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | bool AXListBoxOption::isEnabled() const {
if (!getNode())
return false;
if (equalIgnoringASCIICase(getAttribute(aria_disabledAttr), "true"))
return false;
if (toElement(getNode())->hasAttribute(disabledAttr))
return false;
return true;
}
| 171,907 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 SVGElement::HasSVGParent() const {
return ParentOrShadowHostElement() &&
ParentOrShadowHostElement()->IsSVGElement();
}
Commit Message: Fix SVG crash for v0 distribution into foreignObject.
We require a parent element to be an SVG element for non-svg-root
elements in order to create a LayoutObject for them. However, we checked
the light tree parent element, not the flat tree one which is the parent
for the layout tree construction. Note that this is just an issue in
Shadow DOM v0 since v1 does not allow shadow roots on SVG elements.
Bug: 915469
Change-Id: Id81843abad08814fae747b5bc81c09666583f130
Reviewed-on: https://chromium-review.googlesource.com/c/1382494
Reviewed-by: Fredrik Söderquist <[email protected]>
Commit-Queue: Rune Lillesveen <[email protected]>
Cr-Commit-Position: refs/heads/master@{#617487}
CWE ID: CWE-704 | bool SVGElement::HasSVGParent() const {
Element* parent = FlatTreeTraversal::ParentElement(*this);
return parent && parent->IsSVGElement();
}
| 173,065 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 Document::InitSecurityContext(const DocumentInit& initializer) {
DCHECK(!GetSecurityOrigin());
if (!initializer.HasSecurityContext()) {
cookie_url_ = KURL(kParsedURLString, g_empty_string);
SetSecurityOrigin(SecurityOrigin::CreateUnique());
InitContentSecurityPolicy();
SetFeaturePolicy(g_empty_string);
return;
}
EnforceSandboxFlags(initializer.GetSandboxFlags());
SetInsecureRequestPolicy(initializer.GetInsecureRequestPolicy());
if (initializer.InsecureNavigationsToUpgrade()) {
for (auto to_upgrade : *initializer.InsecureNavigationsToUpgrade())
AddInsecureNavigationUpgrade(to_upgrade);
}
if (IsSandboxed(kSandboxOrigin)) {
cookie_url_ = url_;
SetSecurityOrigin(SecurityOrigin::CreateUnique());
Document* owner = initializer.OwnerDocument();
if (owner) {
if (owner->GetSecurityOrigin()->IsPotentiallyTrustworthy())
GetSecurityOrigin()->SetUniqueOriginIsPotentiallyTrustworthy(true);
if (owner->GetSecurityOrigin()->CanLoadLocalResources())
GetSecurityOrigin()->GrantLoadLocalResources();
}
} else if (Document* owner = initializer.OwnerDocument()) {
cookie_url_ = owner->CookieURL();
SetSecurityOrigin(owner->GetSecurityOrigin());
} else {
cookie_url_ = url_;
SetSecurityOrigin(SecurityOrigin::Create(url_));
}
if (initializer.IsHostedInReservedIPRange()) {
SetAddressSpace(GetSecurityOrigin()->IsLocalhost()
? kWebAddressSpaceLocal
: kWebAddressSpacePrivate);
} else if (GetSecurityOrigin()->IsLocal()) {
SetAddressSpace(kWebAddressSpaceLocal);
} else {
SetAddressSpace(kWebAddressSpacePublic);
}
if (ImportsController()) {
SetContentSecurityPolicy(
ImportsController()->Master()->GetContentSecurityPolicy());
} else {
InitContentSecurityPolicy();
}
if (GetSecurityOrigin()->HasSuborigin())
EnforceSuborigin(*GetSecurityOrigin()->GetSuborigin());
if (Settings* settings = initializer.GetSettings()) {
if (!settings->GetWebSecurityEnabled()) {
GetSecurityOrigin()->GrantUniversalAccess();
} else if (GetSecurityOrigin()->IsLocal()) {
if (settings->GetAllowUniversalAccessFromFileURLs()) {
GetSecurityOrigin()->GrantUniversalAccess();
} else if (!settings->GetAllowFileAccessFromFileURLs()) {
GetSecurityOrigin()->BlockLocalAccessFromLocalOrigin();
}
}
}
if (GetSecurityOrigin()->IsUnique() &&
SecurityOrigin::Create(url_)->IsPotentiallyTrustworthy())
GetSecurityOrigin()->SetUniqueOriginIsPotentiallyTrustworthy(true);
if (GetSecurityOrigin()->HasSuborigin())
EnforceSuborigin(*GetSecurityOrigin()->GetSuborigin());
SetFeaturePolicy(g_empty_string);
}
Commit Message: Inherit CSP when we inherit the security origin
This prevents attacks that use main window navigation to get out of the
existing csp constraints such as the related bug
Bug: 747847
Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8
Reviewed-on: https://chromium-review.googlesource.com/592027
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492333}
CWE ID: CWE-732 | void Document::InitSecurityContext(const DocumentInit& initializer) {
DCHECK(!GetSecurityOrigin());
if (!initializer.HasSecurityContext()) {
cookie_url_ = KURL(kParsedURLString, g_empty_string);
SetSecurityOrigin(SecurityOrigin::CreateUnique());
InitContentSecurityPolicy();
SetFeaturePolicy(g_empty_string);
return;
}
EnforceSandboxFlags(initializer.GetSandboxFlags());
SetInsecureRequestPolicy(initializer.GetInsecureRequestPolicy());
if (initializer.InsecureNavigationsToUpgrade()) {
for (auto to_upgrade : *initializer.InsecureNavigationsToUpgrade())
AddInsecureNavigationUpgrade(to_upgrade);
}
ContentSecurityPolicy* policy_to_inherit = nullptr;
if (IsSandboxed(kSandboxOrigin)) {
cookie_url_ = url_;
SetSecurityOrigin(SecurityOrigin::CreateUnique());
Document* owner = initializer.OwnerDocument();
if (owner) {
if (owner->GetSecurityOrigin()->IsPotentiallyTrustworthy())
GetSecurityOrigin()->SetUniqueOriginIsPotentiallyTrustworthy(true);
if (owner->GetSecurityOrigin()->CanLoadLocalResources())
GetSecurityOrigin()->GrantLoadLocalResources();
policy_to_inherit = owner->GetContentSecurityPolicy();
}
} else if (Document* owner = initializer.OwnerDocument()) {
cookie_url_ = owner->CookieURL();
SetSecurityOrigin(owner->GetSecurityOrigin());
policy_to_inherit = owner->GetContentSecurityPolicy();
} else {
cookie_url_ = url_;
SetSecurityOrigin(SecurityOrigin::Create(url_));
}
if (initializer.IsHostedInReservedIPRange()) {
SetAddressSpace(GetSecurityOrigin()->IsLocalhost()
? kWebAddressSpaceLocal
: kWebAddressSpacePrivate);
} else if (GetSecurityOrigin()->IsLocal()) {
SetAddressSpace(kWebAddressSpaceLocal);
} else {
SetAddressSpace(kWebAddressSpacePublic);
}
if (ImportsController()) {
SetContentSecurityPolicy(
ImportsController()->Master()->GetContentSecurityPolicy());
} else {
InitContentSecurityPolicy(nullptr, policy_to_inherit);
}
if (GetSecurityOrigin()->HasSuborigin())
EnforceSuborigin(*GetSecurityOrigin()->GetSuborigin());
if (Settings* settings = initializer.GetSettings()) {
if (!settings->GetWebSecurityEnabled()) {
GetSecurityOrigin()->GrantUniversalAccess();
} else if (GetSecurityOrigin()->IsLocal()) {
if (settings->GetAllowUniversalAccessFromFileURLs()) {
GetSecurityOrigin()->GrantUniversalAccess();
} else if (!settings->GetAllowFileAccessFromFileURLs()) {
GetSecurityOrigin()->BlockLocalAccessFromLocalOrigin();
}
}
}
if (GetSecurityOrigin()->IsUnique() &&
SecurityOrigin::Create(url_)->IsPotentiallyTrustworthy())
GetSecurityOrigin()->SetUniqueOriginIsPotentiallyTrustworthy(true);
if (GetSecurityOrigin()->HasSuborigin())
EnforceSuborigin(*GetSecurityOrigin()->GetSuborigin());
SetFeaturePolicy(g_empty_string);
}
| 172,300 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: T1_Get_Private_Dict( T1_Parser parser,
PSAux_Service psaux )
{
FT_Stream stream = parser->stream;
FT_Memory memory = parser->root.memory;
FT_Error error = FT_Err_Ok;
FT_ULong size;
if ( parser->in_pfb )
{
/* in the case of the PFB format, the private dictionary can be */
/* made of several segments. We thus first read the number of */
/* segments to compute the total size of the private dictionary */
/* then re-read them into memory. */
FT_ULong start_pos = FT_STREAM_POS();
FT_UShort tag;
parser->private_len = 0;
for (;;)
{
error = read_pfb_tag( stream, &tag, &size );
if ( error )
goto Fail;
if ( tag != 0x8002U )
break;
parser->private_len += size;
if ( FT_STREAM_SKIP( size ) )
goto Fail;
}
/* Check that we have a private dictionary there */
/* and allocate private dictionary buffer */
if ( parser->private_len == 0 )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" invalid private dictionary section\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
if ( FT_STREAM_SEEK( start_pos ) ||
FT_ALLOC( parser->private_dict, parser->private_len ) )
goto Fail;
parser->private_len = 0;
for (;;)
{
error = read_pfb_tag( stream, &tag, &size );
if ( error || tag != 0x8002U )
{
error = FT_Err_Ok;
break;
}
if ( FT_STREAM_READ( parser->private_dict + parser->private_len,
size ) )
goto Fail;
parser->private_len += size;
}
}
else
{
/* We have already `loaded' the whole PFA font file into memory; */
/* if this is a memory resource, allocate a new block to hold */
/* the private dict. Otherwise, simply overwrite into the base */
/* dictionary block in the heap. */
/* first of all, look at the `eexec' keyword */
FT_Byte* cur = parser->base_dict;
FT_Byte* limit = cur + parser->base_len;
FT_Byte c;
FT_Pointer pos_lf;
FT_Bool test_cr;
Again:
for (;;)
{
c = cur[0];
if ( c == 'e' && cur + 9 < limit ) /* 9 = 5 letters for `eexec' + */
/* whitespace + 4 chars */
{
if ( cur[1] == 'e' &&
cur[2] == 'x' &&
cur[3] == 'e' &&
cur[4] == 'c' )
break;
}
cur++;
if ( cur >= limit )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" could not find `eexec' keyword\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
}
/* check whether `eexec' was real -- it could be in a comment */
/* or string (as e.g. in u003043t.gsf from ghostscript) */
parser->root.cursor = parser->base_dict;
/* set limit to `eexec' + whitespace + 4 characters */
parser->root.limit = cur + 10;
cur = parser->root.cursor;
limit = parser->root.limit;
while ( cur < limit )
{
if ( *cur == 'e' && ft_strncmp( (char*)cur, "eexec", 5 ) == 0 )
goto Found;
T1_Skip_PS_Token( parser );
if ( parser->root.error )
break;
T1_Skip_Spaces ( parser );
cur = parser->root.cursor;
}
/* we haven't found the correct `eexec'; go back and continue */
/* searching */
cur = limit;
limit = parser->base_dict + parser->base_len;
goto Again;
/* now determine where to write the _encrypted_ binary private */
/* According to the Type 1 spec, the first cipher byte must not be */
/* an ASCII whitespace character code (blank, tab, carriage return */
/* or line feed). We have seen Type 1 fonts with two line feed */
/* characters... So skip now all whitespace character codes. */
/* */
/* On the other hand, Adobe's Type 1 parser handles fonts just */
/* fine that are violating this limitation, so we add a heuristic */
/* test to stop at \r only if it is not used for EOL. */
pos_lf = ft_memchr( cur, '\n', (size_t)( limit - cur ) );
test_cr = FT_BOOL( !pos_lf ||
pos_lf > ft_memchr( cur,
'\r',
(size_t)( limit - cur ) ) );
while ( cur < limit &&
( *cur == ' ' ||
*cur == '\t' ||
(test_cr && *cur == '\r' ) ||
*cur == '\n' ) )
++cur;
if ( cur >= limit )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" `eexec' not properly terminated\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
size = parser->base_len - (FT_ULong)( cur - parser->base_dict );
if ( parser->in_memory )
{
/* note that we allocate one more byte to put a terminating `0' */
if ( FT_ALLOC( parser->private_dict, size + 1 ) )
goto Fail;
parser->private_len = size;
}
else
{
parser->single_block = 1;
parser->private_dict = parser->base_dict;
parser->private_len = size;
parser->base_dict = NULL;
parser->base_len = 0;
}
/* now determine whether the private dictionary is encoded in binary */
/* or hexadecimal ASCII format -- decode it accordingly */
/* we need to access the next 4 bytes (after the final whitespace */
/* following the `eexec' keyword); if they all are hexadecimal */
/* digits, then we have a case of ASCII storage */
if ( cur + 3 < limit &&
ft_isxdigit( cur[0] ) && ft_isxdigit( cur[1] ) &&
ft_isxdigit( cur[2] ) && ft_isxdigit( cur[3] ) )
{
/* ASCII hexadecimal encoding */
FT_ULong len;
parser->root.cursor = cur;
(void)psaux->ps_parser_funcs->to_bytes( &parser->root,
parser->private_dict,
parser->private_len,
&len,
0 );
parser->private_len = len;
/* put a safeguard */
parser->private_dict[len] = '\0';
}
else
/* binary encoding -- copy the private dict */
FT_MEM_MOVE( parser->private_dict, cur, size );
}
/* we now decrypt the encoded binary private dictionary */
psaux->t1_decrypt( parser->private_dict, parser->private_len, 55665U );
if ( parser->private_len < 4 )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" invalid private dictionary section\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* replace the four random bytes at the beginning with whitespace */
parser->private_dict[0] = ' ';
parser->private_dict[1] = ' ';
parser->private_dict[2] = ' ';
parser->private_dict[3] = ' ';
parser->root.base = parser->private_dict;
parser->root.cursor = parser->private_dict;
parser->root.limit = parser->root.cursor + parser->private_len;
Fail:
Exit:
return error;
}
Commit Message:
CWE ID: CWE-125 | T1_Get_Private_Dict( T1_Parser parser,
PSAux_Service psaux )
{
FT_Stream stream = parser->stream;
FT_Memory memory = parser->root.memory;
FT_Error error = FT_Err_Ok;
FT_ULong size;
if ( parser->in_pfb )
{
/* in the case of the PFB format, the private dictionary can be */
/* made of several segments. We thus first read the number of */
/* segments to compute the total size of the private dictionary */
/* then re-read them into memory. */
FT_ULong start_pos = FT_STREAM_POS();
FT_UShort tag;
parser->private_len = 0;
for (;;)
{
error = read_pfb_tag( stream, &tag, &size );
if ( error )
goto Fail;
if ( tag != 0x8002U )
break;
parser->private_len += size;
if ( FT_STREAM_SKIP( size ) )
goto Fail;
}
/* Check that we have a private dictionary there */
/* and allocate private dictionary buffer */
if ( parser->private_len == 0 )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" invalid private dictionary section\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
if ( FT_STREAM_SEEK( start_pos ) ||
FT_ALLOC( parser->private_dict, parser->private_len ) )
goto Fail;
parser->private_len = 0;
for (;;)
{
error = read_pfb_tag( stream, &tag, &size );
if ( error || tag != 0x8002U )
{
error = FT_Err_Ok;
break;
}
if ( FT_STREAM_READ( parser->private_dict + parser->private_len,
size ) )
goto Fail;
parser->private_len += size;
}
}
else
{
/* We have already `loaded' the whole PFA font file into memory; */
/* if this is a memory resource, allocate a new block to hold */
/* the private dict. Otherwise, simply overwrite into the base */
/* dictionary block in the heap. */
/* first of all, look at the `eexec' keyword */
FT_Byte* cur = parser->base_dict;
FT_Byte* limit = cur + parser->base_len;
FT_Byte c;
FT_Pointer pos_lf;
FT_Bool test_cr;
Again:
for (;;)
{
c = cur[0];
if ( c == 'e' && cur + 9 < limit ) /* 9 = 5 letters for `eexec' + */
/* whitespace + 4 chars */
{
if ( cur[1] == 'e' &&
cur[2] == 'x' &&
cur[3] == 'e' &&
cur[4] == 'c' )
break;
}
cur++;
if ( cur >= limit )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" could not find `eexec' keyword\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
}
/* check whether `eexec' was real -- it could be in a comment */
/* or string (as e.g. in u003043t.gsf from ghostscript) */
parser->root.cursor = parser->base_dict;
/* set limit to `eexec' + whitespace + 4 characters */
parser->root.limit = cur + 10;
cur = parser->root.cursor;
limit = parser->root.limit;
while ( cur < limit )
{
if ( *cur == 'e' && ft_strncmp( (char*)cur, "eexec", 5 ) == 0 )
goto Found;
T1_Skip_PS_Token( parser );
if ( parser->root.error )
break;
T1_Skip_Spaces ( parser );
cur = parser->root.cursor;
}
/* we haven't found the correct `eexec'; go back and continue */
/* searching */
cur = limit;
limit = parser->base_dict + parser->base_len;
if ( cur >= limit )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" premature end in private dictionary\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
goto Again;
/* now determine where to write the _encrypted_ binary private */
/* According to the Type 1 spec, the first cipher byte must not be */
/* an ASCII whitespace character code (blank, tab, carriage return */
/* or line feed). We have seen Type 1 fonts with two line feed */
/* characters... So skip now all whitespace character codes. */
/* */
/* On the other hand, Adobe's Type 1 parser handles fonts just */
/* fine that are violating this limitation, so we add a heuristic */
/* test to stop at \r only if it is not used for EOL. */
pos_lf = ft_memchr( cur, '\n', (size_t)( limit - cur ) );
test_cr = FT_BOOL( !pos_lf ||
pos_lf > ft_memchr( cur,
'\r',
(size_t)( limit - cur ) ) );
while ( cur < limit &&
( *cur == ' ' ||
*cur == '\t' ||
(test_cr && *cur == '\r' ) ||
*cur == '\n' ) )
++cur;
if ( cur >= limit )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" `eexec' not properly terminated\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
size = parser->base_len - (FT_ULong)( cur - parser->base_dict );
if ( parser->in_memory )
{
/* note that we allocate one more byte to put a terminating `0' */
if ( FT_ALLOC( parser->private_dict, size + 1 ) )
goto Fail;
parser->private_len = size;
}
else
{
parser->single_block = 1;
parser->private_dict = parser->base_dict;
parser->private_len = size;
parser->base_dict = NULL;
parser->base_len = 0;
}
/* now determine whether the private dictionary is encoded in binary */
/* or hexadecimal ASCII format -- decode it accordingly */
/* we need to access the next 4 bytes (after the final whitespace */
/* following the `eexec' keyword); if they all are hexadecimal */
/* digits, then we have a case of ASCII storage */
if ( cur + 3 < limit &&
ft_isxdigit( cur[0] ) && ft_isxdigit( cur[1] ) &&
ft_isxdigit( cur[2] ) && ft_isxdigit( cur[3] ) )
{
/* ASCII hexadecimal encoding */
FT_ULong len;
parser->root.cursor = cur;
(void)psaux->ps_parser_funcs->to_bytes( &parser->root,
parser->private_dict,
parser->private_len,
&len,
0 );
parser->private_len = len;
/* put a safeguard */
parser->private_dict[len] = '\0';
}
else
/* binary encoding -- copy the private dict */
FT_MEM_MOVE( parser->private_dict, cur, size );
}
/* we now decrypt the encoded binary private dictionary */
psaux->t1_decrypt( parser->private_dict, parser->private_len, 55665U );
if ( parser->private_len < 4 )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" invalid private dictionary section\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* replace the four random bytes at the beginning with whitespace */
parser->private_dict[0] = ' ';
parser->private_dict[1] = ' ';
parser->private_dict[2] = ' ';
parser->private_dict[3] = ' ';
parser->root.base = parser->private_dict;
parser->root.cursor = parser->private_dict;
parser->root.limit = parser->root.cursor + parser->private_len;
Fail:
Exit:
return error;
}
| 165,428 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 sendTouchEvent(BlackBerry::Platform::TouchEvent::Type type)
{
BlackBerry::Platform::TouchEvent event;
event.m_type = type;
event.m_points.assign(touches.begin(), touches.end());
BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->touchEvent(event);
Vector<BlackBerry::Platform::TouchPoint> t;
for (Vector<BlackBerry::Platform::TouchPoint>::iterator it = touches.begin(); it != touches.end(); ++it) {
if (it->m_state != BlackBerry::Platform::TouchPoint::TouchReleased) {
it->m_state = BlackBerry::Platform::TouchPoint::TouchStationary;
t.append(*it);
}
}
touches = t;
}
Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API
https://bugs.webkit.org/show_bug.cgi?id=105143
RIM PR 171941
Reviewed by Rob Buis.
Internally reviewed by George Staikos.
Source/WebCore:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit.
Also adapt to new method names and encapsulation of TouchPoint data
members.
No change in behavior, no new tests.
* platform/blackberry/PlatformTouchPointBlackBerry.cpp:
(WebCore::PlatformTouchPoint::PlatformTouchPoint):
Source/WebKit/blackberry:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit. One exception
is when passing events to a full screen plugin.
Also adapt to new method names and encapsulation of TouchPoint data
members.
* Api/WebPage.cpp:
(BlackBerry::WebKit::WebPage::touchEvent):
(BlackBerry::WebKit::WebPage::touchPointAsMouseEvent):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin):
* WebKitSupport/InputHandler.cpp:
(BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint):
* WebKitSupport/InputHandler.h:
(InputHandler):
* WebKitSupport/TouchEventHandler.cpp:
(BlackBerry::WebKit::TouchEventHandler::doFatFingers):
(BlackBerry::WebKit::TouchEventHandler::handleTouchPoint):
* WebKitSupport/TouchEventHandler.h:
(TouchEventHandler):
Tools:
Adapt to new method names and encapsulation of TouchPoint data members.
* DumpRenderTree/blackberry/EventSender.cpp:
(addTouchPointCallback):
(updateTouchPointCallback):
(touchEndCallback):
(releaseTouchPointCallback):
(sendTouchEvent):
git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void sendTouchEvent(BlackBerry::Platform::TouchEvent::Type type)
{
BlackBerry::Platform::TouchEvent event;
event.m_type = type;
event.m_points.assign(touches.begin(), touches.end());
BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->touchEvent(event);
Vector<BlackBerry::Platform::TouchPoint> t;
for (Vector<BlackBerry::Platform::TouchPoint>::iterator it = touches.begin(); it != touches.end(); ++it) {
if (it->state() != BlackBerry::Platform::TouchPoint::TouchReleased) {
it->updateState(BlackBerry::Platform::TouchPoint::TouchStationary);
t.append(*it);
}
}
touches = t;
}
| 170,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: int main(int argc, char *argv[])
{
int32_t ret = GPMF_OK;
GPMF_stream metadata_stream, *ms = &metadata_stream;
double metadatalength;
uint32_t *payload = NULL; //buffer to store GPMF samples from the MP4.
if (argc != 2)
{
printf("usage: %s <file_with_GPMF>\n", argv[0]);
return -1;
}
size_t mp4 = OpenMP4Source(argv[1], MOV_GPMF_TRAK_TYPE, MOV_GPMF_TRAK_SUBTYPE);
metadatalength = GetDuration(mp4);
if (metadatalength > 0.0)
{
uint32_t index, payloads = GetNumberPayloads(mp4);
#if 1
if (payloads == 1) // Printf the contents of the single payload
{
uint32_t payloadsize = GetPayloadSize(mp4,0);
payload = GetPayload(mp4, payload, 0);
if(payload == NULL)
goto cleanup;
ret = GPMF_Init(ms, payload, payloadsize);
if (ret != GPMF_OK)
goto cleanup;
ret = GPMF_Validate(ms, GPMF_RECURSE_LEVELS); // optional
if (GPMF_OK != ret)
{
printf("Invalid Structure\n");
goto cleanup;
}
GPMF_ResetState(ms);
do
{
PrintGPMF(ms); // printf current GPMF KLV
} while (GPMF_OK == GPMF_Next(ms, GPMF_RECURSE_LEVELS));
GPMF_ResetState(ms);
printf("\n");
}
#endif
for (index = 0; index < payloads; index++)
{
uint32_t payloadsize = GetPayloadSize(mp4, index);
float in = 0.0, out = 0.0; //times
payload = GetPayload(mp4, payload, index);
if (payload == NULL)
goto cleanup;
ret = GetPayloadTime(mp4, index, &in, &out);
if (ret != GPMF_OK)
goto cleanup;
ret = GPMF_Init(ms, payload, payloadsize);
if (ret != GPMF_OK)
goto cleanup;
#if 1 // Find all the available Streams and the data carrying FourCC
if (index == 0) // show first payload
{
ret = GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS);
while (GPMF_OK == ret)
{
ret = GPMF_SeekToSamples(ms);
if (GPMF_OK == ret) //find the last FOURCC within the stream
{
uint32_t key = GPMF_Key(ms);
GPMF_SampleType type = GPMF_Type(ms);
uint32_t elements = GPMF_ElementsInStruct(ms);
uint32_t samples = GPMF_PayloadSampleCount(ms);
if (samples)
{
printf(" STRM of %c%c%c%c ", PRINTF_4CC(key));
if (type == GPMF_TYPE_COMPLEX)
{
GPMF_stream find_stream;
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_CURRENT_LEVEL))
{
char tmp[64];
char *data = (char *)GPMF_RawData(&find_stream);
int size = GPMF_RawDataSize(&find_stream);
if (size < sizeof(tmp))
{
memcpy(tmp, data, size);
tmp[size] = 0;
printf("of type %s ", tmp);
}
}
}
else
{
printf("of type %c ", type);
}
printf("with %d sample%s ", samples, samples > 1 ? "s" : "");
if (elements > 1)
printf("-- %d elements per sample", elements);
printf("\n");
}
ret = GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS);
}
else
{
if (ret == GPMF_ERROR_BAD_STRUCTURE) // some payload element was corrupt, skip to the next valid GPMF KLV at the previous level.
{
ret = GPMF_Next(ms, GPMF_CURRENT_LEVEL); // this will be the next stream if any more are present.
}
}
}
GPMF_ResetState(ms);
printf("\n");
}
#endif
#if 1 // Find GPS values and return scaled doubles.
if (index == 0) // show first payload
{
if (GPMF_OK == GPMF_FindNext(ms, STR2FOURCC("GPS5"), GPMF_RECURSE_LEVELS) || //GoPro Hero5/6/7 GPS
GPMF_OK == GPMF_FindNext(ms, STR2FOURCC("GPRI"), GPMF_RECURSE_LEVELS)) //GoPro Karma GPS
{
uint32_t key = GPMF_Key(ms);
uint32_t samples = GPMF_Repeat(ms);
uint32_t elements = GPMF_ElementsInStruct(ms);
uint32_t buffersize = samples * elements * sizeof(double);
GPMF_stream find_stream;
double *ptr, *tmpbuffer = malloc(buffersize);
char units[10][6] = { "" };
uint32_t unit_samples = 1;
printf("MP4 Payload time %.3f to %.3f seconds\n", in, out);
if (tmpbuffer && samples)
{
uint32_t i, j;
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_SI_UNITS, GPMF_CURRENT_LEVEL) ||
GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_UNITS, GPMF_CURRENT_LEVEL))
{
char *data = (char *)GPMF_RawData(&find_stream);
int ssize = GPMF_StructSize(&find_stream);
unit_samples = GPMF_Repeat(&find_stream);
for (i = 0; i < unit_samples; i++)
{
memcpy(units[i], data, ssize);
units[i][ssize] = 0;
data += ssize;
}
}
GPMF_ScaledData(ms, tmpbuffer, buffersize, 0, samples, GPMF_TYPE_DOUBLE); //Output scaled data as floats
ptr = tmpbuffer;
for (i = 0; i < samples; i++)
{
printf("%c%c%c%c ", PRINTF_4CC(key));
for (j = 0; j < elements; j++)
printf("%.3f%s, ", *ptr++, units[j%unit_samples]);
printf("\n");
}
free(tmpbuffer);
}
}
GPMF_ResetState(ms);
printf("\n");
}
#endif
}
#if 1
while (GPMF_OK == GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS))
{
if (GPMF_OK == GPMF_SeekToSamples(ms)) //find the last FOURCC within the stream
{
uint32_t fourcc = GPMF_Key(ms);
double rate = GetGPMFSampleRate(mp4, fourcc, GPMF_SAMPLE_RATE_PRECISE);// GPMF_SAMPLE_RATE_FAST);
printf("%c%c%c%c sampling rate = %f Hz\n", PRINTF_4CC(fourcc), rate);
}
}
#endif
cleanup:
if (payload) FreePayload(payload); payload = NULL;
CloseSource(mp4);
}
return ret;
}
Commit Message: fixed many security issues with the too crude mp4 reader
CWE ID: CWE-787 | int main(int argc, char *argv[])
{
int32_t ret = GPMF_OK;
GPMF_stream metadata_stream, *ms = &metadata_stream;
double metadatalength;
uint32_t *payload = NULL; //buffer to store GPMF samples from the MP4.
if (argc != 2)
{
printf("usage: %s <file_with_GPMF>\n", argv[0]);
return -1;
}
size_t mp4 = OpenMP4Source(argv[1], MOV_GPMF_TRAK_TYPE, MOV_GPMF_TRAK_SUBTYPE);
if (mp4 == 0)
{
printf("error: %s is an invalid MP4/MOV\n", argv[1]);
return -1;
}
metadatalength = GetDuration(mp4);
if (metadatalength > 0.0)
{
uint32_t index, payloads = GetNumberPayloads(mp4);
#if 1
if (payloads == 1) // Printf the contents of the single payload
{
uint32_t payloadsize = GetPayloadSize(mp4,0);
payload = GetPayload(mp4, payload, 0);
if(payload == NULL)
goto cleanup;
ret = GPMF_Init(ms, payload, payloadsize);
if (ret != GPMF_OK)
goto cleanup;
ret = GPMF_Validate(ms, GPMF_RECURSE_LEVELS); // optional
if (GPMF_OK != ret)
{
printf("Invalid Structure\n");
goto cleanup;
}
GPMF_ResetState(ms);
do
{
PrintGPMF(ms); // printf current GPMF KLV
} while (GPMF_OK == GPMF_Next(ms, GPMF_RECURSE_LEVELS));
GPMF_ResetState(ms);
printf("\n");
}
#endif
for (index = 0; index < payloads; index++)
{
uint32_t payloadsize = GetPayloadSize(mp4, index);
double in = 0.0, out = 0.0; //times
payload = GetPayload(mp4, payload, index);
if (payload == NULL)
goto cleanup;
ret = GetPayloadTime(mp4, index, &in, &out);
if (ret != GPMF_OK)
goto cleanup;
ret = GPMF_Init(ms, payload, payloadsize);
if (ret != GPMF_OK)
goto cleanup;
#if 1 // Find all the available Streams and the data carrying FourCC
if (index == 0) // show first payload
{
ret = GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS);
while (GPMF_OK == ret)
{
ret = GPMF_SeekToSamples(ms);
if (GPMF_OK == ret) //find the last FOURCC within the stream
{
uint32_t key = GPMF_Key(ms);
GPMF_SampleType type = GPMF_Type(ms);
uint32_t elements = GPMF_ElementsInStruct(ms);
uint32_t samples = GPMF_PayloadSampleCount(ms);
if (samples)
{
printf(" STRM of %c%c%c%c ", PRINTF_4CC(key));
if (type == GPMF_TYPE_COMPLEX)
{
GPMF_stream find_stream;
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_CURRENT_LEVEL))
{
char tmp[64];
char *data = (char *)GPMF_RawData(&find_stream);
int size = GPMF_RawDataSize(&find_stream);
if (size < sizeof(tmp))
{
memcpy(tmp, data, size);
tmp[size] = 0;
printf("of type %s ", tmp);
}
}
}
else
{
printf("of type %c ", type);
}
printf("with %d sample%s ", samples, samples > 1 ? "s" : "");
if (elements > 1)
printf("-- %d elements per sample", elements);
printf("\n");
}
ret = GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS);
}
else
{
if (ret == GPMF_ERROR_BAD_STRUCTURE) // some payload element was corrupt, skip to the next valid GPMF KLV at the previous level.
{
ret = GPMF_Next(ms, GPMF_CURRENT_LEVEL); // this will be the next stream if any more are present.
}
}
}
GPMF_ResetState(ms);
printf("\n");
}
#endif
#if 1 // Find GPS values and return scaled doubles.
if (index == 0) // show first payload
{
if (GPMF_OK == GPMF_FindNext(ms, STR2FOURCC("GPS5"), GPMF_RECURSE_LEVELS) || //GoPro Hero5/6/7 GPS
GPMF_OK == GPMF_FindNext(ms, STR2FOURCC("GPRI"), GPMF_RECURSE_LEVELS)) //GoPro Karma GPS
{
uint32_t key = GPMF_Key(ms);
uint32_t samples = GPMF_Repeat(ms);
uint32_t elements = GPMF_ElementsInStruct(ms);
uint32_t buffersize = samples * elements * sizeof(double);
GPMF_stream find_stream;
double *ptr, *tmpbuffer = malloc(buffersize);
char units[10][6] = { "" };
uint32_t unit_samples = 1;
printf("MP4 Payload time %.3f to %.3f seconds\n", in, out);
if (tmpbuffer && samples)
{
uint32_t i, j;
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_SI_UNITS, GPMF_CURRENT_LEVEL) ||
GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_UNITS, GPMF_CURRENT_LEVEL))
{
char *data = (char *)GPMF_RawData(&find_stream);
int ssize = GPMF_StructSize(&find_stream);
unit_samples = GPMF_Repeat(&find_stream);
for (i = 0; i < unit_samples; i++)
{
memcpy(units[i], data, ssize);
units[i][ssize] = 0;
data += ssize;
}
}
GPMF_ScaledData(ms, tmpbuffer, buffersize, 0, samples, GPMF_TYPE_DOUBLE); //Output scaled data as floats
ptr = tmpbuffer;
for (i = 0; i < samples; i++)
{
printf("%c%c%c%c ", PRINTF_4CC(key));
for (j = 0; j < elements; j++)
printf("%.3f%s, ", *ptr++, units[j%unit_samples]);
printf("\n");
}
free(tmpbuffer);
}
}
GPMF_ResetState(ms);
printf("\n");
}
#endif
}
#if 1
while (GPMF_OK == GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS))
{
if (GPMF_OK == GPMF_SeekToSamples(ms)) //find the last FOURCC within the stream
{
double in = 0.0, out = 0.0;
uint32_t fourcc = GPMF_Key(ms);
double rate = GetGPMFSampleRate(mp4, fourcc, GPMF_SAMPLE_RATE_PRECISE, &in, &out);// GPMF_SAMPLE_RATE_FAST);
printf("%c%c%c%c sampling rate = %f Hz (from %f to %f)\n", PRINTF_4CC(fourcc), rate, in, out);
}
}
#endif
cleanup:
if (payload) FreePayload(payload); payload = NULL;
CloseSource(mp4);
}
return ret;
}
| 169,545 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 BnOMX::onTransact(
uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
switch (code) {
case LIVES_LOCALLY:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
pid_t pid = (pid_t)data.readInt32();
reply->writeInt32(livesLocally(node, pid));
return OK;
}
case LIST_NODES:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
List<ComponentInfo> list;
listNodes(&list);
reply->writeInt32(list.size());
for (List<ComponentInfo>::iterator it = list.begin();
it != list.end(); ++it) {
ComponentInfo &cur = *it;
reply->writeString8(cur.mName);
reply->writeInt32(cur.mRoles.size());
for (List<String8>::iterator role_it = cur.mRoles.begin();
role_it != cur.mRoles.end(); ++role_it) {
reply->writeString8(*role_it);
}
}
return NO_ERROR;
}
case ALLOCATE_NODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
const char *name = data.readCString();
sp<IOMXObserver> observer =
interface_cast<IOMXObserver>(data.readStrongBinder());
node_id node;
status_t err = allocateNode(name, observer, &node);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)node);
}
return NO_ERROR;
}
case FREE_NODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
reply->writeInt32(freeNode(node));
return NO_ERROR;
}
case SEND_COMMAND:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_COMMANDTYPE cmd =
static_cast<OMX_COMMANDTYPE>(data.readInt32());
OMX_S32 param = data.readInt32();
reply->writeInt32(sendCommand(node, cmd, param));
return NO_ERROR;
}
case GET_PARAMETER:
case SET_PARAMETER:
case GET_CONFIG:
case SET_CONFIG:
case SET_INTERNAL_OPTION:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32());
size_t size = data.readInt64();
status_t err = NOT_ENOUGH_DATA;
void *params = NULL;
size_t pageSize = 0;
size_t allocSize = 0;
if (code != SET_INTERNAL_OPTION && size < 8) {
ALOGE("b/27207275 (%zu)", size);
android_errorWriteLog(0x534e4554, "27207275");
} else {
err = NO_MEMORY;
pageSize = (size_t) sysconf(_SC_PAGE_SIZE);
if (size > SIZE_MAX - (pageSize * 2)) {
ALOGE("requested param size too big");
} else {
allocSize = (size + pageSize * 2) & ~(pageSize - 1);
params = mmap(NULL, allocSize, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1 /* fd */, 0 /* offset */);
}
if (params != MAP_FAILED) {
err = data.read(params, size);
if (err != OK) {
android_errorWriteLog(0x534e4554, "26914474");
} else {
err = NOT_ENOUGH_DATA;
OMX_U32 declaredSize = *(OMX_U32*)params;
if (code != SET_INTERNAL_OPTION && declaredSize > size) {
ALOGE("b/27207275 (%u/%zu)", declaredSize, size);
android_errorWriteLog(0x534e4554, "27207275");
} else {
mprotect((char*)params + allocSize - pageSize, pageSize, PROT_NONE);
switch (code) {
case GET_PARAMETER:
err = getParameter(node, index, params, size);
break;
case SET_PARAMETER:
err = setParameter(node, index, params, size);
break;
case GET_CONFIG:
err = getConfig(node, index, params, size);
break;
case SET_CONFIG:
err = setConfig(node, index, params, size);
break;
case SET_INTERNAL_OPTION:
{
InternalOptionType type =
(InternalOptionType)data.readInt32();
err = setInternalOption(node, index, type, params, size);
break;
}
default:
TRESPASS();
}
}
}
} else {
ALOGE("couldn't map: %s", strerror(errno));
}
}
reply->writeInt32(err);
if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) {
reply->write(params, size);
}
if (params) {
munmap(params, allocSize);
}
params = NULL;
return NO_ERROR;
}
case GET_STATE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_STATETYPE state = OMX_StateInvalid;
status_t err = getState(node, &state);
reply->writeInt32(state);
reply->writeInt32(err);
return NO_ERROR;
}
case ENABLE_GRAPHIC_BUFFERS:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
status_t err = enableGraphicBuffers(node, port_index, enable);
reply->writeInt32(err);
return NO_ERROR;
}
case GET_GRAPHIC_BUFFER_USAGE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_U32 usage = 0;
status_t err = getGraphicBufferUsage(node, port_index, &usage);
reply->writeInt32(err);
reply->writeInt32(usage);
return NO_ERROR;
}
case USE_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IMemory> params =
interface_cast<IMemory>(data.readStrongBinder());
OMX_U32 allottedSize = data.readInt32();
buffer_id buffer;
status_t err = useBuffer(node, port_index, params, &buffer, allottedSize);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case USE_GRAPHIC_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
buffer_id buffer;
status_t err = useGraphicBuffer(
node, port_index, graphicBuffer, &buffer);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case UPDATE_GRAPHIC_BUFFER_IN_META:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
buffer_id buffer = (buffer_id)data.readInt32();
status_t err = updateGraphicBufferInMeta(
node, port_index, graphicBuffer, buffer);
reply->writeInt32(err);
return NO_ERROR;
}
case CREATE_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IGraphicBufferProducer> bufferProducer;
MetadataBufferType type = kMetadataBufferTypeInvalid;
status_t err = createInputSurface(node, port_index, &bufferProducer, &type);
if ((err != OK) && (type == kMetadataBufferTypeInvalid)) {
android_errorWriteLog(0x534e4554, "26324358");
}
reply->writeInt32(type);
reply->writeInt32(err);
if (err == OK) {
reply->writeStrongBinder(IInterface::asBinder(bufferProducer));
}
return NO_ERROR;
}
case CREATE_PERSISTENT_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
sp<IGraphicBufferProducer> bufferProducer;
sp<IGraphicBufferConsumer> bufferConsumer;
status_t err = createPersistentInputSurface(
&bufferProducer, &bufferConsumer);
reply->writeInt32(err);
if (err == OK) {
reply->writeStrongBinder(IInterface::asBinder(bufferProducer));
reply->writeStrongBinder(IInterface::asBinder(bufferConsumer));
}
return NO_ERROR;
}
case SET_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IGraphicBufferConsumer> bufferConsumer =
interface_cast<IGraphicBufferConsumer>(data.readStrongBinder());
MetadataBufferType type = kMetadataBufferTypeInvalid;
status_t err = setInputSurface(node, port_index, bufferConsumer, &type);
if ((err != OK) && (type == kMetadataBufferTypeInvalid)) {
android_errorWriteLog(0x534e4554, "26324358");
}
reply->writeInt32(type);
reply->writeInt32(err);
return NO_ERROR;
}
case SIGNAL_END_OF_INPUT_STREAM:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
status_t err = signalEndOfInputStream(node);
reply->writeInt32(err);
return NO_ERROR;
}
case STORE_META_DATA_IN_BUFFERS:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
MetadataBufferType type = kMetadataBufferTypeInvalid;
status_t err = storeMetaDataInBuffers(node, port_index, enable, &type);
reply->writeInt32(type);
reply->writeInt32(err);
return NO_ERROR;
}
case PREPARE_FOR_ADAPTIVE_PLAYBACK:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
OMX_U32 max_width = data.readInt32();
OMX_U32 max_height = data.readInt32();
status_t err = prepareForAdaptivePlayback(
node, port_index, enable, max_width, max_height);
reply->writeInt32(err);
return NO_ERROR;
}
case CONFIGURE_VIDEO_TUNNEL_MODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL tunneled = (OMX_BOOL)data.readInt32();
OMX_U32 audio_hw_sync = data.readInt32();
native_handle_t *sideband_handle = NULL;
status_t err = configureVideoTunnelMode(
node, port_index, tunneled, audio_hw_sync, &sideband_handle);
reply->writeInt32(err);
if(err == OK){
reply->writeNativeHandle(sideband_handle);
}
return NO_ERROR;
}
case ALLOC_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) {
ALOGE("b/24310423");
reply->writeInt32(INVALID_OPERATION);
return NO_ERROR;
}
size_t size = data.readInt64();
buffer_id buffer;
void *buffer_data;
status_t err = allocateBuffer(
node, port_index, size, &buffer, &buffer_data);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
reply->writeInt64((uintptr_t)buffer_data);
}
return NO_ERROR;
}
case ALLOC_BUFFER_WITH_BACKUP:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IMemory> params =
interface_cast<IMemory>(data.readStrongBinder());
OMX_U32 allottedSize = data.readInt32();
buffer_id buffer;
status_t err = allocateBufferWithBackup(
node, port_index, params, &buffer, allottedSize);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case FREE_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
reply->writeInt32(freeBuffer(node, port_index, buffer));
return NO_ERROR;
}
case FILL_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
bool haveFence = data.readInt32();
int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1;
reply->writeInt32(fillBuffer(node, buffer, fenceFd));
return NO_ERROR;
}
case EMPTY_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
OMX_U32 range_offset = data.readInt32();
OMX_U32 range_length = data.readInt32();
OMX_U32 flags = data.readInt32();
OMX_TICKS timestamp = data.readInt64();
bool haveFence = data.readInt32();
int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1;
reply->writeInt32(emptyBuffer(
node, buffer, range_offset, range_length, flags, timestamp, fenceFd));
return NO_ERROR;
}
case GET_EXTENSION_INDEX:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
const char *parameter_name = data.readCString();
OMX_INDEXTYPE index;
status_t err = getExtensionIndex(node, parameter_name, &index);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32(index);
}
return OK;
}
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
Commit Message: Fix size check for OMX_IndexParamConsumerUsageBits
since it doesn't follow the OMX convention. And remove support
for the kClientNeedsFrameBuffer flag.
Bug: 27207275
Change-Id: Ia2c119e2456ebf9e2f4e1de5104ef9032a212255
CWE ID: CWE-119 | status_t BnOMX::onTransact(
uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
switch (code) {
case LIVES_LOCALLY:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
pid_t pid = (pid_t)data.readInt32();
reply->writeInt32(livesLocally(node, pid));
return OK;
}
case LIST_NODES:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
List<ComponentInfo> list;
listNodes(&list);
reply->writeInt32(list.size());
for (List<ComponentInfo>::iterator it = list.begin();
it != list.end(); ++it) {
ComponentInfo &cur = *it;
reply->writeString8(cur.mName);
reply->writeInt32(cur.mRoles.size());
for (List<String8>::iterator role_it = cur.mRoles.begin();
role_it != cur.mRoles.end(); ++role_it) {
reply->writeString8(*role_it);
}
}
return NO_ERROR;
}
case ALLOCATE_NODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
const char *name = data.readCString();
sp<IOMXObserver> observer =
interface_cast<IOMXObserver>(data.readStrongBinder());
node_id node;
status_t err = allocateNode(name, observer, &node);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)node);
}
return NO_ERROR;
}
case FREE_NODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
reply->writeInt32(freeNode(node));
return NO_ERROR;
}
case SEND_COMMAND:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_COMMANDTYPE cmd =
static_cast<OMX_COMMANDTYPE>(data.readInt32());
OMX_S32 param = data.readInt32();
reply->writeInt32(sendCommand(node, cmd, param));
return NO_ERROR;
}
case GET_PARAMETER:
case SET_PARAMETER:
case GET_CONFIG:
case SET_CONFIG:
case SET_INTERNAL_OPTION:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32());
size_t size = data.readInt64();
status_t err = NOT_ENOUGH_DATA;
void *params = NULL;
size_t pageSize = 0;
size_t allocSize = 0;
if ((index == (OMX_INDEXTYPE) OMX_IndexParamConsumerUsageBits && size < 4) ||
(code != SET_INTERNAL_OPTION && size < 8)) {
ALOGE("b/27207275 (%zu)", size);
android_errorWriteLog(0x534e4554, "27207275");
} else {
err = NO_MEMORY;
pageSize = (size_t) sysconf(_SC_PAGE_SIZE);
if (size > SIZE_MAX - (pageSize * 2)) {
ALOGE("requested param size too big");
} else {
allocSize = (size + pageSize * 2) & ~(pageSize - 1);
params = mmap(NULL, allocSize, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1 /* fd */, 0 /* offset */);
}
if (params != MAP_FAILED) {
err = data.read(params, size);
if (err != OK) {
android_errorWriteLog(0x534e4554, "26914474");
} else {
err = NOT_ENOUGH_DATA;
OMX_U32 declaredSize = *(OMX_U32*)params;
if (code != SET_INTERNAL_OPTION &&
index != (OMX_INDEXTYPE) OMX_IndexParamConsumerUsageBits &&
declaredSize > size) {
ALOGE("b/27207275 (%u/%zu)", declaredSize, size);
android_errorWriteLog(0x534e4554, "27207275");
} else {
mprotect((char*)params + allocSize - pageSize, pageSize, PROT_NONE);
switch (code) {
case GET_PARAMETER:
err = getParameter(node, index, params, size);
break;
case SET_PARAMETER:
err = setParameter(node, index, params, size);
break;
case GET_CONFIG:
err = getConfig(node, index, params, size);
break;
case SET_CONFIG:
err = setConfig(node, index, params, size);
break;
case SET_INTERNAL_OPTION:
{
InternalOptionType type =
(InternalOptionType)data.readInt32();
err = setInternalOption(node, index, type, params, size);
break;
}
default:
TRESPASS();
}
}
}
} else {
ALOGE("couldn't map: %s", strerror(errno));
}
}
reply->writeInt32(err);
if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) {
reply->write(params, size);
}
if (params) {
munmap(params, allocSize);
}
params = NULL;
return NO_ERROR;
}
case GET_STATE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_STATETYPE state = OMX_StateInvalid;
status_t err = getState(node, &state);
reply->writeInt32(state);
reply->writeInt32(err);
return NO_ERROR;
}
case ENABLE_GRAPHIC_BUFFERS:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
status_t err = enableGraphicBuffers(node, port_index, enable);
reply->writeInt32(err);
return NO_ERROR;
}
case GET_GRAPHIC_BUFFER_USAGE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_U32 usage = 0;
status_t err = getGraphicBufferUsage(node, port_index, &usage);
reply->writeInt32(err);
reply->writeInt32(usage);
return NO_ERROR;
}
case USE_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IMemory> params =
interface_cast<IMemory>(data.readStrongBinder());
OMX_U32 allottedSize = data.readInt32();
buffer_id buffer;
status_t err = useBuffer(node, port_index, params, &buffer, allottedSize);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case USE_GRAPHIC_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
buffer_id buffer;
status_t err = useGraphicBuffer(
node, port_index, graphicBuffer, &buffer);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case UPDATE_GRAPHIC_BUFFER_IN_META:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
buffer_id buffer = (buffer_id)data.readInt32();
status_t err = updateGraphicBufferInMeta(
node, port_index, graphicBuffer, buffer);
reply->writeInt32(err);
return NO_ERROR;
}
case CREATE_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IGraphicBufferProducer> bufferProducer;
MetadataBufferType type = kMetadataBufferTypeInvalid;
status_t err = createInputSurface(node, port_index, &bufferProducer, &type);
if ((err != OK) && (type == kMetadataBufferTypeInvalid)) {
android_errorWriteLog(0x534e4554, "26324358");
}
reply->writeInt32(type);
reply->writeInt32(err);
if (err == OK) {
reply->writeStrongBinder(IInterface::asBinder(bufferProducer));
}
return NO_ERROR;
}
case CREATE_PERSISTENT_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
sp<IGraphicBufferProducer> bufferProducer;
sp<IGraphicBufferConsumer> bufferConsumer;
status_t err = createPersistentInputSurface(
&bufferProducer, &bufferConsumer);
reply->writeInt32(err);
if (err == OK) {
reply->writeStrongBinder(IInterface::asBinder(bufferProducer));
reply->writeStrongBinder(IInterface::asBinder(bufferConsumer));
}
return NO_ERROR;
}
case SET_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IGraphicBufferConsumer> bufferConsumer =
interface_cast<IGraphicBufferConsumer>(data.readStrongBinder());
MetadataBufferType type = kMetadataBufferTypeInvalid;
status_t err = setInputSurface(node, port_index, bufferConsumer, &type);
if ((err != OK) && (type == kMetadataBufferTypeInvalid)) {
android_errorWriteLog(0x534e4554, "26324358");
}
reply->writeInt32(type);
reply->writeInt32(err);
return NO_ERROR;
}
case SIGNAL_END_OF_INPUT_STREAM:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
status_t err = signalEndOfInputStream(node);
reply->writeInt32(err);
return NO_ERROR;
}
case STORE_META_DATA_IN_BUFFERS:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
MetadataBufferType type = kMetadataBufferTypeInvalid;
status_t err = storeMetaDataInBuffers(node, port_index, enable, &type);
reply->writeInt32(type);
reply->writeInt32(err);
return NO_ERROR;
}
case PREPARE_FOR_ADAPTIVE_PLAYBACK:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
OMX_U32 max_width = data.readInt32();
OMX_U32 max_height = data.readInt32();
status_t err = prepareForAdaptivePlayback(
node, port_index, enable, max_width, max_height);
reply->writeInt32(err);
return NO_ERROR;
}
case CONFIGURE_VIDEO_TUNNEL_MODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL tunneled = (OMX_BOOL)data.readInt32();
OMX_U32 audio_hw_sync = data.readInt32();
native_handle_t *sideband_handle = NULL;
status_t err = configureVideoTunnelMode(
node, port_index, tunneled, audio_hw_sync, &sideband_handle);
reply->writeInt32(err);
if(err == OK){
reply->writeNativeHandle(sideband_handle);
}
return NO_ERROR;
}
case ALLOC_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) {
ALOGE("b/24310423");
reply->writeInt32(INVALID_OPERATION);
return NO_ERROR;
}
size_t size = data.readInt64();
buffer_id buffer;
void *buffer_data;
status_t err = allocateBuffer(
node, port_index, size, &buffer, &buffer_data);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
reply->writeInt64((uintptr_t)buffer_data);
}
return NO_ERROR;
}
case ALLOC_BUFFER_WITH_BACKUP:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IMemory> params =
interface_cast<IMemory>(data.readStrongBinder());
OMX_U32 allottedSize = data.readInt32();
buffer_id buffer;
status_t err = allocateBufferWithBackup(
node, port_index, params, &buffer, allottedSize);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case FREE_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
reply->writeInt32(freeBuffer(node, port_index, buffer));
return NO_ERROR;
}
case FILL_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
bool haveFence = data.readInt32();
int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1;
reply->writeInt32(fillBuffer(node, buffer, fenceFd));
return NO_ERROR;
}
case EMPTY_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
OMX_U32 range_offset = data.readInt32();
OMX_U32 range_length = data.readInt32();
OMX_U32 flags = data.readInt32();
OMX_TICKS timestamp = data.readInt64();
bool haveFence = data.readInt32();
int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1;
reply->writeInt32(emptyBuffer(
node, buffer, range_offset, range_length, flags, timestamp, fenceFd));
return NO_ERROR;
}
case GET_EXTENSION_INDEX:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
const char *parameter_name = data.readCString();
OMX_INDEXTYPE index;
status_t err = getExtensionIndex(node, parameter_name, &index);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32(index);
}
return OK;
}
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
| 173,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: static struct mnt_namespace *create_mnt_ns(struct vfsmount *m)
{
struct mnt_namespace *new_ns = alloc_mnt_ns(&init_user_ns);
if (!IS_ERR(new_ns)) {
struct mount *mnt = real_mount(m);
mnt->mnt_ns = new_ns;
new_ns->root = mnt;
list_add(&mnt->mnt_list, &new_ns->list);
} else {
mntput(m);
}
return new_ns;
}
Commit Message: mnt: Add a per mount namespace limit on the number of mounts
CAI Qian <[email protected]> pointed out that the semantics
of shared subtrees make it possible to create an exponentially
increasing number of mounts in a mount namespace.
mkdir /tmp/1 /tmp/2
mount --make-rshared /
for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done
Will create create 2^20 or 1048576 mounts, which is a practical problem
as some people have managed to hit this by accident.
As such CVE-2016-6213 was assigned.
Ian Kent <[email protected]> described the situation for autofs users
as follows:
> The number of mounts for direct mount maps is usually not very large because of
> the way they are implemented, large direct mount maps can have performance
> problems. There can be anywhere from a few (likely case a few hundred) to less
> than 10000, plus mounts that have been triggered and not yet expired.
>
> Indirect mounts have one autofs mount at the root plus the number of mounts that
> have been triggered and not yet expired.
>
> The number of autofs indirect map entries can range from a few to the common
> case of several thousand and in rare cases up to between 30000 and 50000. I've
> not heard of people with maps larger than 50000 entries.
>
> The larger the number of map entries the greater the possibility for a large
> number of active mounts so it's not hard to expect cases of a 1000 or somewhat
> more active mounts.
So I am setting the default number of mounts allowed per mount
namespace at 100,000. This is more than enough for any use case I
know of, but small enough to quickly stop an exponential increase
in mounts. Which should be perfect to catch misconfigurations and
malfunctioning programs.
For anyone who needs a higher limit this can be changed by writing
to the new /proc/sys/fs/mount-max sysctl.
Tested-by: CAI Qian <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-400 | static struct mnt_namespace *create_mnt_ns(struct vfsmount *m)
{
struct mnt_namespace *new_ns = alloc_mnt_ns(&init_user_ns);
if (!IS_ERR(new_ns)) {
struct mount *mnt = real_mount(m);
mnt->mnt_ns = new_ns;
new_ns->root = mnt;
new_ns->mounts++;
list_add(&mnt->mnt_list, &new_ns->list);
} else {
mntput(m);
}
return new_ns;
}
| 167,010 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: extract_header_length(uint16_t fc)
{
int len = 0;
switch ((fc >> 10) & 0x3) {
case 0x00:
if (fc & (1 << 6)) /* intra-PAN with none dest addr */
return -1;
break;
case 0x01:
return -1;
case 0x02:
len += 4;
break;
case 0x03:
len += 10;
break;
}
switch ((fc >> 14) & 0x3) {
case 0x00:
break;
case 0x01:
return -1;
case 0x02:
len += 4;
break;
case 0x03:
len += 10;
break;
}
if (fc & (1 << 6)) {
if (len < 2)
return -1;
len -= 2;
}
return len;
}
Commit Message: CVE-2017-13000/IEEE 802.15.4: Add more bounds checks.
While we're at it, add a bunch of macros for the frame control field's
subfields, have the reserved frame types show the frame type value, use
the same code path for processing source and destination addresses
regardless of whether -v was specified (just leave out the addresses in
non-verbose mode), and return the header length in all cases.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add tests using the capture files supplied by the reporter(s).
CWE ID: CWE-125 | extract_header_length(uint16_t fc)
| 170,029 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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::OnUnregisterAgentError(
const std::string& error_name,
const std::string& error_message) {
LOG(WARNING) << object_path_.value() << ": Failed to unregister agent: "
<< error_name << ": " << error_message;
}
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::OnUnregisterAgentError(
| 171,231 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 ChromeMetricsServiceClient::RegisterMetricsServiceProviders() {
PrefService* local_state = g_browser_process->local_state();
metrics_service_->RegisterMetricsProvider(
std::make_unique<SubprocessMetricsProvider>());
#if BUILDFLAG(ENABLE_EXTENSIONS)
metrics_service_->RegisterMetricsProvider(
std::make_unique<ExtensionsMetricsProvider>(metrics_state_manager_));
#endif
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::NetworkMetricsProvider>(
content::CreateNetworkConnectionTrackerAsyncGetter(),
std::make_unique<metrics::NetworkQualityEstimatorProviderImpl>()));
metrics_service_->RegisterMetricsProvider(
std::make_unique<OmniboxMetricsProvider>(
base::Bind(&chrome::IsIncognitoSessionActive)));
metrics_service_->RegisterMetricsProvider(
std::make_unique<ChromeStabilityMetricsProvider>(local_state));
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::GPUMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::ScreenInfoMetricsProvider>());
metrics_service_->RegisterMetricsProvider(CreateFileMetricsProvider(
metrics_state_manager_->IsMetricsReportingEnabled()));
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::DriveMetricsProvider>(
chrome::FILE_LOCAL_STATE));
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::CallStackProfileMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::SamplingMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<translate::TranslateRankerMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::ComponentMetricsProvider>(
g_browser_process->component_updater()));
#if defined(OS_ANDROID)
metrics_service_->RegisterMetricsProvider(
std::make_unique<AndroidMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<PageLoadMetricsProvider>());
#endif // defined(OS_ANDROID)
#if defined(OS_WIN)
metrics_service_->RegisterMetricsProvider(
std::make_unique<GoogleUpdateMetricsProviderWin>());
base::FilePath user_data_dir;
base::FilePath crash_dir;
if (!base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir) ||
!base::PathService::Get(chrome::DIR_CRASH_DUMPS, &crash_dir)) {
user_data_dir = base::FilePath();
crash_dir = base::FilePath();
}
metrics_service_->RegisterMetricsProvider(
std::make_unique<browser_watcher::WatcherMetricsProviderWin>(
chrome::GetBrowserExitCodesRegistryPath(), user_data_dir, crash_dir,
base::Bind(&GetExecutableVersionDetails)));
metrics_service_->RegisterMetricsProvider(
std::make_unique<AntiVirusMetricsProvider>());
#endif // defined(OS_WIN)
#if BUILDFLAG(ENABLE_PLUGINS)
plugin_metrics_provider_ = new PluginMetricsProvider(local_state);
metrics_service_->RegisterMetricsProvider(
std::unique_ptr<metrics::MetricsProvider>(plugin_metrics_provider_));
#endif // BUILDFLAG(ENABLE_PLUGINS)
#if defined(OS_CHROMEOS)
metrics_service_->RegisterMetricsProvider(
std::make_unique<ChromeOSMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<SigninStatusMetricsProviderChromeOS>());
if (metrics::GetMetricsReportingDefaultState(local_state) ==
metrics::EnableMetricsDefault::DEFAULT_UNKNOWN) {
metrics::RecordMetricsReportingDefaultState(
local_state, metrics::EnableMetricsDefault::OPT_OUT);
}
metrics_service_->RegisterMetricsProvider(
std::make_unique<chromeos::PrinterMetricsProvider>());
#endif // defined(OS_CHROMEOS)
#if !defined(OS_CHROMEOS)
metrics_service_->RegisterMetricsProvider(
SigninStatusMetricsProvider::CreateInstance(
std::make_unique<ChromeSigninStatusMetricsProviderDelegate>()));
#endif // !defined(OS_CHROMEOS)
metrics_service_->RegisterMetricsProvider(
std::make_unique<syncer::DeviceCountMetricsProvider>(
base::Bind(&browser_sync::ChromeSyncClient::GetDeviceInfoTrackers)));
metrics_service_->RegisterMetricsProvider(
std::make_unique<HttpsEngagementMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<CertificateReportingMetricsProvider>());
#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
metrics_service_->RegisterMetricsProvider(
std::make_unique<UpgradeMetricsProvider>());
#endif //! defined(OS_ANDROID) && !defined(OS_CHROMEOS)
#if defined(OS_MACOSX)
metrics_service_->RegisterMetricsProvider(
std::make_unique<PowerMetricsProvider>());
#endif
#if BUILDFLAG(ENABLE_CROS_ASSISTANT)
metrics_service_->RegisterMetricsProvider(
std::make_unique<AssistantServiceMetricsProvider>());
#endif // BUILDFLAG(ENABLE_CROS_ASSISTANT)
}
Commit Message: Add CPU metrics provider and Add CPU/GPU provider for UKM.
Bug: 907674
Change-Id: I61b88aeac8d2a7ff81d812fa5a267f48203ec7e2
Reviewed-on: https://chromium-review.googlesource.com/c/1381376
Commit-Queue: Nik Bhagat <[email protected]>
Reviewed-by: Robert Kaplow <[email protected]>
Cr-Commit-Position: refs/heads/master@{#618037}
CWE ID: CWE-79 | void ChromeMetricsServiceClient::RegisterMetricsServiceProviders() {
PrefService* local_state = g_browser_process->local_state();
metrics_service_->RegisterMetricsProvider(
std::make_unique<SubprocessMetricsProvider>());
#if BUILDFLAG(ENABLE_EXTENSIONS)
metrics_service_->RegisterMetricsProvider(
std::make_unique<ExtensionsMetricsProvider>(metrics_state_manager_));
#endif
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::NetworkMetricsProvider>(
content::CreateNetworkConnectionTrackerAsyncGetter(),
std::make_unique<metrics::NetworkQualityEstimatorProviderImpl>()));
metrics_service_->RegisterMetricsProvider(
std::make_unique<OmniboxMetricsProvider>(
base::Bind(&chrome::IsIncognitoSessionActive)));
metrics_service_->RegisterMetricsProvider(
std::make_unique<ChromeStabilityMetricsProvider>(local_state));
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::GPUMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::CPUMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::ScreenInfoMetricsProvider>());
metrics_service_->RegisterMetricsProvider(CreateFileMetricsProvider(
metrics_state_manager_->IsMetricsReportingEnabled()));
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::DriveMetricsProvider>(
chrome::FILE_LOCAL_STATE));
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::CallStackProfileMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::SamplingMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<translate::TranslateRankerMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<metrics::ComponentMetricsProvider>(
g_browser_process->component_updater()));
#if defined(OS_ANDROID)
metrics_service_->RegisterMetricsProvider(
std::make_unique<AndroidMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<PageLoadMetricsProvider>());
#endif // defined(OS_ANDROID)
#if defined(OS_WIN)
metrics_service_->RegisterMetricsProvider(
std::make_unique<GoogleUpdateMetricsProviderWin>());
base::FilePath user_data_dir;
base::FilePath crash_dir;
if (!base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir) ||
!base::PathService::Get(chrome::DIR_CRASH_DUMPS, &crash_dir)) {
user_data_dir = base::FilePath();
crash_dir = base::FilePath();
}
metrics_service_->RegisterMetricsProvider(
std::make_unique<browser_watcher::WatcherMetricsProviderWin>(
chrome::GetBrowserExitCodesRegistryPath(), user_data_dir, crash_dir,
base::Bind(&GetExecutableVersionDetails)));
metrics_service_->RegisterMetricsProvider(
std::make_unique<AntiVirusMetricsProvider>());
#endif // defined(OS_WIN)
#if BUILDFLAG(ENABLE_PLUGINS)
plugin_metrics_provider_ = new PluginMetricsProvider(local_state);
metrics_service_->RegisterMetricsProvider(
std::unique_ptr<metrics::MetricsProvider>(plugin_metrics_provider_));
#endif // BUILDFLAG(ENABLE_PLUGINS)
#if defined(OS_CHROMEOS)
metrics_service_->RegisterMetricsProvider(
std::make_unique<ChromeOSMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<SigninStatusMetricsProviderChromeOS>());
if (metrics::GetMetricsReportingDefaultState(local_state) ==
metrics::EnableMetricsDefault::DEFAULT_UNKNOWN) {
metrics::RecordMetricsReportingDefaultState(
local_state, metrics::EnableMetricsDefault::OPT_OUT);
}
metrics_service_->RegisterMetricsProvider(
std::make_unique<chromeos::PrinterMetricsProvider>());
#endif // defined(OS_CHROMEOS)
#if !defined(OS_CHROMEOS)
metrics_service_->RegisterMetricsProvider(
SigninStatusMetricsProvider::CreateInstance(
std::make_unique<ChromeSigninStatusMetricsProviderDelegate>()));
#endif // !defined(OS_CHROMEOS)
metrics_service_->RegisterMetricsProvider(
std::make_unique<syncer::DeviceCountMetricsProvider>(
base::Bind(&browser_sync::ChromeSyncClient::GetDeviceInfoTrackers)));
metrics_service_->RegisterMetricsProvider(
std::make_unique<HttpsEngagementMetricsProvider>());
metrics_service_->RegisterMetricsProvider(
std::make_unique<CertificateReportingMetricsProvider>());
#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
metrics_service_->RegisterMetricsProvider(
std::make_unique<UpgradeMetricsProvider>());
#endif //! defined(OS_ANDROID) && !defined(OS_CHROMEOS)
#if defined(OS_MACOSX)
metrics_service_->RegisterMetricsProvider(
std::make_unique<PowerMetricsProvider>());
#endif
#if BUILDFLAG(ENABLE_CROS_ASSISTANT)
metrics_service_->RegisterMetricsProvider(
std::make_unique<AssistantServiceMetricsProvider>());
#endif // BUILDFLAG(ENABLE_CROS_ASSISTANT)
}
| 172,070 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: do_page_fault(struct pt_regs *regs, unsigned long error_code)
{
struct vm_area_struct *vma;
struct task_struct *tsk;
unsigned long address;
struct mm_struct *mm;
int fault;
int write = error_code & PF_WRITE;
unsigned int flags = FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE |
(write ? FAULT_FLAG_WRITE : 0);
tsk = current;
mm = tsk->mm;
/* Get the faulting address: */
address = read_cr2();
/*
* Detect and handle instructions that would cause a page fault for
* both a tracked kernel page and a userspace page.
*/
if (kmemcheck_active(regs))
kmemcheck_hide(regs);
prefetchw(&mm->mmap_sem);
if (unlikely(kmmio_fault(regs, address)))
return;
/*
* We fault-in kernel-space virtual memory on-demand. The
* 'reference' page table is init_mm.pgd.
*
* NOTE! We MUST NOT take any locks for this case. We may
* be in an interrupt or a critical region, and should
* only copy the information from the master page table,
* nothing more.
*
* This verifies that the fault happens in kernel space
* (error_code & 4) == 0, and that the fault was not a
* protection error (error_code & 9) == 0.
*/
if (unlikely(fault_in_kernel_space(address))) {
if (!(error_code & (PF_RSVD | PF_USER | PF_PROT))) {
if (vmalloc_fault(address) >= 0)
return;
if (kmemcheck_fault(regs, address, error_code))
return;
}
/* Can handle a stale RO->RW TLB: */
if (spurious_fault(error_code, address))
return;
/* kprobes don't want to hook the spurious faults: */
if (notify_page_fault(regs))
return;
/*
* Don't take the mm semaphore here. If we fixup a prefetch
* fault we could otherwise deadlock:
*/
bad_area_nosemaphore(regs, error_code, address);
return;
}
/* kprobes don't want to hook the spurious faults: */
if (unlikely(notify_page_fault(regs)))
return;
/*
* It's safe to allow irq's after cr2 has been saved and the
* vmalloc fault has been handled.
*
* User-mode registers count as a user access even for any
* potential system fault or CPU buglet:
*/
if (user_mode_vm(regs)) {
local_irq_enable();
error_code |= PF_USER;
} else {
if (regs->flags & X86_EFLAGS_IF)
local_irq_enable();
}
if (unlikely(error_code & PF_RSVD))
pgtable_bad(regs, error_code, address);
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, address);
/*
* If we're in an interrupt, have no user context or are running
* in an atomic region then we must not take the fault:
*/
if (unlikely(in_atomic() || !mm)) {
bad_area_nosemaphore(regs, error_code, address);
return;
}
/*
* When running in the kernel we expect faults to occur only to
* addresses in user space. All other faults represent errors in
* the kernel and should generate an OOPS. Unfortunately, in the
* case of an erroneous fault occurring in a code path which already
* holds mmap_sem we will deadlock attempting to validate the fault
* against the address space. Luckily the kernel only validly
* references user space from well defined areas of code, which are
* listed in the exceptions table.
*
* As the vast majority of faults will be valid we will only perform
* the source reference check when there is a possibility of a
* deadlock. Attempt to lock the address space, if we cannot we then
* validate the source. If this is invalid we can skip the address
* space check, thus avoiding the deadlock:
*/
if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
if ((error_code & PF_USER) == 0 &&
!search_exception_tables(regs->ip)) {
bad_area_nosemaphore(regs, error_code, address);
return;
}
retry:
down_read(&mm->mmap_sem);
} else {
/*
* The above down_read_trylock() might have succeeded in
* which case we'll have missed the might_sleep() from
* down_read():
*/
might_sleep();
}
vma = find_vma(mm, address);
if (unlikely(!vma)) {
bad_area(regs, error_code, address);
return;
}
if (likely(vma->vm_start <= address))
goto good_area;
if (unlikely(!(vma->vm_flags & VM_GROWSDOWN))) {
bad_area(regs, error_code, address);
return;
}
if (error_code & PF_USER) {
/*
* Accessing the stack below %sp is always a bug.
* The large cushion allows instructions like enter
* and pusha to work. ("enter $65535, $31" pushes
* 32 pointers and then decrements %sp by 65535.)
*/
if (unlikely(address + 65536 + 32 * sizeof(unsigned long) < regs->sp)) {
bad_area(regs, error_code, address);
return;
}
}
if (unlikely(expand_stack(vma, address))) {
bad_area(regs, error_code, address);
return;
}
/*
* Ok, we have a good vm_area for this memory access, so
* we can handle it..
*/
good_area:
if (unlikely(access_error(error_code, vma))) {
bad_area_access_error(regs, error_code, address);
return;
}
/*
* If for any reason at all we couldn't handle the fault,
* make sure we exit gracefully rather than endlessly redo
* the fault:
*/
fault = handle_mm_fault(mm, vma, address, flags);
if (unlikely(fault & (VM_FAULT_RETRY|VM_FAULT_ERROR))) {
if (mm_fault_error(regs, error_code, address, fault))
return;
}
/*
* Major/minor page fault accounting is only done on the
* initial attempt. If we go through a retry, it is extremely
* likely that the page will be found in page cache at that point.
*/
if (flags & FAULT_FLAG_ALLOW_RETRY) {
if (fault & VM_FAULT_MAJOR) {
tsk->maj_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0,
regs, address);
} else {
tsk->min_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0,
regs, address);
}
if (fault & VM_FAULT_RETRY) {
/* Clear FAULT_FLAG_ALLOW_RETRY to avoid any risk
* of starvation. */
flags &= ~FAULT_FLAG_ALLOW_RETRY;
goto retry;
}
}
check_v8086_mode(regs, address, tsk);
up_read(&mm->mmap_sem);
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | do_page_fault(struct pt_regs *regs, unsigned long error_code)
{
struct vm_area_struct *vma;
struct task_struct *tsk;
unsigned long address;
struct mm_struct *mm;
int fault;
int write = error_code & PF_WRITE;
unsigned int flags = FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE |
(write ? FAULT_FLAG_WRITE : 0);
tsk = current;
mm = tsk->mm;
/* Get the faulting address: */
address = read_cr2();
/*
* Detect and handle instructions that would cause a page fault for
* both a tracked kernel page and a userspace page.
*/
if (kmemcheck_active(regs))
kmemcheck_hide(regs);
prefetchw(&mm->mmap_sem);
if (unlikely(kmmio_fault(regs, address)))
return;
/*
* We fault-in kernel-space virtual memory on-demand. The
* 'reference' page table is init_mm.pgd.
*
* NOTE! We MUST NOT take any locks for this case. We may
* be in an interrupt or a critical region, and should
* only copy the information from the master page table,
* nothing more.
*
* This verifies that the fault happens in kernel space
* (error_code & 4) == 0, and that the fault was not a
* protection error (error_code & 9) == 0.
*/
if (unlikely(fault_in_kernel_space(address))) {
if (!(error_code & (PF_RSVD | PF_USER | PF_PROT))) {
if (vmalloc_fault(address) >= 0)
return;
if (kmemcheck_fault(regs, address, error_code))
return;
}
/* Can handle a stale RO->RW TLB: */
if (spurious_fault(error_code, address))
return;
/* kprobes don't want to hook the spurious faults: */
if (notify_page_fault(regs))
return;
/*
* Don't take the mm semaphore here. If we fixup a prefetch
* fault we could otherwise deadlock:
*/
bad_area_nosemaphore(regs, error_code, address);
return;
}
/* kprobes don't want to hook the spurious faults: */
if (unlikely(notify_page_fault(regs)))
return;
/*
* It's safe to allow irq's after cr2 has been saved and the
* vmalloc fault has been handled.
*
* User-mode registers count as a user access even for any
* potential system fault or CPU buglet:
*/
if (user_mode_vm(regs)) {
local_irq_enable();
error_code |= PF_USER;
} else {
if (regs->flags & X86_EFLAGS_IF)
local_irq_enable();
}
if (unlikely(error_code & PF_RSVD))
pgtable_bad(regs, error_code, address);
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);
/*
* If we're in an interrupt, have no user context or are running
* in an atomic region then we must not take the fault:
*/
if (unlikely(in_atomic() || !mm)) {
bad_area_nosemaphore(regs, error_code, address);
return;
}
/*
* When running in the kernel we expect faults to occur only to
* addresses in user space. All other faults represent errors in
* the kernel and should generate an OOPS. Unfortunately, in the
* case of an erroneous fault occurring in a code path which already
* holds mmap_sem we will deadlock attempting to validate the fault
* against the address space. Luckily the kernel only validly
* references user space from well defined areas of code, which are
* listed in the exceptions table.
*
* As the vast majority of faults will be valid we will only perform
* the source reference check when there is a possibility of a
* deadlock. Attempt to lock the address space, if we cannot we then
* validate the source. If this is invalid we can skip the address
* space check, thus avoiding the deadlock:
*/
if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
if ((error_code & PF_USER) == 0 &&
!search_exception_tables(regs->ip)) {
bad_area_nosemaphore(regs, error_code, address);
return;
}
retry:
down_read(&mm->mmap_sem);
} else {
/*
* The above down_read_trylock() might have succeeded in
* which case we'll have missed the might_sleep() from
* down_read():
*/
might_sleep();
}
vma = find_vma(mm, address);
if (unlikely(!vma)) {
bad_area(regs, error_code, address);
return;
}
if (likely(vma->vm_start <= address))
goto good_area;
if (unlikely(!(vma->vm_flags & VM_GROWSDOWN))) {
bad_area(regs, error_code, address);
return;
}
if (error_code & PF_USER) {
/*
* Accessing the stack below %sp is always a bug.
* The large cushion allows instructions like enter
* and pusha to work. ("enter $65535, $31" pushes
* 32 pointers and then decrements %sp by 65535.)
*/
if (unlikely(address + 65536 + 32 * sizeof(unsigned long) < regs->sp)) {
bad_area(regs, error_code, address);
return;
}
}
if (unlikely(expand_stack(vma, address))) {
bad_area(regs, error_code, address);
return;
}
/*
* Ok, we have a good vm_area for this memory access, so
* we can handle it..
*/
good_area:
if (unlikely(access_error(error_code, vma))) {
bad_area_access_error(regs, error_code, address);
return;
}
/*
* If for any reason at all we couldn't handle the fault,
* make sure we exit gracefully rather than endlessly redo
* the fault:
*/
fault = handle_mm_fault(mm, vma, address, flags);
if (unlikely(fault & (VM_FAULT_RETRY|VM_FAULT_ERROR))) {
if (mm_fault_error(regs, error_code, address, fault))
return;
}
/*
* Major/minor page fault accounting is only done on the
* initial attempt. If we go through a retry, it is extremely
* likely that the page will be found in page cache at that point.
*/
if (flags & FAULT_FLAG_ALLOW_RETRY) {
if (fault & VM_FAULT_MAJOR) {
tsk->maj_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1,
regs, address);
} else {
tsk->min_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1,
regs, address);
}
if (fault & VM_FAULT_RETRY) {
/* Clear FAULT_FLAG_ALLOW_RETRY to avoid any risk
* of starvation. */
flags &= ~FAULT_FLAG_ALLOW_RETRY;
goto retry;
}
}
check_v8086_mode(regs, address, tsk);
up_read(&mm->mmap_sem);
}
| 165,825 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 TearDownTestCase() {
vpx_free(input_ - 1);
input_ = NULL;
vpx_free(output_);
output_ = NULL;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | static void TearDownTestCase() {
vpx_free(input_ - 1);
input_ = NULL;
vpx_free(output_);
output_ = NULL;
vpx_free(output_ref_);
output_ref_ = NULL;
#if CONFIG_VP9_HIGHBITDEPTH
vpx_free(input16_ - 1);
input16_ = NULL;
vpx_free(output16_);
output16_ = NULL;
vpx_free(output16_ref_);
output16_ref_ = NULL;
#endif
}
| 174,507 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 handle_exception(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct kvm_run *kvm_run = vcpu->run;
u32 intr_info, ex_no, error_code;
unsigned long cr2, rip, dr6;
u32 vect_info;
enum emulation_result er;
vect_info = vmx->idt_vectoring_info;
intr_info = vmx->exit_intr_info;
if (is_machine_check(intr_info))
return handle_machine_check(vcpu);
if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR)
return 1; /* already handled by vmx_vcpu_run() */
if (is_no_device(intr_info)) {
vmx_fpu_activate(vcpu);
return 1;
}
if (is_invalid_opcode(intr_info)) {
if (is_guest_mode(vcpu)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
if (er != EMULATE_DONE)
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
error_code = 0;
if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
/*
* The #PF with PFEC.RSVD = 1 indicates the guest is accessing
* MMIO, it is better to report an internal error.
* See the comments in vmx_handle_exit.
*/
if ((vect_info & VECTORING_INFO_VALID_MASK) &&
!(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
vcpu->run->internal.ndata = 3;
vcpu->run->internal.data[0] = vect_info;
vcpu->run->internal.data[1] = intr_info;
vcpu->run->internal.data[2] = error_code;
return 0;
}
if (is_page_fault(intr_info)) {
/* EPT won't cause page fault directly */
BUG_ON(enable_ept);
cr2 = vmcs_readl(EXIT_QUALIFICATION);
trace_kvm_page_fault(cr2, error_code);
if (kvm_event_needs_reinjection(vcpu))
kvm_mmu_unprotect_page_virt(vcpu, cr2);
return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
}
ex_no = intr_info & INTR_INFO_VECTOR_MASK;
if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
return handle_rmode_exception(vcpu, ex_no, error_code);
switch (ex_no) {
case AC_VECTOR:
kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
return 1;
case DB_VECTOR:
dr6 = vmcs_readl(EXIT_QUALIFICATION);
if (!(vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
vcpu->arch.dr6 &= ~15;
vcpu->arch.dr6 |= dr6 | DR6_RTM;
if (!(dr6 & ~DR6_RESERVED)) /* icebp */
skip_emulated_instruction(vcpu);
kvm_queue_exception(vcpu, DB_VECTOR);
return 1;
}
kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
/* fall through */
case BP_VECTOR:
/*
* Update instruction length as we may reinject #BP from
* user space while in guest debugging mode. Reading it for
* #DB as well causes no harm, it is not used in that case.
*/
vmx->vcpu.arch.event_exit_inst_len =
vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
kvm_run->exit_reason = KVM_EXIT_DEBUG;
rip = kvm_rip_read(vcpu);
kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
kvm_run->debug.arch.exception = ex_no;
break;
default:
kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
kvm_run->ex.exception = ex_no;
kvm_run->ex.error_code = error_code;
break;
}
return 0;
}
Commit Message: kvm: nVMX: Allow L1 to intercept software exceptions (#BP and #OF)
When L2 exits to L0 due to "exception or NMI", software exceptions
(#BP and #OF) for which L1 has requested an intercept should be
handled by L1 rather than L0. Previously, only hardware exceptions
were forwarded to L1.
Signed-off-by: Jim Mattson <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-388 | static int handle_exception(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct kvm_run *kvm_run = vcpu->run;
u32 intr_info, ex_no, error_code;
unsigned long cr2, rip, dr6;
u32 vect_info;
enum emulation_result er;
vect_info = vmx->idt_vectoring_info;
intr_info = vmx->exit_intr_info;
if (is_machine_check(intr_info))
return handle_machine_check(vcpu);
if (is_nmi(intr_info))
return 1; /* already handled by vmx_vcpu_run() */
if (is_no_device(intr_info)) {
vmx_fpu_activate(vcpu);
return 1;
}
if (is_invalid_opcode(intr_info)) {
if (is_guest_mode(vcpu)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
if (er != EMULATE_DONE)
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
error_code = 0;
if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
/*
* The #PF with PFEC.RSVD = 1 indicates the guest is accessing
* MMIO, it is better to report an internal error.
* See the comments in vmx_handle_exit.
*/
if ((vect_info & VECTORING_INFO_VALID_MASK) &&
!(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
vcpu->run->internal.ndata = 3;
vcpu->run->internal.data[0] = vect_info;
vcpu->run->internal.data[1] = intr_info;
vcpu->run->internal.data[2] = error_code;
return 0;
}
if (is_page_fault(intr_info)) {
/* EPT won't cause page fault directly */
BUG_ON(enable_ept);
cr2 = vmcs_readl(EXIT_QUALIFICATION);
trace_kvm_page_fault(cr2, error_code);
if (kvm_event_needs_reinjection(vcpu))
kvm_mmu_unprotect_page_virt(vcpu, cr2);
return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
}
ex_no = intr_info & INTR_INFO_VECTOR_MASK;
if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
return handle_rmode_exception(vcpu, ex_no, error_code);
switch (ex_no) {
case AC_VECTOR:
kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
return 1;
case DB_VECTOR:
dr6 = vmcs_readl(EXIT_QUALIFICATION);
if (!(vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
vcpu->arch.dr6 &= ~15;
vcpu->arch.dr6 |= dr6 | DR6_RTM;
if (!(dr6 & ~DR6_RESERVED)) /* icebp */
skip_emulated_instruction(vcpu);
kvm_queue_exception(vcpu, DB_VECTOR);
return 1;
}
kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
/* fall through */
case BP_VECTOR:
/*
* Update instruction length as we may reinject #BP from
* user space while in guest debugging mode. Reading it for
* #DB as well causes no harm, it is not used in that case.
*/
vmx->vcpu.arch.event_exit_inst_len =
vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
kvm_run->exit_reason = KVM_EXIT_DEBUG;
rip = kvm_rip_read(vcpu);
kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
kvm_run->debug.arch.exception = ex_no;
break;
default:
kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
kvm_run->ex.exception = ex_no;
kvm_run->ex.error_code = error_code;
break;
}
return 0;
}
| 166,854 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 n_tty_ioctl(struct tty_struct *tty, struct file *file,
unsigned int cmd, unsigned long arg)
{
struct n_tty_data *ldata = tty->disc_data;
int retval;
switch (cmd) {
case TIOCOUTQ:
return put_user(tty_chars_in_buffer(tty), (int __user *) arg);
case TIOCINQ:
down_write(&tty->termios_rwsem);
if (L_ICANON(tty))
retval = inq_canon(ldata);
else
retval = read_cnt(ldata);
up_write(&tty->termios_rwsem);
return put_user(retval, (unsigned int __user *) arg);
default:
return n_tty_ioctl_helper(tty, file, cmd, arg);
}
}
Commit Message: n_tty: fix EXTPROC vs ICANON interaction with TIOCINQ (aka FIONREAD)
We added support for EXTPROC back in 2010 in commit 26df6d13406d ("tty:
Add EXTPROC support for LINEMODE") and the intent was to allow it to
override some (all?) ICANON behavior. Quoting from that original commit
message:
There is a new bit in the termios local flag word, EXTPROC.
When this bit is set, several aspects of the terminal driver
are disabled. Input line editing, character echo, and mapping
of signals are all disabled. This allows the telnetd to turn
off these functions when in linemode, but still keep track of
what state the user wants the terminal to be in.
but the problem turns out that "several aspects of the terminal driver
are disabled" is a bit ambiguous, and you can really confuse the n_tty
layer by setting EXTPROC and then causing some of the ICANON invariants
to no longer be maintained.
This fixes at least one such case (TIOCINQ) becoming unhappy because of
the confusion over whether ICANON really means ICANON when EXTPROC is set.
This basically makes TIOCINQ match the case of read: if EXTPROC is set,
we ignore ICANON. Also, make sure to reset the ICANON state ie EXTPROC
changes, not just if ICANON changes.
Fixes: 26df6d13406d ("tty: Add EXTPROC support for LINEMODE")
Reported-by: Tetsuo Handa <[email protected]>
Reported-by: syzkaller <[email protected]>
Cc: Jiri Slaby <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-704 | static int n_tty_ioctl(struct tty_struct *tty, struct file *file,
unsigned int cmd, unsigned long arg)
{
struct n_tty_data *ldata = tty->disc_data;
int retval;
switch (cmd) {
case TIOCOUTQ:
return put_user(tty_chars_in_buffer(tty), (int __user *) arg);
case TIOCINQ:
down_write(&tty->termios_rwsem);
if (L_ICANON(tty) && !L_EXTPROC(tty))
retval = inq_canon(ldata);
else
retval = read_cnt(ldata);
up_write(&tty->termios_rwsem);
return put_user(retval, (unsigned int __user *) arg);
default:
return n_tty_ioctl_helper(tty, file, cmd, arg);
}
}
| 169,009 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: make_transform_image(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type,
png_byte PNG_CONST bit_depth, unsigned int palette_number,
int interlace_type, png_const_charp name)
{
context(ps, fault);
check_interlace_type(interlace_type);
Try
{
png_infop pi;
png_structp pp = set_store_for_write(ps, &pi, name);
png_uint_32 h;
/* In the event of a problem return control to the Catch statement below
* to do the clean up - it is not possible to 'return' directly from a Try
* block.
*/
if (pp == NULL)
Throw ps;
h = transform_height(pp, colour_type, bit_depth);
png_set_IHDR(pp, pi, transform_width(pp, colour_type, bit_depth), h,
bit_depth, colour_type, interlace_type,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
#ifdef PNG_TEXT_SUPPORTED
# if defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED)
# define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_zTXt
# else
# define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_NONE
# endif
{
static char key[] = "image name"; /* must be writeable */
size_t pos;
png_text text;
char copy[FILE_NAME_SIZE];
/* Use a compressed text string to test the correct interaction of text
* compression and IDAT compression.
*/
text.compression = TEXT_COMPRESSION;
text.key = key;
/* Yuck: the text must be writable! */
pos = safecat(copy, sizeof copy, 0, ps->wname);
text.text = copy;
text.text_length = pos;
text.itxt_length = 0;
text.lang = 0;
text.lang_key = 0;
png_set_text(pp, pi, &text, 1);
}
#endif
if (colour_type == 3) /* palette */
init_standard_palette(ps, pp, pi, 1U << bit_depth, 1/*do tRNS*/);
png_write_info(pp, pi);
if (png_get_rowbytes(pp, pi) !=
transform_rowsize(pp, colour_type, bit_depth))
png_error(pp, "row size incorrect");
else
{
/* Somewhat confusingly this must be called *after* png_write_info
* because if it is called before, the information in *pp has not been
* updated to reflect the interlaced image.
*/
int npasses = png_set_interlace_handling(pp);
int pass;
if (npasses != npasses_from_interlace_type(pp, interlace_type))
png_error(pp, "write: png_set_interlace_handling failed");
for (pass=0; pass<npasses; ++pass)
{
png_uint_32 y;
for (y=0; y<h; ++y)
{
png_byte buffer[TRANSFORM_ROWMAX];
transform_row(pp, buffer, colour_type, bit_depth, y);
png_write_row(pp, buffer);
}
}
}
#ifdef PNG_TEXT_SUPPORTED
{
static char key[] = "end marker";
static char comment[] = "end";
png_text text;
/* Use a compressed text string to test the correct interaction of text
* compression and IDAT compression.
*/
text.compression = TEXT_COMPRESSION;
text.key = key;
text.text = comment;
text.text_length = (sizeof comment)-1;
text.itxt_length = 0;
text.lang = 0;
text.lang_key = 0;
png_set_text(pp, pi, &text, 1);
}
#endif
png_write_end(pp, pi);
/* And store this under the appropriate id, then clean up. */
store_storefile(ps, FILEID(colour_type, bit_depth, palette_number,
interlace_type, 0, 0, 0));
store_write_reset(ps);
}
Catch(fault)
{
/* Use the png_store returned by the exception. This may help the compiler
* because 'ps' is not used in this branch of the setjmp. Note that fault
* and ps will always be the same value.
*/
store_write_reset(fault);
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | make_transform_image(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type,
make_transform_image(png_store* const ps, png_byte const colour_type,
png_byte const bit_depth, unsigned int palette_number,
int interlace_type, png_const_charp name)
{
context(ps, fault);
check_interlace_type(interlace_type);
Try
{
png_infop pi;
png_structp pp = set_store_for_write(ps, &pi, name);
png_uint_32 h, w;
/* In the event of a problem return control to the Catch statement below
* to do the clean up - it is not possible to 'return' directly from a Try
* block.
*/
if (pp == NULL)
Throw ps;
w = transform_width(pp, colour_type, bit_depth);
h = transform_height(pp, colour_type, bit_depth);
png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
#ifdef PNG_TEXT_SUPPORTED
# if defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED)
# define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_zTXt
# else
# define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_NONE
# endif
{
static char key[] = "image name"; /* must be writeable */
size_t pos;
png_text text;
char copy[FILE_NAME_SIZE];
/* Use a compressed text string to test the correct interaction of text
* compression and IDAT compression.
*/
text.compression = TEXT_COMPRESSION;
text.key = key;
/* Yuck: the text must be writable! */
pos = safecat(copy, sizeof copy, 0, ps->wname);
text.text = copy;
text.text_length = pos;
text.itxt_length = 0;
text.lang = 0;
text.lang_key = 0;
png_set_text(pp, pi, &text, 1);
}
#endif
if (colour_type == 3) /* palette */
init_standard_palette(ps, pp, pi, 1U << bit_depth, 1/*do tRNS*/);
# ifdef PNG_WRITE_tRNS_SUPPORTED
else if (palette_number)
set_random_tRNS(pp, pi, colour_type, bit_depth);
# endif
png_write_info(pp, pi);
if (png_get_rowbytes(pp, pi) !=
transform_rowsize(pp, colour_type, bit_depth))
png_error(pp, "transform row size incorrect");
else
{
/* Somewhat confusingly this must be called *after* png_write_info
* because if it is called before, the information in *pp has not been
* updated to reflect the interlaced image.
*/
int npasses = set_write_interlace_handling(pp, interlace_type);
int pass;
if (npasses != npasses_from_interlace_type(pp, interlace_type))
png_error(pp, "write: png_set_interlace_handling failed");
for (pass=0; pass<npasses; ++pass)
{
png_uint_32 y;
/* do_own_interlace is a pre-defined boolean (a #define) which is
* set if we have to work out the interlaced rows here.
*/
for (y=0; y<h; ++y)
{
png_byte buffer[TRANSFORM_ROWMAX];
transform_row(pp, buffer, colour_type, bit_depth, y);
# if do_own_interlace
/* If do_own_interlace *and* the image is interlaced we need a
* reduced interlace row; this may be reduced to empty.
*/
if (interlace_type == PNG_INTERLACE_ADAM7)
{
/* The row must not be written if it doesn't exist, notice
* that there are two conditions here, either the row isn't
* ever in the pass or the row would be but isn't wide
* enough to contribute any pixels. In fact the wPass test
* can be used to skip the whole y loop in this case.
*/
if (PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
PNG_PASS_COLS(w, pass) > 0)
interlace_row(buffer, buffer,
bit_size(pp, colour_type, bit_depth), w, pass,
0/*data always bigendian*/);
else
continue;
}
# endif /* do_own_interlace */
png_write_row(pp, buffer);
}
}
}
#ifdef PNG_TEXT_SUPPORTED
{
static char key[] = "end marker";
static char comment[] = "end";
png_text text;
/* Use a compressed text string to test the correct interaction of text
* compression and IDAT compression.
*/
text.compression = TEXT_COMPRESSION;
text.key = key;
text.text = comment;
text.text_length = (sizeof comment)-1;
text.itxt_length = 0;
text.lang = 0;
text.lang_key = 0;
png_set_text(pp, pi, &text, 1);
}
#endif
png_write_end(pp, pi);
/* And store this under the appropriate id, then clean up. */
store_storefile(ps, FILEID(colour_type, bit_depth, palette_number,
interlace_type, 0, 0, 0));
store_write_reset(ps);
}
Catch(fault)
{
/* Use the png_store returned by the exception. This may help the compiler
* because 'ps' is not used in this branch of the setjmp. Note that fault
* and ps will always be the same value.
*/
store_write_reset(fault);
}
}
| 173,665 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 pop_sync_mailbox(struct Context *ctx, int *index_hint)
{
int i, j, ret = 0;
char buf[LONG_STRING];
struct PopData *pop_data = (struct PopData *) ctx->data;
struct Progress progress;
#ifdef USE_HCACHE
header_cache_t *hc = NULL;
#endif
pop_data->check_time = 0;
while (true)
{
if (pop_reconnect(ctx) < 0)
return -1;
mutt_progress_init(&progress, _("Marking messages deleted..."),
MUTT_PROGRESS_MSG, WriteInc, ctx->deleted);
#ifdef USE_HCACHE
hc = pop_hcache_open(pop_data, ctx->path);
#endif
for (i = 0, j = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++)
{
if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->refno != -1)
{
j++;
if (!ctx->quiet)
mutt_progress_update(&progress, j, -1);
snprintf(buf, sizeof(buf), "DELE %d\r\n", ctx->hdrs[i]->refno);
ret = pop_query(pop_data, buf, sizeof(buf));
if (ret == 0)
{
mutt_bcache_del(pop_data->bcache, ctx->hdrs[i]->data);
#ifdef USE_HCACHE
mutt_hcache_delete(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data));
#endif
}
}
#ifdef USE_HCACHE
if (ctx->hdrs[i]->changed)
{
mutt_hcache_store(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data),
ctx->hdrs[i], 0);
}
#endif
}
#ifdef USE_HCACHE
mutt_hcache_close(hc);
#endif
if (ret == 0)
{
mutt_str_strfcpy(buf, "QUIT\r\n", sizeof(buf));
ret = pop_query(pop_data, buf, sizeof(buf));
}
if (ret == 0)
{
pop_data->clear_cache = true;
pop_clear_cache(pop_data);
pop_data->status = POP_DISCONNECTED;
return 0;
}
if (ret == -2)
{
mutt_error("%s", pop_data->err_msg);
return -1;
}
}
}
Commit Message: sanitise cache paths
Co-authored-by: JerikoOne <[email protected]>
CWE ID: CWE-22 | static int pop_sync_mailbox(struct Context *ctx, int *index_hint)
{
int i, j, ret = 0;
char buf[LONG_STRING];
struct PopData *pop_data = (struct PopData *) ctx->data;
struct Progress progress;
#ifdef USE_HCACHE
header_cache_t *hc = NULL;
#endif
pop_data->check_time = 0;
while (true)
{
if (pop_reconnect(ctx) < 0)
return -1;
mutt_progress_init(&progress, _("Marking messages deleted..."),
MUTT_PROGRESS_MSG, WriteInc, ctx->deleted);
#ifdef USE_HCACHE
hc = pop_hcache_open(pop_data, ctx->path);
#endif
for (i = 0, j = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++)
{
if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->refno != -1)
{
j++;
if (!ctx->quiet)
mutt_progress_update(&progress, j, -1);
snprintf(buf, sizeof(buf), "DELE %d\r\n", ctx->hdrs[i]->refno);
ret = pop_query(pop_data, buf, sizeof(buf));
if (ret == 0)
{
mutt_bcache_del(pop_data->bcache, cache_id(ctx->hdrs[i]->data));
#ifdef USE_HCACHE
mutt_hcache_delete(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data));
#endif
}
}
#ifdef USE_HCACHE
if (ctx->hdrs[i]->changed)
{
mutt_hcache_store(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data),
ctx->hdrs[i], 0);
}
#endif
}
#ifdef USE_HCACHE
mutt_hcache_close(hc);
#endif
if (ret == 0)
{
mutt_str_strfcpy(buf, "QUIT\r\n", sizeof(buf));
ret = pop_query(pop_data, buf, sizeof(buf));
}
if (ret == 0)
{
pop_data->clear_cache = true;
pop_clear_cache(pop_data);
pop_data->status = POP_DISCONNECTED;
return 0;
}
if (ret == -2)
{
mutt_error("%s", pop_data->err_msg);
return -1;
}
}
}
| 169,123 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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)
{
int rc;
char p = ' ', numbers = 3, count = 0;
int w = 0, h = 0, v = 255, c = 0;
char buf[256];
FILE *f = NULL;
if (im->data)
return 0;
f = fopen(im->real_file, "rb");
if (!f)
return 0;
/* can't use fgets(), because there might be
* binary data after the header and there
* needn't be a newline before the data, so
* no chance to distinguish between end of buffer
* and a binary 0.
*/
/* read the header info */
rc = 0; /* Error */
c = fgetc(f);
if (c != 'P')
goto quit;
p = fgetc(f);
if (p == '1' || p == '4')
numbers = 2; /* bitimages don't have max value */
if ((p < '1') || (p > '8'))
goto quit;
count = 0;
while (count < numbers)
{
c = fgetc(f);
if (c == EOF)
goto quit;
/* eat whitespace */
while (isspace(c))
c = fgetc(f);
/* if comment, eat that */
if (c == '#')
{
do
c = fgetc(f);
while (c != '\n' && c != EOF);
}
/* no comment -> proceed */
else
{
int i = 0;
/* read numbers */
while (c != EOF && !isspace(c) && (i < 255))
{
buf[i++] = c;
c = fgetc(f);
}
if (i)
{
buf[i] = 0;
count++;
switch (count)
{
/* width */
case 1:
w = atoi(buf);
break;
/* height */
case 2:
h = atoi(buf);
break;
/* max value, only for color and greyscale */
case 3:
v = atoi(buf);
break;
}
}
}
}
if ((v < 0) || (v > 255))
goto quit;
im->w = w;
im->h = h;
if (!IMAGE_DIMENSIONS_OK(w, h))
goto quit;
if (!im->format)
{
if (p == '8')
SET_FLAG(im->flags, F_HAS_ALPHA);
else
UNSET_FLAG(im->flags, F_HAS_ALPHA);
im->format = strdup("pnm");
}
rc = 1; /* Ok */
if (((!im->data) && (im->loader)) || (immediate_load) || (progress))
{
DATA8 *data = NULL; /* for the binary versions */
DATA8 *ptr = NULL;
int *idata = NULL; /* for the ASCII versions */
int *iptr;
char buf2[256];
DATA32 *ptr2;
int i, j, x, y, pl = 0;
char pper = 0;
/* must set the im->data member before callign progress function */
ptr2 = im->data = malloc(w * h * sizeof(DATA32));
if (!im->data)
goto quit_error;
/* start reading the data */
switch (p)
{
case '1': /* ASCII monochrome */
buf[0] = 0;
i = 0;
for (y = 0; y < h; y++)
{
x = 0;
while (x < w)
{
if (!buf[i]) /* fill buffer */
{
if (!fgets(buf, 255, f))
goto quit_error;
i = 0;
}
while (buf[i] && isspace(buf[i]))
i++;
if (buf[i])
{
if (buf[i] == '1')
*ptr2 = 0xff000000;
else if (buf[i] == '0')
*ptr2 = 0xffffffff;
else
goto quit_error;
ptr2++;
i++;
}
}
if (progress &&
do_progress(im, progress, progress_granularity,
&pper, &pl, y))
goto quit_progress;
}
break;
case '2': /* ASCII greyscale */
idata = malloc(sizeof(int) * w);
if (!idata)
goto quit_error;
buf[0] = 0;
i = 0;
j = 0;
for (y = 0; y < h; y++)
{
iptr = idata;
x = 0;
while (x < w)
{
int k;
/* check 4 chars ahead to see if we need to
* fill the buffer */
for (k = 0; k < 4; k++)
{
if (!buf[i + k]) /* fill buffer */
{
if (fseek(f, -k, SEEK_CUR) == -1 ||
!fgets(buf, 255, f))
goto quit_error;
i = 0;
break;
}
}
while (buf[i] && isspace(buf[i]))
i++;
while (buf[i] && !isspace(buf[i]))
buf2[j++] = buf[i++];
if (j)
{
buf2[j] = 0;
*(iptr++) = atoi(buf2);
j = 0;
x++;
}
}
iptr = idata;
if (v == 255)
{
for (x = 0; x < w; x++)
{
*ptr2 =
0xff000000 | (iptr[0] << 16) | (iptr[0] << 8)
| iptr[0];
ptr2++;
iptr++;
}
}
else
{
for (x = 0; x < w; x++)
{
*ptr2 =
0xff000000 |
(((iptr[0] * 255) / v) << 16) |
(((iptr[0] * 255) / v) << 8) |
((iptr[0] * 255) / v);
ptr2++;
iptr++;
}
}
if (progress &&
do_progress(im, progress, progress_granularity,
&pper, &pl, y))
goto quit_progress;
}
break;
case '3': /* ASCII RGB */
idata = malloc(3 * sizeof(int) * w);
if (!idata)
goto quit_error;
buf[0] = 0;
i = 0;
j = 0;
for (y = 0; y < h; y++)
{
int w3 = 3 * w;
iptr = idata;
x = 0;
while (x < w3)
{
int k;
/* check 4 chars ahead to see if we need to
* fill the buffer */
for (k = 0; k < 4; k++)
{
if (!buf[i + k]) /* fill buffer */
{
if (fseek(f, -k, SEEK_CUR) == -1 ||
!fgets(buf, 255, f))
goto quit_error;
i = 0;
break;
}
}
while (buf[i] && isspace(buf[i]))
i++;
while (buf[i] && !isspace(buf[i]))
buf2[j++] = buf[i++];
if (j)
{
buf2[j] = 0;
*(iptr++) = atoi(buf2);
j = 0;
x++;
}
}
iptr = idata;
if (v == 255)
{
for (x = 0; x < w; x++)
{
*ptr2 =
0xff000000 | (iptr[0] << 16) | (iptr[1] << 8)
| iptr[2];
ptr2++;
iptr += 3;
}
}
else
{
for (x = 0; x < w; x++)
{
*ptr2 =
0xff000000 |
(((iptr[0] * 255) / v) << 16) |
(((iptr[1] * 255) / v) << 8) |
((iptr[2] * 255) / v);
ptr2++;
iptr += 3;
}
}
if (progress &&
do_progress(im, progress, progress_granularity,
&pper, &pl, y))
goto quit_progress;
}
break;
case '4': /* binary 1bit monochrome */
data = malloc((w + 7) / 8 * sizeof(DATA8));
if (!data)
goto quit_error;
ptr2 = im->data;
for (y = 0; y < h; y++)
{
if (!fread(data, (w + 7) / 8, 1, f))
goto quit_error;
ptr = data;
for (x = 0; x < w; x += 8)
{
j = (w - x >= 8) ? 8 : w - x;
for (i = 0; i < j; i++)
{
if (ptr[0] & (0x80 >> i))
*ptr2 = 0xff000000;
else
*ptr2 = 0xffffffff;
ptr2++;
}
ptr++;
}
if (progress &&
do_progress(im, progress, progress_granularity,
&pper, &pl, y))
goto quit_progress;
}
break;
case '5': /* binary 8bit grayscale GGGGGGGG */
data = malloc(1 * sizeof(DATA8) * w);
if (!data)
goto quit_error;
ptr2 = im->data;
for (y = 0; y < h; y++)
{
if (!fread(data, w * 1, 1, f))
break;
ptr = data;
if (v == 255)
{
for (x = 0; x < w; x++)
{
*ptr2 =
0xff000000 | (ptr[0] << 16) | (ptr[0] << 8) |
ptr[0];
ptr2++;
ptr++;
}
}
else
{
for (x = 0; x < w; x++)
{
*ptr2 =
0xff000000 |
(((ptr[0] * 255) / v) << 16) |
(((ptr[0] * 255) / v) << 8) |
((ptr[0] * 255) / v);
ptr2++;
ptr++;
}
}
if (progress &&
do_progress(im, progress, progress_granularity,
&pper, &pl, y))
goto quit_progress;
}
break;
case '6': /* 24bit binary RGBRGBRGB */
data = malloc(3 * sizeof(DATA8) * w);
if (!data)
goto quit_error;
ptr2 = im->data;
for (y = 0; y < h; y++)
{
if (!fread(data, w * 3, 1, f))
break;
ptr = data;
if (v == 255)
{
for (x = 0; x < w; x++)
{
*ptr2 =
0xff000000 | (ptr[0] << 16) | (ptr[1] << 8) |
ptr[2];
ptr2++;
ptr += 3;
}
}
else
{
for (x = 0; x < w; x++)
{
*ptr2 =
0xff000000 |
(((ptr[0] * 255) / v) << 16) |
(((ptr[1] * 255) / v) << 8) |
((ptr[2] * 255) / v);
ptr2++;
ptr += 3;
}
}
if (progress &&
do_progress(im, progress, progress_granularity,
&pper, &pl, y))
goto quit_progress;
}
break;
case '7': /* XV's 8bit 332 format */
data = malloc(1 * sizeof(DATA8) * w);
if (!data)
goto quit_error;
ptr2 = im->data;
for (y = 0; y < h; y++)
{
if (!fread(data, w * 1, 1, f))
break;
ptr = data;
for (x = 0; x < w; x++)
{
int r, g, b;
r = (*ptr >> 5) & 0x7;
g = (*ptr >> 2) & 0x7;
b = (*ptr) & 0x3;
*ptr2 =
0xff000000 |
(((r << 21) | (r << 18) | (r << 15)) & 0xff0000) |
(((g << 13) | (g << 10) | (g << 7)) & 0xff00) |
((b << 6) | (b << 4) | (b << 2) | (b << 0));
ptr2++;
ptr++;
}
if (progress &&
do_progress(im, progress, progress_granularity,
&pper, &pl, y))
goto quit_progress;
}
break;
case '8': /* 24bit binary RGBARGBARGBA */
data = malloc(4 * sizeof(DATA8) * w);
if (!data)
goto quit_error;
ptr2 = im->data;
for (y = 0; y < h; y++)
{
if (!fread(data, w * 4, 1, f))
break;
ptr = data;
if (v == 255)
{
for (x = 0; x < w; x++)
{
*ptr2 =
(ptr[3] << 24) | (ptr[0] << 16) |
(ptr[1] << 8) | ptr[2];
ptr2++;
ptr += 4;
}
}
else
{
for (x = 0; x < w; x++)
{
*ptr2 =
(((ptr[3] * 255) / v) << 24) |
(((ptr[0] * 255) / v) << 16) |
(((ptr[1] * 255) / v) << 8) |
((ptr[2] * 255) / v);
ptr2++;
ptr += 4;
}
}
if (progress &&
do_progress(im, progress, progress_granularity,
&pper, &pl, y))
goto quit_progress;
}
break;
default:
quit_error:
rc = 0;
break;
quit_progress:
rc = 2;
break;
}
if (idata)
free(idata);
if (data)
free(data);
}
quit:
fclose(f);
return rc;
}
Commit Message:
CWE ID: CWE-189 | load(ImlibImage * im, ImlibProgressFunction progress,
char progress_granularity, char immediate_load)
{
int rc;
char p = ' ', numbers = 3, count = 0;
int w = 0, h = 0, v = 255, c = 0;
char buf[256];
FILE *f = NULL;
if (im->data)
return 0;
f = fopen(im->real_file, "rb");
if (!f)
return 0;
/* can't use fgets(), because there might be
* binary data after the header and there
* needn't be a newline before the data, so
* no chance to distinguish between end of buffer
* and a binary 0.
*/
/* read the header info */
rc = 0; /* Error */
c = fgetc(f);
if (c != 'P')
goto quit;
p = fgetc(f);
if (p == '1' || p == '4')
numbers = 2; /* bitimages don't have max value */
if ((p < '1') || (p > '8'))
goto quit;
count = 0;
while (count < numbers)
{
c = fgetc(f);
if (c == EOF)
goto quit;
/* eat whitespace */
while (isspace(c))
c = fgetc(f);
/* if comment, eat that */
if (c == '#')
{
do
c = fgetc(f);
while (c != '\n' && c != EOF);
}
/* no comment -> proceed */
else
{
int i = 0;
/* read numbers */
while (c != EOF && !isspace(c) && (i < 255))
{
buf[i++] = c;
c = fgetc(f);
}
if (i)
{
buf[i] = 0;
count++;
switch (count)
{
/* width */
case 1:
w = atoi(buf);
break;
/* height */
case 2:
h = atoi(buf);
break;
/* max value, only for color and greyscale */
case 3:
v = atoi(buf);
break;
}
}
}
}
if ((v < 0) || (v > 255))
goto quit;
im->w = w;
im->h = h;
if (!IMAGE_DIMENSIONS_OK(w, h))
goto quit;
if (!im->format)
{
if (p == '8')
SET_FLAG(im->flags, F_HAS_ALPHA);
else
UNSET_FLAG(im->flags, F_HAS_ALPHA);
im->format = strdup("pnm");
}
rc = 1; /* Ok */
if (((!im->data) && (im->loader)) || (immediate_load) || (progress))
{
DATA8 *data = NULL; /* for the binary versions */
DATA8 *ptr = NULL;
int *idata = NULL; /* for the ASCII versions */
int *iptr;
char buf2[256];
DATA32 *ptr2;
int i, j, x, y, pl = 0;
char pper = 0;
/* must set the im->data member before callign progress function */
ptr2 = im->data = malloc(w * h * sizeof(DATA32));
if (!im->data)
goto quit_error;
/* start reading the data */
switch (p)
{
case '1': /* ASCII monochrome */
buf[0] = 0;
i = 0;
for (y = 0; y < h; y++)
{
x = 0;
while (x < w)
{
if (!buf[i]) /* fill buffer */
{
if (!fgets(buf, 255, f))
goto quit_error;
i = 0;
}
while (buf[i] && isspace(buf[i]))
i++;
if (buf[i])
{
if (buf[i] == '1')
*ptr2 = 0xff000000;
else if (buf[i] == '0')
*ptr2 = 0xffffffff;
else
goto quit_error;
ptr2++;
i++;
}
}
if (progress &&
do_progress(im, progress, progress_granularity,
&pper, &pl, y))
goto quit_progress;
}
break;
case '2': /* ASCII greyscale */
idata = malloc(sizeof(int) * w);
if (!idata)
goto quit_error;
buf[0] = 0;
i = 0;
j = 0;
for (y = 0; y < h; y++)
{
iptr = idata;
x = 0;
while (x < w)
{
int k;
/* check 4 chars ahead to see if we need to
* fill the buffer */
for (k = 0; k < 4; k++)
{
if (!buf[i + k]) /* fill buffer */
{
if (fseek(f, -k, SEEK_CUR) == -1 ||
!fgets(buf, 255, f))
goto quit_error;
i = 0;
break;
}
}
while (buf[i] && isspace(buf[i]))
i++;
while (buf[i] && !isspace(buf[i]))
buf2[j++] = buf[i++];
if (j)
{
buf2[j] = 0;
*(iptr++) = atoi(buf2);
j = 0;
x++;
}
}
iptr = idata;
if (v == 0 || v == 255)
{
for (x = 0; x < w; x++)
{
*ptr2 =
0xff000000 | (iptr[0] << 16) | (iptr[0] << 8)
| iptr[0];
ptr2++;
iptr++;
}
}
else
{
for (x = 0; x < w; x++)
{
*ptr2 =
0xff000000 |
(((iptr[0] * 255) / v) << 16) |
(((iptr[0] * 255) / v) << 8) |
((iptr[0] * 255) / v);
ptr2++;
iptr++;
}
}
if (progress &&
do_progress(im, progress, progress_granularity,
&pper, &pl, y))
goto quit_progress;
}
break;
case '3': /* ASCII RGB */
idata = malloc(3 * sizeof(int) * w);
if (!idata)
goto quit_error;
buf[0] = 0;
i = 0;
j = 0;
for (y = 0; y < h; y++)
{
int w3 = 3 * w;
iptr = idata;
x = 0;
while (x < w3)
{
int k;
/* check 4 chars ahead to see if we need to
* fill the buffer */
for (k = 0; k < 4; k++)
{
if (!buf[i + k]) /* fill buffer */
{
if (fseek(f, -k, SEEK_CUR) == -1 ||
!fgets(buf, 255, f))
goto quit_error;
i = 0;
break;
}
}
while (buf[i] && isspace(buf[i]))
i++;
while (buf[i] && !isspace(buf[i]))
buf2[j++] = buf[i++];
if (j)
{
buf2[j] = 0;
*(iptr++) = atoi(buf2);
j = 0;
x++;
}
}
iptr = idata;
if (v == 0 || v == 255)
{
for (x = 0; x < w; x++)
{
*ptr2 =
0xff000000 | (iptr[0] << 16) | (iptr[1] << 8)
| iptr[2];
ptr2++;
iptr += 3;
}
}
else
{
for (x = 0; x < w; x++)
{
*ptr2 =
0xff000000 |
(((iptr[0] * 255) / v) << 16) |
(((iptr[1] * 255) / v) << 8) |
((iptr[2] * 255) / v);
ptr2++;
iptr += 3;
}
}
if (progress &&
do_progress(im, progress, progress_granularity,
&pper, &pl, y))
goto quit_progress;
}
break;
case '4': /* binary 1bit monochrome */
data = malloc((w + 7) / 8 * sizeof(DATA8));
if (!data)
goto quit_error;
ptr2 = im->data;
for (y = 0; y < h; y++)
{
if (!fread(data, (w + 7) / 8, 1, f))
goto quit_error;
ptr = data;
for (x = 0; x < w; x += 8)
{
j = (w - x >= 8) ? 8 : w - x;
for (i = 0; i < j; i++)
{
if (ptr[0] & (0x80 >> i))
*ptr2 = 0xff000000;
else
*ptr2 = 0xffffffff;
ptr2++;
}
ptr++;
}
if (progress &&
do_progress(im, progress, progress_granularity,
&pper, &pl, y))
goto quit_progress;
}
break;
case '5': /* binary 8bit grayscale GGGGGGGG */
data = malloc(1 * sizeof(DATA8) * w);
if (!data)
goto quit_error;
ptr2 = im->data;
for (y = 0; y < h; y++)
{
if (!fread(data, w * 1, 1, f))
break;
ptr = data;
if (v == 0 || v == 255)
{
for (x = 0; x < w; x++)
{
*ptr2 =
0xff000000 | (ptr[0] << 16) | (ptr[0] << 8) |
ptr[0];
ptr2++;
ptr++;
}
}
else
{
for (x = 0; x < w; x++)
{
*ptr2 =
0xff000000 |
(((ptr[0] * 255) / v) << 16) |
(((ptr[0] * 255) / v) << 8) |
((ptr[0] * 255) / v);
ptr2++;
ptr++;
}
}
if (progress &&
do_progress(im, progress, progress_granularity,
&pper, &pl, y))
goto quit_progress;
}
break;
case '6': /* 24bit binary RGBRGBRGB */
data = malloc(3 * sizeof(DATA8) * w);
if (!data)
goto quit_error;
ptr2 = im->data;
for (y = 0; y < h; y++)
{
if (!fread(data, w * 3, 1, f))
break;
ptr = data;
if (v == 0 || v == 255)
{
for (x = 0; x < w; x++)
{
*ptr2 =
0xff000000 | (ptr[0] << 16) | (ptr[1] << 8) |
ptr[2];
ptr2++;
ptr += 3;
}
}
else
{
for (x = 0; x < w; x++)
{
*ptr2 =
0xff000000 |
(((ptr[0] * 255) / v) << 16) |
(((ptr[1] * 255) / v) << 8) |
((ptr[2] * 255) / v);
ptr2++;
ptr += 3;
}
}
if (progress &&
do_progress(im, progress, progress_granularity,
&pper, &pl, y))
goto quit_progress;
}
break;
case '7': /* XV's 8bit 332 format */
data = malloc(1 * sizeof(DATA8) * w);
if (!data)
goto quit_error;
ptr2 = im->data;
for (y = 0; y < h; y++)
{
if (!fread(data, w * 1, 1, f))
break;
ptr = data;
for (x = 0; x < w; x++)
{
int r, g, b;
r = (*ptr >> 5) & 0x7;
g = (*ptr >> 2) & 0x7;
b = (*ptr) & 0x3;
*ptr2 =
0xff000000 |
(((r << 21) | (r << 18) | (r << 15)) & 0xff0000) |
(((g << 13) | (g << 10) | (g << 7)) & 0xff00) |
((b << 6) | (b << 4) | (b << 2) | (b << 0));
ptr2++;
ptr++;
}
if (progress &&
do_progress(im, progress, progress_granularity,
&pper, &pl, y))
goto quit_progress;
}
break;
case '8': /* 24bit binary RGBARGBARGBA */
data = malloc(4 * sizeof(DATA8) * w);
if (!data)
goto quit_error;
ptr2 = im->data;
for (y = 0; y < h; y++)
{
if (!fread(data, w * 4, 1, f))
break;
ptr = data;
if (v == 0 || v == 255)
{
for (x = 0; x < w; x++)
{
*ptr2 =
(ptr[3] << 24) | (ptr[0] << 16) |
(ptr[1] << 8) | ptr[2];
ptr2++;
ptr += 4;
}
}
else
{
for (x = 0; x < w; x++)
{
*ptr2 =
(((ptr[3] * 255) / v) << 24) |
(((ptr[0] * 255) / v) << 16) |
(((ptr[1] * 255) / v) << 8) |
((ptr[2] * 255) / v);
ptr2++;
ptr += 4;
}
}
if (progress &&
do_progress(im, progress, progress_granularity,
&pper, &pl, y))
goto quit_progress;
}
break;
default:
quit_error:
rc = 0;
break;
quit_progress:
rc = 2;
break;
}
if (idata)
free(idata);
if (data)
free(data);
}
quit:
fclose(f);
return rc;
}
| 165,339 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 BTM_PINCodeReply (BD_ADDR bd_addr, UINT8 res, UINT8 pin_len, UINT8 *p_pin, UINT32 trusted_mask[])
{
tBTM_SEC_DEV_REC *p_dev_rec;
BTM_TRACE_API ("BTM_PINCodeReply(): PairState: %s PairFlags: 0x%02x PinLen:%d Result:%d",
btm_pair_state_descr(btm_cb.pairing_state), btm_cb.pairing_flags, pin_len, res);
/* If timeout already expired or has been canceled, ignore the reply */
if (btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_PIN)
{
BTM_TRACE_WARNING ("BTM_PINCodeReply() - Wrong State: %d", btm_cb.pairing_state);
return;
}
if (memcmp (bd_addr, btm_cb.pairing_bda, BD_ADDR_LEN) != 0)
{
BTM_TRACE_ERROR ("BTM_PINCodeReply() - Wrong BD Addr");
return;
}
if ((p_dev_rec = btm_find_dev (bd_addr)) == NULL)
{
BTM_TRACE_ERROR ("BTM_PINCodeReply() - no dev CB");
return;
}
if ( (pin_len > PIN_CODE_LEN) || (pin_len == 0) || (p_pin == NULL) )
res = BTM_ILLEGAL_VALUE;
if (res != BTM_SUCCESS)
{
/* if peer started dd OR we started dd and pre-fetch pin was not used send negative reply */
if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PEER_STARTED_DD) ||
((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
(btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE)) )
{
/* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed event */
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY;
btsnd_hcic_pin_code_neg_reply (bd_addr);
}
else
{
p_dev_rec->security_required = BTM_SEC_NONE;
btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
}
return;
}
if (trusted_mask)
BTM_SEC_COPY_TRUSTED_DEVICE(trusted_mask, p_dev_rec->trusted_mask);
p_dev_rec->sec_flags |= BTM_SEC_LINK_KEY_AUTHED;
if ( (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
&& (p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE)
&& (btm_cb.security_mode_changed == FALSE) )
{
/* This is start of the dedicated bonding if local device is 2.0 */
btm_cb.pin_code_len = pin_len;
memcpy (btm_cb.pin_code, p_pin, pin_len);
btm_cb.security_mode_changed = TRUE;
#ifdef APPL_AUTH_WRITE_EXCEPTION
if(!(APPL_AUTH_WRITE_EXCEPTION)(p_dev_rec->bd_addr))
#endif
btsnd_hcic_write_auth_enable (TRUE);
btm_cb.acl_disc_reason = 0xff ;
/* if we rejected incoming connection request, we have to wait HCI_Connection_Complete event */
/* before originating */
if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT)
{
BTM_TRACE_WARNING ("BTM_PINCodeReply(): waiting HCI_Connection_Complete after rejected incoming connection");
/* we change state little bit early so btm_sec_connected() will originate connection */
/* when existing ACL link is down completely */
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_PIN_REQ);
}
/* if we already accepted incoming connection from pairing device */
else if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND)
{
BTM_TRACE_WARNING ("BTM_PINCodeReply(): link is connecting so wait pin code request from peer");
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_PIN_REQ);
}
else if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED)
{
btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
p_dev_rec->sec_flags &= ~BTM_SEC_LINK_KEY_AUTHED;
if (btm_cb.api.p_auth_complete_callback)
(*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr, p_dev_rec->dev_class,
p_dev_rec->sec_bd_name, HCI_ERR_AUTH_FAILURE);
}
return;
}
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
btm_cb.acl_disc_reason = HCI_SUCCESS;
#ifdef PORCHE_PAIRING_CONFLICT
BTM_TRACE_EVENT("BTM_PINCodeReply(): Saving pin_len: %d btm_cb.pin_code_len: %d", pin_len, btm_cb.pin_code_len);
/* if this was not pre-fetched, save the PIN */
if (btm_cb.pin_code_len == 0)
memcpy (btm_cb.pin_code, p_pin, pin_len);
btm_cb.pin_code_len_saved = pin_len;
#endif
btsnd_hcic_pin_code_req_reply (bd_addr, pin_len, p_pin);
}
Commit Message: DO NOT MERGE Remove Porsche car-kit pairing workaround
Bug: 26551752
Change-Id: I14c5e3fcda0849874c8a94e48aeb7d09585617e1
CWE ID: CWE-264 | void BTM_PINCodeReply (BD_ADDR bd_addr, UINT8 res, UINT8 pin_len, UINT8 *p_pin, UINT32 trusted_mask[])
{
tBTM_SEC_DEV_REC *p_dev_rec;
BTM_TRACE_API ("BTM_PINCodeReply(): PairState: %s PairFlags: 0x%02x PinLen:%d Result:%d",
btm_pair_state_descr(btm_cb.pairing_state), btm_cb.pairing_flags, pin_len, res);
/* If timeout already expired or has been canceled, ignore the reply */
if (btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_PIN)
{
BTM_TRACE_WARNING ("BTM_PINCodeReply() - Wrong State: %d", btm_cb.pairing_state);
return;
}
if (memcmp (bd_addr, btm_cb.pairing_bda, BD_ADDR_LEN) != 0)
{
BTM_TRACE_ERROR ("BTM_PINCodeReply() - Wrong BD Addr");
return;
}
if ((p_dev_rec = btm_find_dev (bd_addr)) == NULL)
{
BTM_TRACE_ERROR ("BTM_PINCodeReply() - no dev CB");
return;
}
if ( (pin_len > PIN_CODE_LEN) || (pin_len == 0) || (p_pin == NULL) )
res = BTM_ILLEGAL_VALUE;
if (res != BTM_SUCCESS)
{
/* if peer started dd OR we started dd and pre-fetch pin was not used send negative reply */
if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PEER_STARTED_DD) ||
((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
(btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE)) )
{
/* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed event */
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY;
btsnd_hcic_pin_code_neg_reply (bd_addr);
}
else
{
p_dev_rec->security_required = BTM_SEC_NONE;
btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
}
return;
}
if (trusted_mask)
BTM_SEC_COPY_TRUSTED_DEVICE(trusted_mask, p_dev_rec->trusted_mask);
p_dev_rec->sec_flags |= BTM_SEC_LINK_KEY_AUTHED;
if ( (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD)
&& (p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE)
&& (btm_cb.security_mode_changed == FALSE) )
{
/* This is start of the dedicated bonding if local device is 2.0 */
btm_cb.pin_code_len = pin_len;
memcpy (btm_cb.pin_code, p_pin, pin_len);
btm_cb.security_mode_changed = TRUE;
#ifdef APPL_AUTH_WRITE_EXCEPTION
if(!(APPL_AUTH_WRITE_EXCEPTION)(p_dev_rec->bd_addr))
#endif
btsnd_hcic_write_auth_enable (TRUE);
btm_cb.acl_disc_reason = 0xff ;
/* if we rejected incoming connection request, we have to wait HCI_Connection_Complete event */
/* before originating */
if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT)
{
BTM_TRACE_WARNING ("BTM_PINCodeReply(): waiting HCI_Connection_Complete after rejected incoming connection");
/* we change state little bit early so btm_sec_connected() will originate connection */
/* when existing ACL link is down completely */
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_PIN_REQ);
}
/* if we already accepted incoming connection from pairing device */
else if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND)
{
BTM_TRACE_WARNING ("BTM_PINCodeReply(): link is connecting so wait pin code request from peer");
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_PIN_REQ);
}
else if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED)
{
btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE);
p_dev_rec->sec_flags &= ~BTM_SEC_LINK_KEY_AUTHED;
if (btm_cb.api.p_auth_complete_callback)
(*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr, p_dev_rec->dev_class,
p_dev_rec->sec_bd_name, HCI_ERR_AUTH_FAILURE);
}
return;
}
btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
btm_cb.acl_disc_reason = HCI_SUCCESS;
btsnd_hcic_pin_code_req_reply (bd_addr, pin_len, p_pin);
}
| 173,901 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: create_response(const char *nurl, const char *method, unsigned int *rp_code)
{
char *page, *fpath;
struct MHD_Response *resp = NULL;
if (!strncmp(nurl, URL_BASE_API_1_1, strlen(URL_BASE_API_1_1))) {
resp = create_response_api(nurl, method, rp_code);
} else {
fpath = get_path(nurl, server_data.www_dir);
resp = create_response_file(nurl, method, rp_code, fpath);
free(fpath);
}
}
Commit Message:
CWE ID: CWE-22 | create_response(const char *nurl, const char *method, unsigned int *rp_code)
{
char *page, *fpath, *rpath;
struct MHD_Response *resp = NULL;
int n;
if (!strncmp(nurl, URL_BASE_API_1_1, strlen(URL_BASE_API_1_1))) {
resp = create_response_api(nurl, method, rp_code);
} else {
fpath = get_path(nurl, server_data.www_dir);
rpath = realpath(fpath, NULL);
if (rpath) {
n = strlen(server_data.www_dir);
if (!strncmp(server_data.www_dir, rpath, n))
resp = create_response_file(nurl,
method,
rp_code,
fpath);
free(rpath);
}
free(fpath);
}
}
| 165,509 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: mldv2_report_print(netdissect_options *ndo, const u_char *bp, u_int len)
{
const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp;
u_int group, nsrcs, ngroups;
u_int i, j;
/* Minimum len is 8 */
if (len < 8) {
ND_PRINT((ndo," [invalid len %d]", len));
return;
}
ND_TCHECK(icp->icmp6_data16[1]);
ngroups = EXTRACT_16BITS(&icp->icmp6_data16[1]);
ND_PRINT((ndo,", %d group record(s)", ngroups));
if (ndo->ndo_vflag > 0) {
/* Print the group records */
group = 8;
for (i = 0; i < ngroups; i++) {
/* type(1) + auxlen(1) + numsrc(2) + grp(16) */
if (len < group + 20) {
ND_PRINT((ndo," [invalid number of groups]"));
return;
}
ND_TCHECK2(bp[group + 4], sizeof(struct in6_addr));
ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[group + 4])));
ND_PRINT((ndo," %s", tok2str(mldv2report2str, " [v2-report-#%d]",
bp[group])));
nsrcs = (bp[group + 2] << 8) + bp[group + 3];
/* Check the number of sources and print them */
if (len < group + 20 + (nsrcs * sizeof(struct in6_addr))) {
ND_PRINT((ndo," [invalid number of sources %d]", nsrcs));
return;
}
if (ndo->ndo_vflag == 1)
ND_PRINT((ndo,", %d source(s)", nsrcs));
else {
/* Print the sources */
ND_PRINT((ndo," {"));
for (j = 0; j < nsrcs; j++) {
ND_TCHECK2(bp[group + 20 + j * sizeof(struct in6_addr)],
sizeof(struct in6_addr));
ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[group + 20 + j * sizeof(struct in6_addr)])));
}
ND_PRINT((ndo," }"));
}
/* Next group record */
group += 20 + nsrcs * sizeof(struct in6_addr);
ND_PRINT((ndo,"]"));
}
}
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
return;
}
Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check
Moreover:
Add and use *_tstr[] strings.
Update four tests outputs accordingly.
Fix a space.
Wang Junjie of 360 ESG Codesafe Team had independently identified this
vulnerability in 2018 by means of fuzzing and provided the packet capture
file for the test.
CWE ID: CWE-125 | mldv2_report_print(netdissect_options *ndo, const u_char *bp, u_int len)
{
const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp;
u_int group, nsrcs, ngroups;
u_int i, j;
/* Minimum len is 8 */
if (len < 8) {
ND_PRINT((ndo," [invalid len %d]", len));
return;
}
ND_TCHECK(icp->icmp6_data16[1]);
ngroups = EXTRACT_16BITS(&icp->icmp6_data16[1]);
ND_PRINT((ndo,", %d group record(s)", ngroups));
if (ndo->ndo_vflag > 0) {
/* Print the group records */
group = 8;
for (i = 0; i < ngroups; i++) {
/* type(1) + auxlen(1) + numsrc(2) + grp(16) */
if (len < group + 20) {
ND_PRINT((ndo," [invalid number of groups]"));
return;
}
ND_TCHECK2(bp[group + 4], sizeof(struct in6_addr));
ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[group + 4])));
ND_PRINT((ndo," %s", tok2str(mldv2report2str, " [v2-report-#%d]",
bp[group])));
nsrcs = (bp[group + 2] << 8) + bp[group + 3];
/* Check the number of sources and print them */
if (len < group + 20 + (nsrcs * sizeof(struct in6_addr))) {
ND_PRINT((ndo," [invalid number of sources %d]", nsrcs));
return;
}
if (ndo->ndo_vflag == 1)
ND_PRINT((ndo,", %d source(s)", nsrcs));
else {
/* Print the sources */
ND_PRINT((ndo," {"));
for (j = 0; j < nsrcs; j++) {
ND_TCHECK2(bp[group + 20 + j * sizeof(struct in6_addr)],
sizeof(struct in6_addr));
ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[group + 20 + j * sizeof(struct in6_addr)])));
}
ND_PRINT((ndo," }"));
}
/* Next group record */
group += 20 + nsrcs * sizeof(struct in6_addr);
ND_PRINT((ndo,"]"));
}
}
return;
trunc:
ND_PRINT((ndo, "%s", mldv2_tstr));
return;
}
| 169,827 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 SetImeConfig(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
if (!IBusConnectionsAreAlive()) {
LOG(ERROR) << "SetImeConfig: IBus connection is not alive";
return false;
}
bool is_preload_engines = false;
std::vector<std::string> string_list;
if ((value.type == ImeConfigValue::kValueTypeStringList) &&
(section == kGeneralSectionName) &&
(config_name == kPreloadEnginesConfigName)) {
FilterInputMethods(value.string_list_value, &string_list);
is_preload_engines = true;
} else {
string_list = value.string_list_value;
}
GVariant* variant = NULL;
switch (value.type) {
case ImeConfigValue::kValueTypeString:
variant = g_variant_new_string(value.string_value.c_str());
break;
case ImeConfigValue::kValueTypeInt:
variant = g_variant_new_int32(value.int_value);
break;
case ImeConfigValue::kValueTypeBool:
variant = g_variant_new_boolean(value.bool_value);
break;
case ImeConfigValue::kValueTypeStringList:
GVariantBuilder variant_builder;
g_variant_builder_init(&variant_builder, G_VARIANT_TYPE("as"));
const size_t size = string_list.size(); // don't use string_list_value.
for (size_t i = 0; i < size; ++i) {
g_variant_builder_add(&variant_builder, "s", string_list[i].c_str());
}
variant = g_variant_builder_end(&variant_builder);
break;
}
if (!variant) {
LOG(ERROR) << "SetImeConfig: variant is NULL";
return false;
}
DCHECK(g_variant_is_floating(variant));
ibus_config_set_value_async(ibus_config_,
section.c_str(),
config_name.c_str(),
variant,
-1, // use the default ibus timeout
NULL, // cancellable
SetImeConfigCallback,
g_object_ref(ibus_config_));
if (is_preload_engines) {
DLOG(INFO) << "SetImeConfig: " << section << "/" << config_name
<< ": " << value.ToString();
}
return true;
}
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 | bool SetImeConfig(const std::string& section,
// IBusController override.
virtual bool SetImeConfig(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
if (!IBusConnectionsAreAlive()) {
LOG(ERROR) << "SetImeConfig: IBus connection is not alive";
return false;
}
bool is_preload_engines = false;
std::vector<std::string> string_list;
if ((value.type == ImeConfigValue::kValueTypeStringList) &&
(section == kGeneralSectionName) &&
(config_name == kPreloadEnginesConfigName)) {
FilterInputMethods(value.string_list_value, &string_list);
is_preload_engines = true;
} else {
string_list = value.string_list_value;
}
GVariant* variant = NULL;
switch (value.type) {
case ImeConfigValue::kValueTypeString:
variant = g_variant_new_string(value.string_value.c_str());
break;
case ImeConfigValue::kValueTypeInt:
variant = g_variant_new_int32(value.int_value);
break;
case ImeConfigValue::kValueTypeBool:
variant = g_variant_new_boolean(value.bool_value);
break;
case ImeConfigValue::kValueTypeStringList:
GVariantBuilder variant_builder;
g_variant_builder_init(&variant_builder, G_VARIANT_TYPE("as"));
const size_t size = string_list.size(); // don't use string_list_value.
for (size_t i = 0; i < size; ++i) {
g_variant_builder_add(&variant_builder, "s", string_list[i].c_str());
}
variant = g_variant_builder_end(&variant_builder);
break;
}
if (!variant) {
LOG(ERROR) << "SetImeConfig: variant is NULL";
return false;
}
DCHECK(g_variant_is_floating(variant));
ibus_config_set_value_async(ibus_config_,
section.c_str(),
config_name.c_str(),
variant,
-1, // use the default ibus timeout
NULL, // cancellable
SetImeConfigCallback,
g_object_ref(ibus_config_));
if (is_preload_engines) {
VLOG(1) << "SetImeConfig: " << section << "/" << config_name
<< ": " << value.ToString();
}
return true;
}
| 170,547 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int read_public_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = file->size;
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_public_key(p, keysize, rsa);
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415 | static int read_public_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = MIN(file->size, sizeof buf);
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_public_key(p, keysize, rsa);
}
| 169,081 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xfs_attr_rmtval_get(
struct xfs_da_args *args)
{
struct xfs_bmbt_irec map[ATTR_RMTVALUE_MAPSIZE];
struct xfs_mount *mp = args->dp->i_mount;
struct xfs_buf *bp;
xfs_dablk_t lblkno = args->rmtblkno;
__uint8_t *dst = args->value;
int valuelen = args->valuelen;
int nmap;
int error;
int blkcnt = args->rmtblkcnt;
int i;
int offset = 0;
trace_xfs_attr_rmtval_get(args);
ASSERT(!(args->flags & ATTR_KERNOVAL));
while (valuelen > 0) {
nmap = ATTR_RMTVALUE_MAPSIZE;
error = xfs_bmapi_read(args->dp, (xfs_fileoff_t)lblkno,
blkcnt, map, &nmap,
XFS_BMAPI_ATTRFORK);
if (error)
return error;
ASSERT(nmap >= 1);
for (i = 0; (i < nmap) && (valuelen > 0); i++) {
xfs_daddr_t dblkno;
int dblkcnt;
ASSERT((map[i].br_startblock != DELAYSTARTBLOCK) &&
(map[i].br_startblock != HOLESTARTBLOCK));
dblkno = XFS_FSB_TO_DADDR(mp, map[i].br_startblock);
dblkcnt = XFS_FSB_TO_BB(mp, map[i].br_blockcount);
error = xfs_trans_read_buf(mp, NULL, mp->m_ddev_targp,
dblkno, dblkcnt, 0, &bp,
&xfs_attr3_rmt_buf_ops);
if (error)
return error;
error = xfs_attr_rmtval_copyout(mp, bp, args->dp->i_ino,
&offset, &valuelen,
&dst);
xfs_buf_relse(bp);
if (error)
return error;
/* roll attribute extent map forwards */
lblkno += map[i].br_blockcount;
blkcnt -= map[i].br_blockcount;
}
}
ASSERT(valuelen == 0);
return 0;
}
Commit Message: xfs: remote attribute overwrite causes transaction overrun
Commit e461fcb ("xfs: remote attribute lookups require the value
length") passes the remote attribute length in the xfs_da_args
structure on lookup so that CRC calculations and validity checking
can be performed correctly by related code. This, unfortunately has
the side effect of changing the args->valuelen parameter in cases
where it shouldn't.
That is, when we replace a remote attribute, the incoming
replacement stores the value and length in args->value and
args->valuelen, but then the lookup which finds the existing remote
attribute overwrites args->valuelen with the length of the remote
attribute being replaced. Hence when we go to create the new
attribute, we create it of the size of the existing remote
attribute, not the size it is supposed to be. When the new attribute
is much smaller than the old attribute, this results in a
transaction overrun and an ASSERT() failure on a debug kernel:
XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331
Fix this by keeping the remote attribute value length separate to
the attribute value length in the xfs_da_args structure. The enables
us to pass the length of the remote attribute to be removed without
overwriting the new attribute's length.
Also, ensure that when we save remote block contexts for a later
rename we zero the original state variables so that we don't confuse
the state of the attribute to be removes with the state of the new
attribute that we just added. [Spotted by Brain Foster.]
Signed-off-by: Dave Chinner <[email protected]>
Reviewed-by: Brian Foster <[email protected]>
Signed-off-by: Dave Chinner <[email protected]>
CWE ID: CWE-19 | xfs_attr_rmtval_get(
struct xfs_da_args *args)
{
struct xfs_bmbt_irec map[ATTR_RMTVALUE_MAPSIZE];
struct xfs_mount *mp = args->dp->i_mount;
struct xfs_buf *bp;
xfs_dablk_t lblkno = args->rmtblkno;
__uint8_t *dst = args->value;
int valuelen;
int nmap;
int error;
int blkcnt = args->rmtblkcnt;
int i;
int offset = 0;
trace_xfs_attr_rmtval_get(args);
ASSERT(!(args->flags & ATTR_KERNOVAL));
ASSERT(args->rmtvaluelen == args->valuelen);
valuelen = args->rmtvaluelen;
while (valuelen > 0) {
nmap = ATTR_RMTVALUE_MAPSIZE;
error = xfs_bmapi_read(args->dp, (xfs_fileoff_t)lblkno,
blkcnt, map, &nmap,
XFS_BMAPI_ATTRFORK);
if (error)
return error;
ASSERT(nmap >= 1);
for (i = 0; (i < nmap) && (valuelen > 0); i++) {
xfs_daddr_t dblkno;
int dblkcnt;
ASSERT((map[i].br_startblock != DELAYSTARTBLOCK) &&
(map[i].br_startblock != HOLESTARTBLOCK));
dblkno = XFS_FSB_TO_DADDR(mp, map[i].br_startblock);
dblkcnt = XFS_FSB_TO_BB(mp, map[i].br_blockcount);
error = xfs_trans_read_buf(mp, NULL, mp->m_ddev_targp,
dblkno, dblkcnt, 0, &bp,
&xfs_attr3_rmt_buf_ops);
if (error)
return error;
error = xfs_attr_rmtval_copyout(mp, bp, args->dp->i_ino,
&offset, &valuelen,
&dst);
xfs_buf_relse(bp);
if (error)
return error;
/* roll attribute extent map forwards */
lblkno += map[i].br_blockcount;
blkcnt -= map[i].br_blockcount;
}
}
ASSERT(valuelen == 0);
return 0;
}
| 166,739 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: tChecksumCheckResult ParaNdis_CheckRxChecksum(
PARANDIS_ADAPTER *pContext,
ULONG virtioFlags,
tCompletePhysicalAddress *pPacketPages,
ULONG ulPacketLength,
ULONG ulDataOffset)
{
tOffloadSettingsFlags f = pContext->Offload.flags;
tChecksumCheckResult res, resIp;
tTcpIpPacketParsingResult ppr;
ULONG flagsToCalculate = 0;
res.value = 0;
resIp.value = 0;
if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only
if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID))
{
if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
{
flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum;
}
else
{
if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum;
if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum;
if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum;
if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum;
}
}
ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__);
if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)
{
pContext->extraStatistics.framesRxCSHwOK++;
ppr.xxpCheckSum = ppresCSOK;
}
if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment)
{
if (f.fRxIPChecksum)
{
res.flags.IpOK = ppr.ipCheckSum == ppresCSOK;
res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad;
}
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPChecksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPChecksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
else if (ppr.ipStatus == ppresIPV6)
{
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPv6Checksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPv6Checksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
return res;
}
Commit Message: NetKVM: BZ#1169718: More rigoruous testing of incoming packet
Signed-off-by: Joseph Hindin <[email protected]>
CWE ID: CWE-20 | tChecksumCheckResult ParaNdis_CheckRxChecksum(
PARANDIS_ADAPTER *pContext,
ULONG virtioFlags,
tCompletePhysicalAddress *pPacketPages,
ULONG ulPacketLength,
ULONG ulDataOffset)
{
tOffloadSettingsFlags f = pContext->Offload.flags;
tChecksumCheckResult res;
tTcpIpPacketParsingResult ppr;
ULONG flagsToCalculate = 0;
res.value = 0;
if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only
if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID))
{
if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
{
flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum;
}
else
{
if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum;
if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum;
if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum;
if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum;
}
}
ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__);
if (ppr.ipCheckSum == ppresIPTooShort || ppr.xxpStatus == ppresXxpIncomplete)
{
res.flags.IpOK = FALSE;
res.flags.IpFailed = TRUE;
return res;
}
if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)
{
pContext->extraStatistics.framesRxCSHwOK++;
ppr.xxpCheckSum = ppresCSOK;
}
if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment)
{
if (f.fRxIPChecksum)
{
res.flags.IpOK = ppr.ipCheckSum == ppresCSOK;
res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad;
}
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPChecksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPChecksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
else if (ppr.ipStatus == ppresIPV6)
{
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPv6Checksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPv6Checksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
return res;
}
| 168,887 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: GDataDirectory* AddDirectory(GDataDirectory* parent,
GDataDirectoryService* directory_service,
int sequence_id) {
GDataDirectory* dir = new GDataDirectory(NULL, directory_service);
const std::string dir_name = "dir" + base::IntToString(sequence_id);
const std::string resource_id = std::string("dir_resource_id:") +
dir_name;
dir->set_title(dir_name);
dir->set_resource_id(resource_id);
GDataFileError error = GDATA_FILE_ERROR_FAILED;
FilePath moved_file_path;
directory_service->MoveEntryToDirectory(
parent->GetFilePath(),
dir,
base::Bind(&test_util::CopyResultsFromFileMoveCallback,
&error,
&moved_file_path));
test_util::RunBlockingPoolTask();
EXPECT_EQ(GDATA_FILE_OK, error);
EXPECT_EQ(parent->GetFilePath().AppendASCII(dir_name), moved_file_path);
return dir;
}
Commit Message: Remove parent* arg from GDataEntry ctor.
* Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry.
* Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry.
* Add GDataDirectoryService::FromDocumentEntry and use this everywhere.
* Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and
CreateGDataDirectory. Make GDataEntry ctor protected.
BUG=141494
TEST=unit tests.
Review URL: https://chromiumcodereview.appspot.com/10854083
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | GDataDirectory* AddDirectory(GDataDirectory* parent,
GDataDirectoryService* directory_service,
int sequence_id) {
GDataDirectory* dir = directory_service->CreateGDataDirectory();
const std::string dir_name = "dir" + base::IntToString(sequence_id);
const std::string resource_id = std::string("dir_resource_id:") +
dir_name;
dir->set_title(dir_name);
dir->set_resource_id(resource_id);
GDataFileError error = GDATA_FILE_ERROR_FAILED;
FilePath moved_file_path;
directory_service->MoveEntryToDirectory(
parent->GetFilePath(),
dir,
base::Bind(&test_util::CopyResultsFromFileMoveCallback,
&error,
&moved_file_path));
test_util::RunBlockingPoolTask();
EXPECT_EQ(GDATA_FILE_OK, error);
EXPECT_EQ(parent->GetFilePath().AppendASCII(dir_name), moved_file_path);
return dir;
}
| 171,494 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParseDocTypeDecl(xmlParserCtxtPtr ctxt) {
const xmlChar *name = NULL;
xmlChar *ExternalID = NULL;
xmlChar *URI = NULL;
/*
* We know that '<!DOCTYPE' has been detected.
*/
SKIP(9);
SKIP_BLANKS;
/*
* Parse the DOCTYPE name.
*/
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseDocTypeDecl : no DOCTYPE name !\n");
}
ctxt->intSubName = name;
SKIP_BLANKS;
/*
* Check for SystemID and ExternalID
*/
URI = xmlParseExternalID(ctxt, &ExternalID, 1);
if ((URI != NULL) || (ExternalID != NULL)) {
ctxt->hasExternalSubset = 1;
}
ctxt->extSubURI = URI;
ctxt->extSubSystem = ExternalID;
SKIP_BLANKS;
/*
* Create and update the internal subset.
*/
if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI);
/*
* Is there any internal subset declarations ?
* they are handled separately in xmlParseInternalSubset()
*/
if (RAW == '[')
return;
/*
* We should be at the end of the DOCTYPE declaration.
*/
if (RAW != '>') {
xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL);
}
NEXT;
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseDocTypeDecl(xmlParserCtxtPtr ctxt) {
const xmlChar *name = NULL;
xmlChar *ExternalID = NULL;
xmlChar *URI = NULL;
/*
* We know that '<!DOCTYPE' has been detected.
*/
SKIP(9);
SKIP_BLANKS;
/*
* Parse the DOCTYPE name.
*/
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseDocTypeDecl : no DOCTYPE name !\n");
}
ctxt->intSubName = name;
SKIP_BLANKS;
/*
* Check for SystemID and ExternalID
*/
URI = xmlParseExternalID(ctxt, &ExternalID, 1);
if ((URI != NULL) || (ExternalID != NULL)) {
ctxt->hasExternalSubset = 1;
}
ctxt->extSubURI = URI;
ctxt->extSubSystem = ExternalID;
SKIP_BLANKS;
/*
* Create and update the internal subset.
*/
if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI);
if (ctxt->instate == XML_PARSER_EOF)
return;
/*
* Is there any internal subset declarations ?
* they are handled separately in xmlParseInternalSubset()
*/
if (RAW == '[')
return;
/*
* We should be at the end of the DOCTYPE declaration.
*/
if (RAW != '>') {
xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL);
}
NEXT;
}
| 171,281 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline signed int ReadPropertyMSBLong(const unsigned char **p,
size_t *length)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
int
c;
register ssize_t
i;
unsigned char
buffer[4];
size_t
value;
if (*length < 4)
return(-1);
for (i=0; i < 4; i++)
{
c=(int) (*(*p)++);
(*length)--;
buffer[i]=(unsigned char) c;
}
value=(size_t) (buffer[0] << 24);
value|=buffer[1] << 16;
value|=buffer[2] << 8;
value|=buffer[3];
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static inline signed int ReadPropertyMSBLong(const unsigned char **p,
size_t *length)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
int
c;
register ssize_t
i;
unsigned char
buffer[4];
unsigned int
value;
if (*length < 4)
return(-1);
for (i=0; i < 4; i++)
{
c=(int) (*(*p)++);
(*length)--;
buffer[i]=(unsigned char) c;
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
| 169,952 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Node::InsertionNotificationRequest HTMLLinkElement::InsertedInto(
ContainerNode& insertion_point) {
HTMLElement::InsertedInto(insertion_point);
LogAddElementIfIsolatedWorldAndInDocument("link", relAttr, hrefAttr);
if (!insertion_point.isConnected())
return kInsertionDone;
DCHECK(isConnected());
if (!ShouldLoadLink() && IsInShadowTree()) {
String message = "HTML element <link> is ignored in shadow tree.";
GetDocument().AddConsoleMessage(ConsoleMessage::Create(
kJSMessageSource, kWarningMessageLevel, message));
return kInsertionDone;
}
GetDocument().GetStyleEngine().AddStyleSheetCandidateNode(*this);
Process();
if (link_)
link_->OwnerInserted();
return kInsertionDone;
}
Commit Message: Avoid crash when setting rel=stylesheet on <link> in shadow root.
Link elements in shadow roots without rel=stylesheet are currently not
added as stylesheet candidates upon insertion. This causes a crash if
rel=stylesheet is set (and then loaded) later.
[email protected]
Bug: 886753
Change-Id: Ia0de2c1edf43407950f973982ee1c262a909d220
Reviewed-on: https://chromium-review.googlesource.com/1242463
Commit-Queue: Anders Ruud <[email protected]>
Reviewed-by: Rune Lillesveen <[email protected]>
Cr-Commit-Position: refs/heads/master@{#593907}
CWE ID: CWE-416 | Node::InsertionNotificationRequest HTMLLinkElement::InsertedInto(
ContainerNode& insertion_point) {
HTMLElement::InsertedInto(insertion_point);
LogAddElementIfIsolatedWorldAndInDocument("link", relAttr, hrefAttr);
if (!insertion_point.isConnected())
return kInsertionDone;
DCHECK(isConnected());
GetDocument().GetStyleEngine().AddStyleSheetCandidateNode(*this);
if (!ShouldLoadLink() && IsInShadowTree()) {
String message = "HTML element <link> is ignored in shadow tree.";
GetDocument().AddConsoleMessage(ConsoleMessage::Create(
kJSMessageSource, kWarningMessageLevel, message));
return kInsertionDone;
}
Process();
if (link_)
link_->OwnerInserted();
return kInsertionDone;
}
| 172,586 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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_process_data(void *user_data, const XML_Char *s, int len)
{
st_entry *ent;
wddx_stack *stack = (wddx_stack *)user_data;
TSRMLS_FETCH();
if (!wddx_stack_is_empty(stack) && !stack->done) {
wddx_stack_top(stack, (void**)&ent);
switch (ent->type) {
case ST_STRING:
if (Z_STRLEN_P(ent->data) == 0) {
STR_FREE(Z_STRVAL_P(ent->data));
Z_STRVAL_P(ent->data) = estrndup(s, len);
Z_STRLEN_P(ent->data) = len;
} else {
Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1);
memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len);
Z_STRLEN_P(ent->data) += len;
Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0';
}
break;
case ST_BINARY:
if (Z_STRLEN_P(ent->data) == 0) {
STR_FREE(Z_STRVAL_P(ent->data));
Z_STRVAL_P(ent->data) = estrndup(s, len + 1);
} else {
Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1);
memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len);
}
Z_STRLEN_P(ent->data) += len;
Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0';
break;
case ST_NUMBER:
Z_TYPE_P(ent->data) = IS_STRING;
Z_STRLEN_P(ent->data) = len;
Z_STRVAL_P(ent->data) = estrndup(s, len);
convert_scalar_to_number(ent->data TSRMLS_CC);
break;
case ST_BOOLEAN:
if (!strcmp(s, "true")) {
Z_LVAL_P(ent->data) = 1;
} else if (!strcmp(s, "false")) {
Z_LVAL_P(ent->data) = 0;
} else {
zval_ptr_dtor(&ent->data);
if (ent->varname) {
efree(ent->varname);
}
ent->data = NULL;
}
break;
case ST_DATETIME: {
char *tmp;
tmp = emalloc(len + 1);
memcpy(tmp, s, len);
tmp[len] = '\0';
Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL);
/* date out of range < 1969 or > 2038 */
if (Z_LVAL_P(ent->data) == -1) {
Z_TYPE_P(ent->data) = IS_STRING;
Z_STRLEN_P(ent->data) = len;
Z_STRVAL_P(ent->data) = estrndup(s, len);
}
efree(tmp);
}
break;
default:
break;
}
}
}
Commit Message: Fix bug #72340: Double Free Courruption in wddx_deserialize
CWE ID: CWE-415 | static void php_wddx_process_data(void *user_data, const XML_Char *s, int len)
{
st_entry *ent;
wddx_stack *stack = (wddx_stack *)user_data;
TSRMLS_FETCH();
if (!wddx_stack_is_empty(stack) && !stack->done) {
wddx_stack_top(stack, (void**)&ent);
switch (ent->type) {
case ST_STRING:
if (Z_STRLEN_P(ent->data) == 0) {
STR_FREE(Z_STRVAL_P(ent->data));
Z_STRVAL_P(ent->data) = estrndup(s, len);
Z_STRLEN_P(ent->data) = len;
} else {
Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1);
memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len);
Z_STRLEN_P(ent->data) += len;
Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0';
}
break;
case ST_BINARY:
if (Z_STRLEN_P(ent->data) == 0) {
STR_FREE(Z_STRVAL_P(ent->data));
Z_STRVAL_P(ent->data) = estrndup(s, len + 1);
} else {
Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1);
memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len);
}
Z_STRLEN_P(ent->data) += len;
Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0';
break;
case ST_NUMBER:
Z_TYPE_P(ent->data) = IS_STRING;
Z_STRLEN_P(ent->data) = len;
Z_STRVAL_P(ent->data) = estrndup(s, len);
convert_scalar_to_number(ent->data TSRMLS_CC);
break;
case ST_BOOLEAN:
if(!ent->data) {
break;
}
if (!strcmp(s, "true")) {
Z_LVAL_P(ent->data) = 1;
} else if (!strcmp(s, "false")) {
Z_LVAL_P(ent->data) = 0;
} else {
zval_ptr_dtor(&ent->data);
if (ent->varname) {
efree(ent->varname);
ent->varname = NULL;
}
ent->data = NULL;
}
break;
case ST_DATETIME: {
char *tmp;
tmp = emalloc(len + 1);
memcpy(tmp, s, len);
tmp[len] = '\0';
Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL);
/* date out of range < 1969 or > 2038 */
if (Z_LVAL_P(ent->data) == -1) {
Z_TYPE_P(ent->data) = IS_STRING;
Z_STRLEN_P(ent->data) = len;
Z_STRVAL_P(ent->data) = estrndup(s, len);
}
efree(tmp);
}
break;
default:
break;
}
}
}
| 167,024 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ProcXFixesCopyRegion(ClientPtr client)
{
RegionPtr pSource, pDestination;
REQUEST(xXFixesCopyRegionReq);
VERIFY_REGION(pSource, stuff->source, client, DixReadAccess);
VERIFY_REGION(pDestination, stuff->destination, client, DixWriteAccess);
if (!RegionCopy(pDestination, pSource))
return BadAlloc;
return Success;
}
Commit Message:
CWE ID: CWE-20 | ProcXFixesCopyRegion(ClientPtr client)
{
RegionPtr pSource, pDestination;
REQUEST(xXFixesCopyRegionReq);
REQUEST_SIZE_MATCH(xXFixesCopyRegionReq);
VERIFY_REGION(pSource, stuff->source, client, DixReadAccess);
VERIFY_REGION(pDestination, stuff->destination, client, DixWriteAccess);
if (!RegionCopy(pDestination, pSource))
return BadAlloc;
return Success;
}
| 165,442 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long do_rt_tgsigqueueinfo(pid_t tgid, pid_t pid, int sig, siginfo_t *info)
{
/* This is only valid for single tasks */
if (pid <= 0 || tgid <= 0)
return -EINVAL;
/* Not even root can pretend to send signals from the kernel.
Nor can they impersonate a kill(), which adds source info. */
if (info->si_code >= 0)
return -EPERM;
info->si_signo = sig;
return do_send_specific(tgid, pid, sig, info);
}
Commit Message: Prevent rt_sigqueueinfo and rt_tgsigqueueinfo from spoofing the signal code
Userland should be able to trust the pid and uid of the sender of a
signal if the si_code is SI_TKILL.
Unfortunately, the kernel has historically allowed sigqueueinfo() to
send any si_code at all (as long as it was negative - to distinguish it
from kernel-generated signals like SIGILL etc), so it could spoof a
SI_TKILL with incorrect siginfo values.
Happily, it looks like glibc has always set si_code to the appropriate
SI_QUEUE, so there are probably no actual user code that ever uses
anything but the appropriate SI_QUEUE flag.
So just tighten the check for si_code (we used to allow any negative
value), and add a (one-time) warning in case there are binaries out
there that might depend on using other si_code values.
Signed-off-by: Julien Tinnes <[email protected]>
Acked-by: Oleg Nesterov <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: | long do_rt_tgsigqueueinfo(pid_t tgid, pid_t pid, int sig, siginfo_t *info)
{
/* This is only valid for single tasks */
if (pid <= 0 || tgid <= 0)
return -EINVAL;
/* Not even root can pretend to send signals from the kernel.
* Nor can they impersonate a kill()/tgkill(), which adds source info.
*/
if (info->si_code != SI_QUEUE) {
/* We used to allow any < 0 si_code */
WARN_ON_ONCE(info->si_code < 0);
return -EPERM;
}
info->si_signo = sig;
return do_send_specific(tgid, pid, sig, info);
}
| 166,232 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 n_tty_set_termios(struct tty_struct *tty, struct ktermios *old)
{
struct n_tty_data *ldata = tty->disc_data;
if (!old || (old->c_lflag ^ tty->termios.c_lflag) & ICANON) {
bitmap_zero(ldata->read_flags, N_TTY_BUF_SIZE);
ldata->line_start = ldata->read_tail;
if (!L_ICANON(tty) || !read_cnt(ldata)) {
ldata->canon_head = ldata->read_tail;
ldata->push = 0;
} else {
set_bit((ldata->read_head - 1) & (N_TTY_BUF_SIZE - 1),
ldata->read_flags);
ldata->canon_head = ldata->read_head;
ldata->push = 1;
}
ldata->commit_head = ldata->read_head;
ldata->erasing = 0;
ldata->lnext = 0;
}
ldata->icanon = (L_ICANON(tty) != 0);
if (I_ISTRIP(tty) || I_IUCLC(tty) || I_IGNCR(tty) ||
I_ICRNL(tty) || I_INLCR(tty) || L_ICANON(tty) ||
I_IXON(tty) || L_ISIG(tty) || L_ECHO(tty) ||
I_PARMRK(tty)) {
bitmap_zero(ldata->char_map, 256);
if (I_IGNCR(tty) || I_ICRNL(tty))
set_bit('\r', ldata->char_map);
if (I_INLCR(tty))
set_bit('\n', ldata->char_map);
if (L_ICANON(tty)) {
set_bit(ERASE_CHAR(tty), ldata->char_map);
set_bit(KILL_CHAR(tty), ldata->char_map);
set_bit(EOF_CHAR(tty), ldata->char_map);
set_bit('\n', ldata->char_map);
set_bit(EOL_CHAR(tty), ldata->char_map);
if (L_IEXTEN(tty)) {
set_bit(WERASE_CHAR(tty), ldata->char_map);
set_bit(LNEXT_CHAR(tty), ldata->char_map);
set_bit(EOL2_CHAR(tty), ldata->char_map);
if (L_ECHO(tty))
set_bit(REPRINT_CHAR(tty),
ldata->char_map);
}
}
if (I_IXON(tty)) {
set_bit(START_CHAR(tty), ldata->char_map);
set_bit(STOP_CHAR(tty), ldata->char_map);
}
if (L_ISIG(tty)) {
set_bit(INTR_CHAR(tty), ldata->char_map);
set_bit(QUIT_CHAR(tty), ldata->char_map);
set_bit(SUSP_CHAR(tty), ldata->char_map);
}
clear_bit(__DISABLED_CHAR, ldata->char_map);
ldata->raw = 0;
ldata->real_raw = 0;
} else {
ldata->raw = 1;
if ((I_IGNBRK(tty) || (!I_BRKINT(tty) && !I_PARMRK(tty))) &&
(I_IGNPAR(tty) || !I_INPCK(tty)) &&
(tty->driver->flags & TTY_DRIVER_REAL_RAW))
ldata->real_raw = 1;
else
ldata->real_raw = 0;
}
/*
* Fix tty hang when I_IXON(tty) is cleared, but the tty
* been stopped by STOP_CHAR(tty) before it.
*/
if (!I_IXON(tty) && old && (old->c_iflag & IXON) && !tty->flow_stopped) {
start_tty(tty);
process_echoes(tty);
}
/* The termios change make the tty ready for I/O */
wake_up_interruptible(&tty->write_wait);
wake_up_interruptible(&tty->read_wait);
}
Commit Message: n_tty: fix EXTPROC vs ICANON interaction with TIOCINQ (aka FIONREAD)
We added support for EXTPROC back in 2010 in commit 26df6d13406d ("tty:
Add EXTPROC support for LINEMODE") and the intent was to allow it to
override some (all?) ICANON behavior. Quoting from that original commit
message:
There is a new bit in the termios local flag word, EXTPROC.
When this bit is set, several aspects of the terminal driver
are disabled. Input line editing, character echo, and mapping
of signals are all disabled. This allows the telnetd to turn
off these functions when in linemode, but still keep track of
what state the user wants the terminal to be in.
but the problem turns out that "several aspects of the terminal driver
are disabled" is a bit ambiguous, and you can really confuse the n_tty
layer by setting EXTPROC and then causing some of the ICANON invariants
to no longer be maintained.
This fixes at least one such case (TIOCINQ) becoming unhappy because of
the confusion over whether ICANON really means ICANON when EXTPROC is set.
This basically makes TIOCINQ match the case of read: if EXTPROC is set,
we ignore ICANON. Also, make sure to reset the ICANON state ie EXTPROC
changes, not just if ICANON changes.
Fixes: 26df6d13406d ("tty: Add EXTPROC support for LINEMODE")
Reported-by: Tetsuo Handa <[email protected]>
Reported-by: syzkaller <[email protected]>
Cc: Jiri Slaby <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-704 | static void n_tty_set_termios(struct tty_struct *tty, struct ktermios *old)
{
struct n_tty_data *ldata = tty->disc_data;
if (!old || (old->c_lflag ^ tty->termios.c_lflag) & (ICANON | EXTPROC)) {
bitmap_zero(ldata->read_flags, N_TTY_BUF_SIZE);
ldata->line_start = ldata->read_tail;
if (!L_ICANON(tty) || !read_cnt(ldata)) {
ldata->canon_head = ldata->read_tail;
ldata->push = 0;
} else {
set_bit((ldata->read_head - 1) & (N_TTY_BUF_SIZE - 1),
ldata->read_flags);
ldata->canon_head = ldata->read_head;
ldata->push = 1;
}
ldata->commit_head = ldata->read_head;
ldata->erasing = 0;
ldata->lnext = 0;
}
ldata->icanon = (L_ICANON(tty) != 0);
if (I_ISTRIP(tty) || I_IUCLC(tty) || I_IGNCR(tty) ||
I_ICRNL(tty) || I_INLCR(tty) || L_ICANON(tty) ||
I_IXON(tty) || L_ISIG(tty) || L_ECHO(tty) ||
I_PARMRK(tty)) {
bitmap_zero(ldata->char_map, 256);
if (I_IGNCR(tty) || I_ICRNL(tty))
set_bit('\r', ldata->char_map);
if (I_INLCR(tty))
set_bit('\n', ldata->char_map);
if (L_ICANON(tty)) {
set_bit(ERASE_CHAR(tty), ldata->char_map);
set_bit(KILL_CHAR(tty), ldata->char_map);
set_bit(EOF_CHAR(tty), ldata->char_map);
set_bit('\n', ldata->char_map);
set_bit(EOL_CHAR(tty), ldata->char_map);
if (L_IEXTEN(tty)) {
set_bit(WERASE_CHAR(tty), ldata->char_map);
set_bit(LNEXT_CHAR(tty), ldata->char_map);
set_bit(EOL2_CHAR(tty), ldata->char_map);
if (L_ECHO(tty))
set_bit(REPRINT_CHAR(tty),
ldata->char_map);
}
}
if (I_IXON(tty)) {
set_bit(START_CHAR(tty), ldata->char_map);
set_bit(STOP_CHAR(tty), ldata->char_map);
}
if (L_ISIG(tty)) {
set_bit(INTR_CHAR(tty), ldata->char_map);
set_bit(QUIT_CHAR(tty), ldata->char_map);
set_bit(SUSP_CHAR(tty), ldata->char_map);
}
clear_bit(__DISABLED_CHAR, ldata->char_map);
ldata->raw = 0;
ldata->real_raw = 0;
} else {
ldata->raw = 1;
if ((I_IGNBRK(tty) || (!I_BRKINT(tty) && !I_PARMRK(tty))) &&
(I_IGNPAR(tty) || !I_INPCK(tty)) &&
(tty->driver->flags & TTY_DRIVER_REAL_RAW))
ldata->real_raw = 1;
else
ldata->real_raw = 0;
}
/*
* Fix tty hang when I_IXON(tty) is cleared, but the tty
* been stopped by STOP_CHAR(tty) before it.
*/
if (!I_IXON(tty) && old && (old->c_iflag & IXON) && !tty->flow_stopped) {
start_tty(tty);
process_echoes(tty);
}
/* The termios change make the tty ready for I/O */
wake_up_interruptible(&tty->write_wait);
wake_up_interruptible(&tty->read_wait);
}
| 169,010 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 AXObject::isLiveRegion() const {
const AtomicString& liveRegion = liveRegionStatus();
return equalIgnoringCase(liveRegion, "polite") ||
equalIgnoringCase(liveRegion, "assertive");
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | bool AXObject::isLiveRegion() const {
const AtomicString& liveRegion = liveRegionStatus();
return equalIgnoringASCIICase(liveRegion, "polite") ||
equalIgnoringASCIICase(liveRegion, "assertive");
}
| 171,927 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: DevToolsClient::DevToolsClient(
RenderFrame* main_render_frame,
const std::string& compatibility_script)
: RenderFrameObserver(main_render_frame),
compatibility_script_(compatibility_script),
web_tools_frontend_(
WebDevToolsFrontend::create(main_render_frame->GetWebFrame(), this)) {
}
Commit Message: [DevTools] Move sanitize url to devtools_ui.cc.
Compatibility script is not reliable enough.
BUG=653134
Review-Url: https://codereview.chromium.org/2403633002
Cr-Commit-Position: refs/heads/master@{#425814}
CWE ID: CWE-200 | DevToolsClient::DevToolsClient(
RenderFrame* main_render_frame,
const std::string& compatibility_script)
: RenderFrameObserver(main_render_frame),
compatibility_script_(compatibility_script),
web_tools_frontend_(
WebDevToolsFrontend::create(main_render_frame->GetWebFrame(), this)) {
compatibility_script_ += "\n//# sourceURL=devtools_compatibility.js";
}
| 172,511 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool_t xdr_nullstring(XDR *xdrs, char **objp)
{
u_int size;
if (xdrs->x_op == XDR_ENCODE) {
if (*objp == NULL)
size = 0;
else
size = strlen(*objp) + 1;
}
if (! xdr_u_int(xdrs, &size)) {
return FALSE;
}
switch (xdrs->x_op) {
case XDR_DECODE:
if (size == 0) {
*objp = NULL;
return TRUE;
} else if (*objp == NULL) {
*objp = (char *) mem_alloc(size);
if (*objp == NULL) {
errno = ENOMEM;
return FALSE;
}
}
return (xdr_opaque(xdrs, *objp, size));
case XDR_ENCODE:
if (size != 0)
return (xdr_opaque(xdrs, *objp, size));
return TRUE;
case XDR_FREE:
if (*objp != NULL)
mem_free(*objp, size);
*objp = NULL;
return TRUE;
}
return FALSE;
}
Commit Message: Verify decoded kadmin C strings [CVE-2015-8629]
In xdr_nullstring(), check that the decoded string is terminated with
a zero byte and does not contain any internal zero bytes.
CVE-2015-8629:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to read beyond the end of allocated memory by sending a string
without a terminating zero byte. Information leakage may be possible
for an attacker with permission to modify the database.
CVSSv2 Vector: AV:N/AC:H/Au:S/C:P/I:N/A:N/E:POC/RL:OF/RC:C
ticket: 8341 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119 | bool_t xdr_nullstring(XDR *xdrs, char **objp)
{
u_int size;
if (xdrs->x_op == XDR_ENCODE) {
if (*objp == NULL)
size = 0;
else
size = strlen(*objp) + 1;
}
if (! xdr_u_int(xdrs, &size)) {
return FALSE;
}
switch (xdrs->x_op) {
case XDR_DECODE:
if (size == 0) {
*objp = NULL;
return TRUE;
} else if (*objp == NULL) {
*objp = (char *) mem_alloc(size);
if (*objp == NULL) {
errno = ENOMEM;
return FALSE;
}
}
if (!xdr_opaque(xdrs, *objp, size))
return FALSE;
/* Check that the unmarshalled bytes are a C string. */
if ((*objp)[size - 1] != '\0')
return FALSE;
if (memchr(*objp, '\0', size - 1) != NULL)
return FALSE;
return TRUE;
case XDR_ENCODE:
if (size != 0)
return (xdr_opaque(xdrs, *objp, size));
return TRUE;
case XDR_FREE:
if (*objp != NULL)
mem_free(*objp, size);
*objp = NULL;
return TRUE;
}
return FALSE;
}
| 167,530 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 irda_recvmsg_dgram(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
struct sk_buff *skb;
size_t copied;
int err;
IRDA_DEBUG(4, "%s()\n", __func__);
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &err);
if (!skb)
return err;
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
IRDA_DEBUG(2, "%s(), Received truncated frame (%zd < %zd)!\n",
__func__, copied, size);
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
skb_free_datagram(sk, skb);
/*
* Check if we have previously stopped IrTTP and we know
* have more free space in our rx_queue. If so tell IrTTP
* to start delivering frames again before our rx_queue gets
* empty
*/
if (self->rx_flow == FLOW_STOP) {
if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) {
IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__);
self->rx_flow = FLOW_START;
irttp_flow_request(self->tsap, FLOW_START);
}
}
return copied;
}
Commit Message: irda: Fix missing msg_namelen update in irda_recvmsg_dgram()
The current code does not fill the msg_name member in case it is set.
It also does not set the msg_namelen member to 0 and therefore makes
net/socket.c leak the local, uninitialized sockaddr_storage variable
to userland -- 128 bytes of kernel stack memory.
Fix that by simply setting msg_namelen to 0 as obviously nobody cared
about irda_recvmsg_dgram() not filling the msg_name in case it was
set.
Cc: Samuel Ortiz <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int irda_recvmsg_dgram(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
struct sk_buff *skb;
size_t copied;
int err;
IRDA_DEBUG(4, "%s()\n", __func__);
msg->msg_namelen = 0;
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &err);
if (!skb)
return err;
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
IRDA_DEBUG(2, "%s(), Received truncated frame (%zd < %zd)!\n",
__func__, copied, size);
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
skb_free_datagram(sk, skb);
/*
* Check if we have previously stopped IrTTP and we know
* have more free space in our rx_queue. If so tell IrTTP
* to start delivering frames again before our rx_queue gets
* empty
*/
if (self->rx_flow == FLOW_STOP) {
if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) {
IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__);
self->rx_flow = FLOW_START;
irttp_flow_request(self->tsap, FLOW_START);
}
}
return copied;
}
| 166,039 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 __poke_user(struct task_struct *child, addr_t addr, addr_t data)
{
struct user *dummy = NULL;
addr_t offset;
if (addr < (addr_t) &dummy->regs.acrs) {
/*
* psw and gprs are stored on the stack
*/
if (addr == (addr_t) &dummy->regs.psw.mask) {
unsigned long mask = PSW_MASK_USER;
mask |= is_ri_task(child) ? PSW_MASK_RI : 0;
if ((data & ~mask) != PSW_USER_BITS)
return -EINVAL;
if ((data & PSW_MASK_EA) && !(data & PSW_MASK_BA))
return -EINVAL;
}
*(addr_t *)((addr_t) &task_pt_regs(child)->psw + addr) = data;
} else if (addr < (addr_t) (&dummy->regs.orig_gpr2)) {
/*
* access registers are stored in the thread structure
*/
offset = addr - (addr_t) &dummy->regs.acrs;
#ifdef CONFIG_64BIT
/*
* Very special case: old & broken 64 bit gdb writing
* to acrs[15] with a 64 bit value. Ignore the lower
* half of the value and write the upper 32 bit to
* acrs[15]. Sick...
*/
if (addr == (addr_t) &dummy->regs.acrs[15])
child->thread.acrs[15] = (unsigned int) (data >> 32);
else
#endif
*(addr_t *)((addr_t) &child->thread.acrs + offset) = data;
} else if (addr == (addr_t) &dummy->regs.orig_gpr2) {
/*
* orig_gpr2 is stored on the kernel stack
*/
task_pt_regs(child)->orig_gpr2 = data;
} else if (addr < (addr_t) &dummy->regs.fp_regs) {
/*
* prevent writes of padding hole between
* orig_gpr2 and fp_regs on s390.
*/
return 0;
} else if (addr < (addr_t) (&dummy->regs.fp_regs + 1)) {
/*
* floating point regs. are stored in the thread structure
*/
if (addr == (addr_t) &dummy->regs.fp_regs.fpc)
if ((unsigned int) data != 0 ||
test_fp_ctl(data >> (BITS_PER_LONG - 32)))
return -EINVAL;
offset = addr - (addr_t) &dummy->regs.fp_regs;
*(addr_t *)((addr_t) &child->thread.fp_regs + offset) = data;
} else if (addr < (addr_t) (&dummy->regs.per_info + 1)) {
/*
* Handle access to the per_info structure.
*/
addr -= (addr_t) &dummy->regs.per_info;
__poke_user_per(child, addr, data);
}
return 0;
}
Commit Message: s390/ptrace: fix PSW mask check
The PSW mask check of the PTRACE_POKEUSR_AREA command is incorrect.
The PSW_MASK_USER define contains the PSW_MASK_ASC bits, the ptrace
interface accepts all combinations for the address-space-control
bits. To protect the kernel space the PSW mask check in ptrace needs
to reject the address-space-control bit combination for home space.
Fixes CVE-2014-3534
Cc: [email protected]
Signed-off-by: Martin Schwidefsky <[email protected]>
CWE ID: CWE-264 | static int __poke_user(struct task_struct *child, addr_t addr, addr_t data)
{
struct user *dummy = NULL;
addr_t offset;
if (addr < (addr_t) &dummy->regs.acrs) {
/*
* psw and gprs are stored on the stack
*/
if (addr == (addr_t) &dummy->regs.psw.mask) {
unsigned long mask = PSW_MASK_USER;
mask |= is_ri_task(child) ? PSW_MASK_RI : 0;
if ((data ^ PSW_USER_BITS) & ~mask)
/* Invalid psw mask. */
return -EINVAL;
if ((data & PSW_MASK_ASC) == PSW_ASC_HOME)
/* Invalid address-space-control bits */
return -EINVAL;
if ((data & PSW_MASK_EA) && !(data & PSW_MASK_BA))
/* Invalid addressing mode bits */
return -EINVAL;
}
*(addr_t *)((addr_t) &task_pt_regs(child)->psw + addr) = data;
} else if (addr < (addr_t) (&dummy->regs.orig_gpr2)) {
/*
* access registers are stored in the thread structure
*/
offset = addr - (addr_t) &dummy->regs.acrs;
#ifdef CONFIG_64BIT
/*
* Very special case: old & broken 64 bit gdb writing
* to acrs[15] with a 64 bit value. Ignore the lower
* half of the value and write the upper 32 bit to
* acrs[15]. Sick...
*/
if (addr == (addr_t) &dummy->regs.acrs[15])
child->thread.acrs[15] = (unsigned int) (data >> 32);
else
#endif
*(addr_t *)((addr_t) &child->thread.acrs + offset) = data;
} else if (addr == (addr_t) &dummy->regs.orig_gpr2) {
/*
* orig_gpr2 is stored on the kernel stack
*/
task_pt_regs(child)->orig_gpr2 = data;
} else if (addr < (addr_t) &dummy->regs.fp_regs) {
/*
* prevent writes of padding hole between
* orig_gpr2 and fp_regs on s390.
*/
return 0;
} else if (addr < (addr_t) (&dummy->regs.fp_regs + 1)) {
/*
* floating point regs. are stored in the thread structure
*/
if (addr == (addr_t) &dummy->regs.fp_regs.fpc)
if ((unsigned int) data != 0 ||
test_fp_ctl(data >> (BITS_PER_LONG - 32)))
return -EINVAL;
offset = addr - (addr_t) &dummy->regs.fp_regs;
*(addr_t *)((addr_t) &child->thread.fp_regs + offset) = data;
} else if (addr < (addr_t) (&dummy->regs.per_info + 1)) {
/*
* Handle access to the per_info structure.
*/
addr -= (addr_t) &dummy->regs.per_info;
__poke_user_per(child, addr, data);
}
return 0;
}
| 166,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: bool MediaStreamDevicesController::IsRequestAllowedByDefault() const {
if (ShouldAlwaysAllowOrigin())
return true;
struct {
bool has_capability;
const char* policy_name;
const char* list_policy_name;
ContentSettingsType settings_type;
} device_checks[] = {
{ microphone_requested_, prefs::kAudioCaptureAllowed,
prefs::kAudioCaptureAllowedUrls, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC },
{ webcam_requested_, prefs::kVideoCaptureAllowed,
prefs::kVideoCaptureAllowedUrls,
CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(device_checks); ++i) {
if (!device_checks[i].has_capability)
continue;
DevicePolicy policy = GetDevicePolicy(device_checks[i].policy_name,
device_checks[i].list_policy_name);
if (policy == ALWAYS_DENY ||
(policy == POLICY_NOT_SET &&
profile_->GetHostContentSettingsMap()->GetContentSetting(
request_.security_origin, request_.security_origin,
device_checks[i].settings_type, NO_RESOURCE_IDENTIFIER) !=
CONTENT_SETTING_ALLOW)) {
return false;
}
}
return true;
}
Commit Message: Make the content setting for webcam/mic sticky for Pepper requests.
This makes the content setting sticky for webcam/mic requests from Pepper from non-https origins.
BUG=249335
[email protected], [email protected]
Review URL: https://codereview.chromium.org/17060006
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@206479 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | bool MediaStreamDevicesController::IsRequestAllowedByDefault() const {
if (ShouldAlwaysAllowOrigin())
return true;
struct {
bool has_capability;
const char* policy_name;
const char* list_policy_name;
ContentSettingsType settings_type;
} device_checks[] = {
{ microphone_requested_, prefs::kAudioCaptureAllowed,
prefs::kAudioCaptureAllowedUrls, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC },
{ webcam_requested_, prefs::kVideoCaptureAllowed,
prefs::kVideoCaptureAllowedUrls,
CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(device_checks); ++i) {
if (!device_checks[i].has_capability)
continue;
DevicePolicy policy = GetDevicePolicy(device_checks[i].policy_name,
device_checks[i].list_policy_name);
if (policy == ALWAYS_DENY)
return false;
if (policy == POLICY_NOT_SET) {
// Only load content settings from secure origins unless it is a
// content::MEDIA_OPEN_DEVICE (Pepper) request.
if (!IsSchemeSecure() &&
request_.request_type != content::MEDIA_OPEN_DEVICE) {
return false;
}
if (profile_->GetHostContentSettingsMap()->GetContentSetting(
request_.security_origin, request_.security_origin,
device_checks[i].settings_type, NO_RESOURCE_IDENTIFIER) !=
CONTENT_SETTING_ALLOW) {
return false;
}
}
}
return true;
}
| 171,313 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: header_put_le_3byte (SF_PRIVATE *psf, int x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 3)
{ psf->header [psf->headindex++] = x ;
psf->header [psf->headindex++] = (x >> 8) ;
psf->header [psf->headindex++] = (x >> 16) ;
} ;
} /* header_put_le_3byte */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119 | header_put_le_3byte (SF_PRIVATE *psf, int x)
{ psf->header.ptr [psf->header.indx++] = x ;
psf->header.ptr [psf->header.indx++] = (x >> 8) ;
psf->header.ptr [psf->header.indx++] = (x >> 16) ;
} /* header_put_le_3byte */
| 170,054 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 TabletModeWindowManager::ArrangeWindowsForClamshellMode(
base::flat_map<aura::Window*, WindowStateType> windows_in_splitview) {
int divider_position = CalculateCarryOverDividerPostion(windows_in_splitview);
while (window_state_map_.size()) {
aura::Window* window = window_state_map_.begin()->first;
ForgetWindow(window, /*destroyed=*/false);
}
if (IsClamshellSplitViewModeEnabled()) {
DoSplitViewTransition(windows_in_splitview, divider_position);
}
}
Commit Message: Fix the crash after clamshell -> tablet transition in overview mode.
This CL just reverted some changes that were made in
https://chromium-review.googlesource.com/c/chromium/src/+/1658955. In
that CL, we changed the clamshell <-> tablet transition when clamshell
split view mode is enabled, however, we should keep the old behavior
unchanged if the feature is not enabled, i.e., overview should be ended
if it's active before the transition. Otherwise, it will cause a nullptr
dereference crash since |split_view_drag_indicators_| is not created in
clamshell overview and will be used in tablet overview.
Bug: 982507
Change-Id: I238fe9472648a446cff4ab992150658c228714dd
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1705474
Commit-Queue: Xiaoqian Dai <[email protected]>
Reviewed-by: Mitsuru Oshima (Slow - on/off site) <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679306}
CWE ID: CWE-362 | void TabletModeWindowManager::ArrangeWindowsForClamshellMode(
base::flat_map<aura::Window*, WindowStateType> windows_in_splitview,
bool was_in_overview) {
int divider_position = CalculateCarryOverDividerPostion(windows_in_splitview);
while (window_state_map_.size()) {
aura::Window* window = window_state_map_.begin()->first;
ForgetWindow(window, /*destroyed=*/false, was_in_overview);
}
if (IsClamshellSplitViewModeEnabled()) {
DoSplitViewTransition(windows_in_splitview, divider_position);
}
}
| 172,399 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void OMXNodeInstance::invalidateBufferID(OMX::buffer_id buffer __unused) {
}
Commit Message: IOMX: Enable buffer ptr to buffer id translation for arm32
Bug: 20634516
Change-Id: Iac9eac3cb251eccd9bbad5df7421a07edc21da0c
(cherry picked from commit 2d6b6601743c3c6960c6511a2cb774ef902759f4)
CWE ID: CWE-119 | void OMXNodeInstance::invalidateBufferID(OMX::buffer_id buffer __unused) {
| 173,359 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool UnpackOriginPermissions(const std::vector<std::string>& origins_input,
const PermissionSet& required_permissions,
const PermissionSet& optional_permissions,
bool allow_file_access,
UnpackPermissionSetResult* result,
std::string* error) {
int user_script_schemes = UserScript::ValidUserScriptSchemes();
int explicit_schemes = Extension::kValidHostPermissionSchemes;
if (!allow_file_access) {
user_script_schemes &= ~URLPattern::SCHEME_FILE;
explicit_schemes &= ~URLPattern::SCHEME_FILE;
}
for (const auto& origin_str : origins_input) {
URLPattern explicit_origin(explicit_schemes);
URLPattern::ParseResult parse_result = explicit_origin.Parse(origin_str);
if (URLPattern::ParseResult::kSuccess != parse_result) {
*error = ErrorUtils::FormatErrorMessage(
kInvalidOrigin, origin_str,
URLPattern::GetParseResultString(parse_result));
return false;
}
bool used_origin = false;
if (required_permissions.explicit_hosts().ContainsPattern(
explicit_origin)) {
used_origin = true;
result->required_explicit_hosts.AddPattern(explicit_origin);
} else if (optional_permissions.explicit_hosts().ContainsPattern(
explicit_origin)) {
used_origin = true;
result->optional_explicit_hosts.AddPattern(explicit_origin);
}
URLPattern scriptable_origin(user_script_schemes);
if (scriptable_origin.Parse(origin_str) ==
URLPattern::ParseResult::kSuccess &&
required_permissions.scriptable_hosts().ContainsPattern(
scriptable_origin)) {
used_origin = true;
result->required_scriptable_hosts.AddPattern(scriptable_origin);
}
if (!used_origin)
result->unlisted_hosts.AddPattern(explicit_origin);
}
return true;
}
Commit Message: [Extensions] Have URLPattern::Contains() properly check schemes
Have URLPattern::Contains() properly check the schemes of the patterns
when evaluating if one pattern contains another. This is important in
order to prevent extensions from requesting chrome:-scheme permissions
via the permissions API when <all_urls> is specified as an optional
permission.
Bug: 859600,918470
Change-Id: If04d945ad0c939e84a80d83502c0f84b6ef0923d
Reviewed-on: https://chromium-review.googlesource.com/c/1396561
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Karan Bhatia <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621410}
CWE ID: CWE-79 | bool UnpackOriginPermissions(const std::vector<std::string>& origins_input,
const PermissionSet& required_permissions,
const PermissionSet& optional_permissions,
bool allow_file_access,
UnpackPermissionSetResult* result,
std::string* error) {
int user_script_schemes = UserScript::ValidUserScriptSchemes();
int explicit_schemes = Extension::kValidHostPermissionSchemes;
if (!allow_file_access) {
user_script_schemes &= ~URLPattern::SCHEME_FILE;
explicit_schemes &= ~URLPattern::SCHEME_FILE;
}
auto filter_chrome_scheme = [](URLPattern* pattern) {
// We disallow the chrome:-scheme unless the pattern is explicitly
// "chrome://..." - that is, <all_urls> should not match the chrome:-scheme.
// Patterns which explicitly specify the chrome:-scheme are safe, since
// manifest parsing won't allow them unless the kExtensionsOnChromeURLs
// switch is enabled.
// Note that we don't check PermissionsData::AllUrlsIncludesChromeUrls()
// here, since that's only needed for Chromevox (which doesn't use optional
// permissions).
if (pattern->scheme() != content::kChromeUIScheme) {
// NOTE: We use pattern->valid_schemes() here (instead of
// |user_script_schemes| or |explicit_schemes|) because
// URLPattern::Parse() can mutate the valid schemes for a pattern, and we
// don't want to override those changes.
pattern->SetValidSchemes(pattern->valid_schemes() &
~URLPattern::SCHEME_CHROMEUI);
}
};
for (const auto& origin_str : origins_input) {
URLPattern explicit_origin(explicit_schemes);
URLPattern::ParseResult parse_result = explicit_origin.Parse(origin_str);
if (URLPattern::ParseResult::kSuccess != parse_result) {
*error = ErrorUtils::FormatErrorMessage(
kInvalidOrigin, origin_str,
URLPattern::GetParseResultString(parse_result));
return false;
}
filter_chrome_scheme(&explicit_origin);
bool used_origin = false;
if (required_permissions.explicit_hosts().ContainsPattern(
explicit_origin)) {
used_origin = true;
result->required_explicit_hosts.AddPattern(explicit_origin);
} else if (optional_permissions.explicit_hosts().ContainsPattern(
explicit_origin)) {
used_origin = true;
result->optional_explicit_hosts.AddPattern(explicit_origin);
}
URLPattern scriptable_origin(user_script_schemes);
if (scriptable_origin.Parse(origin_str) ==
URLPattern::ParseResult::kSuccess) {
filter_chrome_scheme(&scriptable_origin);
if (required_permissions.scriptable_hosts().ContainsPattern(
scriptable_origin)) {
used_origin = true;
result->required_scriptable_hosts.AddPattern(scriptable_origin);
}
}
if (!used_origin)
result->unlisted_hosts.AddPattern(explicit_origin);
}
return true;
}
| 173,118 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 UsbDevice::OpenInterface(int interface_id, const OpenCallback& callback) {
Open(callback);
}
Commit Message: Remove fallback when requesting a single USB interface.
This reverts commit 2d475d0ed37bf8f19385537ad31e361f1b21624b. The
permission broker now supports opening devices that are partially
claimed through the OpenPath method and RequestPathAccess will always
fail for these devices so the fallback path from RequestPathAccess to
OpenPath is always taken.
BUG=500057
Review URL: https://codereview.chromium.org/1227313003
Cr-Commit-Position: refs/heads/master@{#338354}
CWE ID: CWE-399 | void UsbDevice::OpenInterface(int interface_id, const OpenCallback& callback) {
| 171,700 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int crypto_report_cipher(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_cipher rcipher;
snprintf(rcipher.type, CRYPTO_MAX_ALG_NAME, "%s", "cipher");
rcipher.blocksize = alg->cra_blocksize;
rcipher.min_keysize = alg->cra_cipher.cia_min_keysize;
rcipher.max_keysize = alg->cra_cipher.cia_max_keysize;
if (nla_put(skb, CRYPTOCFGA_REPORT_CIPHER,
sizeof(struct crypto_report_cipher), &rcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Commit Message: crypto: user - fix info leaks in report API
Three errors resulting in kernel memory disclosure:
1/ The structures used for the netlink based crypto algorithm report API
are located on the stack. As snprintf() does not fill the remainder of
the buffer with null bytes, those stack bytes will be disclosed to users
of the API. Switch to strncpy() to fix this.
2/ crypto_report_one() does not initialize all field of struct
crypto_user_alg. Fix this to fix the heap info leak.
3/ For the module name we should copy only as many bytes as
module_name() returns -- not as much as the destination buffer could
hold. But the current code does not and therefore copies random data
from behind the end of the module name, as the module name is always
shorter than CRYPTO_MAX_ALG_NAME.
Also switch to use strncpy() to copy the algorithm's name and
driver_name. They are strings, after all.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Steffen Klassert <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-310 | static int crypto_report_cipher(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_cipher rcipher;
strncpy(rcipher.type, "cipher", sizeof(rcipher.type));
rcipher.blocksize = alg->cra_blocksize;
rcipher.min_keysize = alg->cra_cipher.cia_min_keysize;
rcipher.max_keysize = alg->cra_cipher.cia_max_keysize;
if (nla_put(skb, CRYPTOCFGA_REPORT_CIPHER,
sizeof(struct crypto_report_cipher), &rcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
| 166,067 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 Chapters::Atom::ShallowCopy(Atom& rhs) const
{
rhs.m_string_uid = m_string_uid;
rhs.m_uid = m_uid;
rhs.m_start_timecode = m_start_timecode;
rhs.m_stop_timecode = m_stop_timecode;
rhs.m_displays = m_displays;
rhs.m_displays_size = m_displays_size;
rhs.m_displays_count = m_displays_count;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | void Chapters::Atom::ShallowCopy(Atom& rhs) const
| 174,442 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: px_crypt_des(const char *key, const char *setting)
{
int i;
uint32 count,
salt,
l,
r0,
r1,
keybuf[2];
char *p;
uint8 *q;
static char output[21];
if (!des_initialised)
des_init();
/*
* Copy the key, shifting each character up by one bit and padding with
* zeros.
*/
q = (uint8 *) keybuf;
while (q - (uint8 *) keybuf - 8)
{
if ((*q++ = *key << 1))
key++;
}
if (des_setkey((char *) keybuf))
#ifndef DISABLE_XDES
if (*setting == _PASSWORD_EFMT1)
{
/*
* "new"-style: setting - underscore, 4 bytes of count, 4 bytes of
* salt key - unlimited characters
*/
for (i = 1, count = 0L; i < 5; i++)
count |= ascii_to_bin(setting[i]) << (i - 1) * 6;
for (i = 5, salt = 0L; i < 9; i++)
salt |= ascii_to_bin(setting[i]) << (i - 5) * 6;
while (*key)
{
/*
* Encrypt the key with itself.
*/
if (des_cipher((char *) keybuf, (char *) keybuf, 0L, 1))
return (NULL);
/*
* And XOR with the next 8 characters of the key.
*/
q = (uint8 *) keybuf;
while (q - (uint8 *) keybuf - 8 && *key)
*q++ ^= *key++ << 1;
if (des_setkey((char *) keybuf))
return (NULL);
}
strncpy(output, setting, 9);
/*
* Double check that we weren't given a short setting. If we were, the
* above code will probably have created weird values for count and
* salt, but we don't really care. Just make sure the output string
* doesn't have an extra NUL in it.
*/
output[9] = '\0';
p = output + strlen(output);
}
else
#endif /* !DISABLE_XDES */
{
/*
* "old"-style: setting - 2 bytes of salt key - up to 8 characters
*/
count = 25;
salt = (ascii_to_bin(setting[1]) << 6)
| ascii_to_bin(setting[0]);
output[0] = setting[0];
/*
* If the encrypted password that the salt was extracted from is only
* 1 character long, the salt will be corrupted. We need to ensure
* that the output string doesn't have an extra NUL in it!
*/
output[1] = setting[1] ? setting[1] : output[0];
p = output + 2;
}
setup_salt(salt);
/*
* Do it.
*/
if (do_des(0L, 0L, &r0, &r1, count))
return (NULL);
/*
* Now encode the result...
*/
l = (r0 >> 8);
*p++ = _crypt_a64[(l >> 18) & 0x3f];
*p++ = _crypt_a64[(l >> 12) & 0x3f];
*p++ = _crypt_a64[(l >> 6) & 0x3f];
*p++ = _crypt_a64[l & 0x3f];
l = (r0 << 16) | ((r1 >> 16) & 0xffff);
*p++ = _crypt_a64[(l >> 18) & 0x3f];
*p++ = _crypt_a64[(l >> 12) & 0x3f];
*p++ = _crypt_a64[(l >> 6) & 0x3f];
*p++ = _crypt_a64[l & 0x3f];
l = r1 << 2;
*p++ = _crypt_a64[(l >> 12) & 0x3f];
*p++ = _crypt_a64[(l >> 6) & 0x3f];
*p++ = _crypt_a64[l & 0x3f];
*p = 0;
return (output);
}
Commit Message:
CWE ID: CWE-310 | px_crypt_des(const char *key, const char *setting)
{
int i;
uint32 count,
salt,
l,
r0,
r1,
keybuf[2];
char *p;
uint8 *q;
static char output[21];
if (!des_initialised)
des_init();
/*
* Copy the key, shifting each character up by one bit and padding with
* zeros.
*/
q = (uint8 *) keybuf;
while (q - (uint8 *) keybuf - 8)
{
*q++ = *key << 1;
if (*key != '\0')
key++;
}
if (des_setkey((char *) keybuf))
#ifndef DISABLE_XDES
if (*setting == _PASSWORD_EFMT1)
{
/*
* "new"-style: setting - underscore, 4 bytes of count, 4 bytes of
* salt key - unlimited characters
*/
for (i = 1, count = 0L; i < 5; i++)
count |= ascii_to_bin(setting[i]) << (i - 1) * 6;
for (i = 5, salt = 0L; i < 9; i++)
salt |= ascii_to_bin(setting[i]) << (i - 5) * 6;
while (*key)
{
/*
* Encrypt the key with itself.
*/
if (des_cipher((char *) keybuf, (char *) keybuf, 0L, 1))
return (NULL);
/*
* And XOR with the next 8 characters of the key.
*/
q = (uint8 *) keybuf;
while (q - (uint8 *) keybuf - 8 && *key)
*q++ ^= *key++ << 1;
if (des_setkey((char *) keybuf))
return (NULL);
}
strncpy(output, setting, 9);
/*
* Double check that we weren't given a short setting. If we were, the
* above code will probably have created weird values for count and
* salt, but we don't really care. Just make sure the output string
* doesn't have an extra NUL in it.
*/
output[9] = '\0';
p = output + strlen(output);
}
else
#endif /* !DISABLE_XDES */
{
/*
* "old"-style: setting - 2 bytes of salt key - up to 8 characters
*/
count = 25;
salt = (ascii_to_bin(setting[1]) << 6)
| ascii_to_bin(setting[0]);
output[0] = setting[0];
/*
* If the encrypted password that the salt was extracted from is only
* 1 character long, the salt will be corrupted. We need to ensure
* that the output string doesn't have an extra NUL in it!
*/
output[1] = setting[1] ? setting[1] : output[0];
p = output + 2;
}
setup_salt(salt);
/*
* Do it.
*/
if (do_des(0L, 0L, &r0, &r1, count))
return (NULL);
/*
* Now encode the result...
*/
l = (r0 >> 8);
*p++ = _crypt_a64[(l >> 18) & 0x3f];
*p++ = _crypt_a64[(l >> 12) & 0x3f];
*p++ = _crypt_a64[(l >> 6) & 0x3f];
*p++ = _crypt_a64[l & 0x3f];
l = (r0 << 16) | ((r1 >> 16) & 0xffff);
*p++ = _crypt_a64[(l >> 18) & 0x3f];
*p++ = _crypt_a64[(l >> 12) & 0x3f];
*p++ = _crypt_a64[(l >> 6) & 0x3f];
*p++ = _crypt_a64[l & 0x3f];
l = r1 << 2;
*p++ = _crypt_a64[(l >> 12) & 0x3f];
*p++ = _crypt_a64[(l >> 6) & 0x3f];
*p++ = _crypt_a64[l & 0x3f];
*p = 0;
return (output);
}
| 165,027 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 RegisterOptimizationHintsComponent(ComponentUpdateService* cus,
PrefService* profile_prefs) {
if (!previews::params::IsOptimizationHintsEnabled()) {
return;
}
bool data_saver_enabled =
base::CommandLine::ForCurrentProcess()->HasSwitch(
data_reduction_proxy::switches::kEnableDataReductionProxy) ||
(profile_prefs && profile_prefs->GetBoolean(
data_reduction_proxy::prefs::kDataSaverEnabled));
if (!data_saver_enabled)
return;
auto installer = base::MakeRefCounted<ComponentInstaller>(
std::make_unique<OptimizationHintsComponentInstallerPolicy>());
installer->Register(cus, base::OnceClosure());
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Commit-Queue: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119 | void RegisterOptimizationHintsComponent(ComponentUpdateService* cus,
PrefService* profile_prefs) {
if (!previews::params::IsOptimizationHintsEnabled()) {
return;
}
if (!data_reduction_proxy::DataReductionProxySettings::
IsDataSaverEnabledByUser(profile_prefs)) {
return;
}
auto installer = base::MakeRefCounted<ComponentInstaller>(
std::make_unique<OptimizationHintsComponentInstallerPolicy>());
installer->Register(cus, base::OnceClosure());
}
| 172,548 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static unsigned long mmap_legacy_base(unsigned long rnd)
{
if (mmap_is_ia32())
return TASK_UNMAPPED_BASE;
else
return TASK_UNMAPPED_BASE + rnd;
}
Commit Message: x86/mm/32: Enable full randomization on i386 and X86_32
Currently on i386 and on X86_64 when emulating X86_32 in legacy mode, only
the stack and the executable are randomized but not other mmapped files
(libraries, vDSO, etc.). This patch enables randomization for the
libraries, vDSO and mmap requests on i386 and in X86_32 in legacy mode.
By default on i386 there are 8 bits for the randomization of the libraries,
vDSO and mmaps which only uses 1MB of VA.
This patch preserves the original randomness, using 1MB of VA out of 3GB or
4GB. We think that 1MB out of 3GB is not a big cost for having the ASLR.
The first obvious security benefit is that all objects are randomized (not
only the stack and the executable) in legacy mode which highly increases
the ASLR effectiveness, otherwise the attackers may use these
non-randomized areas. But also sensitive setuid/setgid applications are
more secure because currently, attackers can disable the randomization of
these applications by setting the ulimit stack to "unlimited". This is a
very old and widely known trick to disable the ASLR in i386 which has been
allowed for too long.
Another trick used to disable the ASLR was to set the ADDR_NO_RANDOMIZE
personality flag, but fortunately this doesn't work on setuid/setgid
applications because there is security checks which clear Security-relevant
flags.
This patch always randomizes the mmap_legacy_base address, removing the
possibility to disable the ASLR by setting the stack to "unlimited".
Signed-off-by: Hector Marco-Gisbert <[email protected]>
Acked-by: Ismael Ripoll Ripoll <[email protected]>
Acked-by: Kees Cook <[email protected]>
Acked-by: Arjan van de Ven <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: [email protected]
Cc: kees Cook <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-254 | static unsigned long mmap_legacy_base(unsigned long rnd)
| 167,353 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 SoftVPXEncoder::onQueueFilled(OMX_U32 portIndex) {
if (mCodecContext == NULL) {
if (OK != initEncoder()) {
ALOGE("Failed to initialize encoder");
notify(OMX_EventError,
OMX_ErrorUndefined,
0, // Extra notification data
NULL); // Notification data pointer
return;
}
}
vpx_codec_err_t codec_return;
List<BufferInfo *> &inputBufferInfoQueue = getPortQueue(kInputPortIndex);
List<BufferInfo *> &outputBufferInfoQueue = getPortQueue(kOutputPortIndex);
while (!inputBufferInfoQueue.empty() && !outputBufferInfoQueue.empty()) {
BufferInfo *inputBufferInfo = *inputBufferInfoQueue.begin();
OMX_BUFFERHEADERTYPE *inputBufferHeader = inputBufferInfo->mHeader;
BufferInfo *outputBufferInfo = *outputBufferInfoQueue.begin();
OMX_BUFFERHEADERTYPE *outputBufferHeader = outputBufferInfo->mHeader;
if (inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) {
inputBufferInfoQueue.erase(inputBufferInfoQueue.begin());
inputBufferInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inputBufferHeader);
outputBufferHeader->nFilledLen = 0;
outputBufferHeader->nFlags = OMX_BUFFERFLAG_EOS;
outputBufferInfoQueue.erase(outputBufferInfoQueue.begin());
outputBufferInfo->mOwnedByUs = false;
notifyFillBufferDone(outputBufferHeader);
return;
}
const uint8_t *source =
inputBufferHeader->pBuffer + inputBufferHeader->nOffset;
size_t frameSize = mWidth * mHeight * 3 / 2;
if (mInputDataIsMeta) {
source = extractGraphicBuffer(
mConversionBuffer, frameSize,
source, inputBufferHeader->nFilledLen,
mWidth, mHeight);
if (source == NULL) {
ALOGE("Unable to extract gralloc buffer in metadata mode");
notify(OMX_EventError, OMX_ErrorUndefined, 0, 0);
return;
}
} else {
if (inputBufferHeader->nFilledLen < frameSize) {
android_errorWriteLog(0x534e4554, "27569635");
notify(OMX_EventError, OMX_ErrorUndefined, 0, 0);
return;
} else if (inputBufferHeader->nFilledLen > frameSize) {
ALOGW("Input buffer contains too many pixels");
}
if (mColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) {
ConvertYUV420SemiPlanarToYUV420Planar(
source, mConversionBuffer, mWidth, mHeight);
source = mConversionBuffer;
}
}
vpx_image_t raw_frame;
vpx_img_wrap(&raw_frame, VPX_IMG_FMT_I420, mWidth, mHeight,
kInputBufferAlignment, (uint8_t *)source);
vpx_enc_frame_flags_t flags = 0;
if (mTemporalPatternLength > 0) {
flags = getEncodeFlags();
}
if (mKeyFrameRequested) {
flags |= VPX_EFLAG_FORCE_KF;
mKeyFrameRequested = false;
}
if (mBitrateUpdated) {
mCodecConfiguration->rc_target_bitrate = mBitrate/1000;
vpx_codec_err_t res = vpx_codec_enc_config_set(mCodecContext,
mCodecConfiguration);
if (res != VPX_CODEC_OK) {
ALOGE("vp8 encoder failed to update bitrate: %s",
vpx_codec_err_to_string(res));
notify(OMX_EventError,
OMX_ErrorUndefined,
0, // Extra notification data
NULL); // Notification data pointer
}
mBitrateUpdated = false;
}
uint32_t frameDuration;
if (inputBufferHeader->nTimeStamp > mLastTimestamp) {
frameDuration = (uint32_t)(inputBufferHeader->nTimeStamp - mLastTimestamp);
} else {
frameDuration = (uint32_t)(((uint64_t)1000000 << 16) / mFramerate);
}
mLastTimestamp = inputBufferHeader->nTimeStamp;
codec_return = vpx_codec_encode(
mCodecContext,
&raw_frame,
inputBufferHeader->nTimeStamp, // in timebase units
frameDuration, // frame duration in timebase units
flags, // frame flags
VPX_DL_REALTIME); // encoding deadline
if (codec_return != VPX_CODEC_OK) {
ALOGE("vpx encoder failed to encode frame");
notify(OMX_EventError,
OMX_ErrorUndefined,
0, // Extra notification data
NULL); // Notification data pointer
return;
}
vpx_codec_iter_t encoded_packet_iterator = NULL;
const vpx_codec_cx_pkt_t* encoded_packet;
while ((encoded_packet = vpx_codec_get_cx_data(
mCodecContext, &encoded_packet_iterator))) {
if (encoded_packet->kind == VPX_CODEC_CX_FRAME_PKT) {
outputBufferHeader->nTimeStamp = encoded_packet->data.frame.pts;
outputBufferHeader->nFlags = 0;
if (encoded_packet->data.frame.flags & VPX_FRAME_IS_KEY)
outputBufferHeader->nFlags |= OMX_BUFFERFLAG_SYNCFRAME;
outputBufferHeader->nOffset = 0;
outputBufferHeader->nFilledLen = encoded_packet->data.frame.sz;
if (outputBufferHeader->nFilledLen > outputBufferHeader->nAllocLen) {
android_errorWriteLog(0x534e4554, "27569635");
notify(OMX_EventError, OMX_ErrorUndefined, 0, 0);
return;
}
memcpy(outputBufferHeader->pBuffer,
encoded_packet->data.frame.buf,
encoded_packet->data.frame.sz);
outputBufferInfo->mOwnedByUs = false;
outputBufferInfoQueue.erase(outputBufferInfoQueue.begin());
notifyFillBufferDone(outputBufferHeader);
}
}
inputBufferInfo->mOwnedByUs = false;
inputBufferInfoQueue.erase(inputBufferInfoQueue.begin());
notifyEmptyBufferDone(inputBufferHeader);
}
}
Commit Message: codecs: handle onReset() for a few encoders
Test: Run PoC binaries
Bug: 34749392
Bug: 34705519
Change-Id: I3356eb615b0e79272d71d72578d363671038c6dd
CWE ID: | void SoftVPXEncoder::onQueueFilled(OMX_U32 portIndex) {
if (mCodecContext == NULL) {
if (OK != initEncoder()) {
ALOGE("Failed to initialize encoder");
notify(OMX_EventError,
OMX_ErrorUndefined,
0, // Extra notification data
NULL); // Notification data pointer
return;
}
}
vpx_codec_err_t codec_return;
List<BufferInfo *> &inputBufferInfoQueue = getPortQueue(kInputPortIndex);
List<BufferInfo *> &outputBufferInfoQueue = getPortQueue(kOutputPortIndex);
while (!inputBufferInfoQueue.empty() && !outputBufferInfoQueue.empty()) {
BufferInfo *inputBufferInfo = *inputBufferInfoQueue.begin();
OMX_BUFFERHEADERTYPE *inputBufferHeader = inputBufferInfo->mHeader;
BufferInfo *outputBufferInfo = *outputBufferInfoQueue.begin();
OMX_BUFFERHEADERTYPE *outputBufferHeader = outputBufferInfo->mHeader;
if (inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) {
inputBufferInfoQueue.erase(inputBufferInfoQueue.begin());
inputBufferInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inputBufferHeader);
outputBufferHeader->nFilledLen = 0;
outputBufferHeader->nFlags = OMX_BUFFERFLAG_EOS;
outputBufferInfoQueue.erase(outputBufferInfoQueue.begin());
outputBufferInfo->mOwnedByUs = false;
notifyFillBufferDone(outputBufferHeader);
return;
}
const uint8_t *source =
inputBufferHeader->pBuffer + inputBufferHeader->nOffset;
size_t frameSize = mWidth * mHeight * 3 / 2;
if (mInputDataIsMeta) {
source = extractGraphicBuffer(
mConversionBuffer, frameSize,
source, inputBufferHeader->nFilledLen,
mWidth, mHeight);
if (source == NULL) {
ALOGE("Unable to extract gralloc buffer in metadata mode");
notify(OMX_EventError, OMX_ErrorUndefined, 0, 0);
return;
}
} else {
if (inputBufferHeader->nFilledLen < frameSize) {
android_errorWriteLog(0x534e4554, "27569635");
notify(OMX_EventError, OMX_ErrorUndefined, 0, 0);
return;
} else if (inputBufferHeader->nFilledLen > frameSize) {
ALOGW("Input buffer contains too many pixels");
}
if (mColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) {
ConvertYUV420SemiPlanarToYUV420Planar(
source, mConversionBuffer, mWidth, mHeight);
source = mConversionBuffer;
}
}
vpx_image_t raw_frame;
vpx_img_wrap(&raw_frame, VPX_IMG_FMT_I420, mWidth, mHeight,
kInputBufferAlignment, (uint8_t *)source);
vpx_enc_frame_flags_t flags = 0;
if (mTemporalPatternLength > 0) {
flags = getEncodeFlags();
}
if (mKeyFrameRequested) {
flags |= VPX_EFLAG_FORCE_KF;
mKeyFrameRequested = false;
}
if (mBitrateUpdated) {
mCodecConfiguration->rc_target_bitrate = mBitrate/1000;
vpx_codec_err_t res = vpx_codec_enc_config_set(mCodecContext,
mCodecConfiguration);
if (res != VPX_CODEC_OK) {
ALOGE("vp8 encoder failed to update bitrate: %s",
vpx_codec_err_to_string(res));
notify(OMX_EventError,
OMX_ErrorUndefined,
0, // Extra notification data
NULL); // Notification data pointer
}
mBitrateUpdated = false;
}
uint32_t frameDuration;
if (inputBufferHeader->nTimeStamp > mLastTimestamp) {
frameDuration = (uint32_t)(inputBufferHeader->nTimeStamp - mLastTimestamp);
} else {
// Use default of 30 fps in case of 0 frame rate.
uint32_t framerate = mFramerate ?: (30 << 16);
frameDuration = (uint32_t)(((uint64_t)1000000 << 16) / framerate);
}
mLastTimestamp = inputBufferHeader->nTimeStamp;
codec_return = vpx_codec_encode(
mCodecContext,
&raw_frame,
inputBufferHeader->nTimeStamp, // in timebase units
frameDuration, // frame duration in timebase units
flags, // frame flags
VPX_DL_REALTIME); // encoding deadline
if (codec_return != VPX_CODEC_OK) {
ALOGE("vpx encoder failed to encode frame");
notify(OMX_EventError,
OMX_ErrorUndefined,
0, // Extra notification data
NULL); // Notification data pointer
return;
}
vpx_codec_iter_t encoded_packet_iterator = NULL;
const vpx_codec_cx_pkt_t* encoded_packet;
while ((encoded_packet = vpx_codec_get_cx_data(
mCodecContext, &encoded_packet_iterator))) {
if (encoded_packet->kind == VPX_CODEC_CX_FRAME_PKT) {
outputBufferHeader->nTimeStamp = encoded_packet->data.frame.pts;
outputBufferHeader->nFlags = 0;
if (encoded_packet->data.frame.flags & VPX_FRAME_IS_KEY)
outputBufferHeader->nFlags |= OMX_BUFFERFLAG_SYNCFRAME;
outputBufferHeader->nOffset = 0;
outputBufferHeader->nFilledLen = encoded_packet->data.frame.sz;
if (outputBufferHeader->nFilledLen > outputBufferHeader->nAllocLen) {
android_errorWriteLog(0x534e4554, "27569635");
notify(OMX_EventError, OMX_ErrorUndefined, 0, 0);
return;
}
memcpy(outputBufferHeader->pBuffer,
encoded_packet->data.frame.buf,
encoded_packet->data.frame.sz);
outputBufferInfo->mOwnedByUs = false;
outputBufferInfoQueue.erase(outputBufferInfoQueue.begin());
notifyFillBufferDone(outputBufferHeader);
}
}
inputBufferInfo->mOwnedByUs = false;
inputBufferInfoQueue.erase(inputBufferInfoQueue.begin());
notifyEmptyBufferDone(inputBufferHeader);
}
}
| 174,012 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void jsR_calllwfunction(js_State *J, int n, js_Function *F, js_Environment *scope)
{
js_Value v;
int i;
jsR_savescope(J, scope);
if (n > F->numparams) {
js_pop(J, F->numparams - n);
n = F->numparams;
}
for (i = n; i < F->varlen; ++i)
js_pushundefined(J);
jsR_run(J, F);
v = *stackidx(J, -1);
TOP = --BOT; /* clear stack */
js_pushvalue(J, v);
jsR_restorescope(J);
}
Commit Message:
CWE ID: CWE-119 | static void jsR_calllwfunction(js_State *J, int n, js_Function *F, js_Environment *scope)
{
js_Value v;
int i;
jsR_savescope(J, scope);
if (n > F->numparams) {
js_pop(J, n - F->numparams);
n = F->numparams;
}
for (i = n; i < F->varlen; ++i)
js_pushundefined(J);
jsR_run(J, F);
v = *stackidx(J, -1);
TOP = --BOT; /* clear stack */
js_pushvalue(J, v);
jsR_restorescope(J);
}
| 165,240 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t CameraService::dump(int fd, const Vector<String16>& args) {
String8 result;
if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
result.appendFormat("Permission Denial: "
"can't dump CameraService from pid=%d, uid=%d\n",
getCallingPid(),
getCallingUid());
write(fd, result.string(), result.size());
} else {
bool locked = tryLock(mServiceLock);
if (!locked) {
result.append("CameraService may be deadlocked\n");
write(fd, result.string(), result.size());
}
bool hasClient = false;
if (!mModule) {
result = String8::format("No camera module available!\n");
write(fd, result.string(), result.size());
return NO_ERROR;
}
result = String8::format("Camera module HAL API version: 0x%x\n",
mModule->common.hal_api_version);
result.appendFormat("Camera module API version: 0x%x\n",
mModule->common.module_api_version);
result.appendFormat("Camera module name: %s\n",
mModule->common.name);
result.appendFormat("Camera module author: %s\n",
mModule->common.author);
result.appendFormat("Number of camera devices: %d\n\n", mNumberOfCameras);
write(fd, result.string(), result.size());
for (int i = 0; i < mNumberOfCameras; i++) {
result = String8::format("Camera %d static information:\n", i);
camera_info info;
status_t rc = mModule->get_camera_info(i, &info);
if (rc != OK) {
result.appendFormat(" Error reading static information!\n");
write(fd, result.string(), result.size());
} else {
result.appendFormat(" Facing: %s\n",
info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
result.appendFormat(" Orientation: %d\n", info.orientation);
int deviceVersion;
if (mModule->common.module_api_version <
CAMERA_MODULE_API_VERSION_2_0) {
deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
} else {
deviceVersion = info.device_version;
}
result.appendFormat(" Device version: 0x%x\n", deviceVersion);
if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
result.appendFormat(" Device static metadata:\n");
write(fd, result.string(), result.size());
dump_indented_camera_metadata(info.static_camera_characteristics,
fd, 2, 4);
} else {
write(fd, result.string(), result.size());
}
}
sp<BasicClient> client = mClient[i].promote();
if (client == 0) {
result = String8::format(" Device is closed, no client instance\n");
write(fd, result.string(), result.size());
continue;
}
hasClient = true;
result = String8::format(" Device is open. Client instance dump:\n");
write(fd, result.string(), result.size());
client->dump(fd, args);
}
if (!hasClient) {
result = String8::format("\nNo active camera clients yet.\n");
write(fd, result.string(), result.size());
}
if (locked) mServiceLock.unlock();
write(fd, "\n", 1);
camera3::CameraTraces::dump(fd, args);
int n = args.size();
for (int i = 0; i + 1 < n; i++) {
String16 verboseOption("-v");
if (args[i] == verboseOption) {
String8 levelStr(args[i+1]);
int level = atoi(levelStr.string());
result = String8::format("\nSetting log level to %d.\n", level);
setLogLevel(level);
write(fd, result.string(), result.size());
}
}
}
return NO_ERROR;
}
Commit Message: Camera: Disallow dumping clients directly
Camera service dumps should only be initiated through
ICameraService::dump.
Bug: 26265403
Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803
CWE ID: CWE-264 | status_t CameraService::dump(int fd, const Vector<String16>& args) {
String8 result;
if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
result.appendFormat("Permission Denial: "
"can't dump CameraService from pid=%d, uid=%d\n",
getCallingPid(),
getCallingUid());
write(fd, result.string(), result.size());
} else {
bool locked = tryLock(mServiceLock);
if (!locked) {
result.append("CameraService may be deadlocked\n");
write(fd, result.string(), result.size());
}
bool hasClient = false;
if (!mModule) {
result = String8::format("No camera module available!\n");
write(fd, result.string(), result.size());
return NO_ERROR;
}
result = String8::format("Camera module HAL API version: 0x%x\n",
mModule->common.hal_api_version);
result.appendFormat("Camera module API version: 0x%x\n",
mModule->common.module_api_version);
result.appendFormat("Camera module name: %s\n",
mModule->common.name);
result.appendFormat("Camera module author: %s\n",
mModule->common.author);
result.appendFormat("Number of camera devices: %d\n\n", mNumberOfCameras);
write(fd, result.string(), result.size());
for (int i = 0; i < mNumberOfCameras; i++) {
result = String8::format("Camera %d static information:\n", i);
camera_info info;
status_t rc = mModule->get_camera_info(i, &info);
if (rc != OK) {
result.appendFormat(" Error reading static information!\n");
write(fd, result.string(), result.size());
} else {
result.appendFormat(" Facing: %s\n",
info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
result.appendFormat(" Orientation: %d\n", info.orientation);
int deviceVersion;
if (mModule->common.module_api_version <
CAMERA_MODULE_API_VERSION_2_0) {
deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
} else {
deviceVersion = info.device_version;
}
result.appendFormat(" Device version: 0x%x\n", deviceVersion);
if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
result.appendFormat(" Device static metadata:\n");
write(fd, result.string(), result.size());
dump_indented_camera_metadata(info.static_camera_characteristics,
fd, 2, 4);
} else {
write(fd, result.string(), result.size());
}
}
sp<BasicClient> client = mClient[i].promote();
if (client == 0) {
result = String8::format(" Device is closed, no client instance\n");
write(fd, result.string(), result.size());
continue;
}
hasClient = true;
result = String8::format(" Device is open. Client instance dump:\n");
write(fd, result.string(), result.size());
client->dumpClient(fd, args);
}
if (!hasClient) {
result = String8::format("\nNo active camera clients yet.\n");
write(fd, result.string(), result.size());
}
if (locked) mServiceLock.unlock();
write(fd, "\n", 1);
camera3::CameraTraces::dump(fd, args);
int n = args.size();
for (int i = 0; i + 1 < n; i++) {
String16 verboseOption("-v");
if (args[i] == verboseOption) {
String8 levelStr(args[i+1]);
int level = atoi(levelStr.string());
result = String8::format("\nSetting log level to %d.\n", level);
setLogLevel(level);
write(fd, result.string(), result.size());
}
}
}
return NO_ERROR;
}
| 173,936 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 rndis_set_response(USBNetState *s,
rndis_set_msg_type *buf, unsigned int length)
{
rndis_set_cmplt_type *resp =
rndis_queue_response(s, sizeof(rndis_set_cmplt_type));
uint32_t bufoffs, buflen;
int ret;
if (!resp)
return USB_RET_STALL;
bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;
buflen = le32_to_cpu(buf->InformationBufferLength);
if (bufoffs + buflen > length)
return USB_RET_STALL;
ret = ndis_set(s, le32_to_cpu(buf->OID),
bufoffs + (uint8_t *) buf, buflen);
resp->MessageLength = cpu_to_le32(sizeof(rndis_set_cmplt_type));
if (ret < 0) {
/* OID not supported */
resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
return 0;
}
resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
return 0;
}
Commit Message:
CWE ID: CWE-189 | static int rndis_set_response(USBNetState *s,
rndis_set_msg_type *buf, unsigned int length)
{
rndis_set_cmplt_type *resp =
rndis_queue_response(s, sizeof(rndis_set_cmplt_type));
uint32_t bufoffs, buflen;
int ret;
if (!resp)
return USB_RET_STALL;
bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;
buflen = le32_to_cpu(buf->InformationBufferLength);
if (buflen > length || bufoffs >= length || bufoffs + buflen > length) {
return USB_RET_STALL;
}
ret = ndis_set(s, le32_to_cpu(buf->OID),
bufoffs + (uint8_t *) buf, buflen);
resp->MessageLength = cpu_to_le32(sizeof(rndis_set_cmplt_type));
if (ret < 0) {
/* OID not supported */
resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
return 0;
}
resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
return 0;
}
| 165,186 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: sctp_chunk_length_valid(struct sctp_chunk *chunk,
__u16 required_length)
{
__u16 chunk_length = ntohs(chunk->chunk_hdr->length);
if (unlikely(chunk_length < required_length))
return 0;
return 1;
}
Commit Message: net: sctp: fix remote memory pressure from excessive queueing
This scenario is not limited to ASCONF, just taken as one
example triggering the issue. When receiving ASCONF probes
in the form of ...
-------------- INIT[ASCONF; ASCONF_ACK] ------------->
<----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------
-------------------- COOKIE-ECHO -------------------->
<-------------------- COOKIE-ACK ---------------------
---- ASCONF_a; [ASCONF_b; ...; ASCONF_n;] JUNK ------>
[...]
---- ASCONF_m; [ASCONF_o; ...; ASCONF_z;] JUNK ------>
... where ASCONF_a, ASCONF_b, ..., ASCONF_z are good-formed
ASCONFs and have increasing serial numbers, we process such
ASCONF chunk(s) marked with !end_of_packet and !singleton,
since we have not yet reached the SCTP packet end. SCTP does
only do verification on a chunk by chunk basis, as an SCTP
packet is nothing more than just a container of a stream of
chunks which it eats up one by one.
We could run into the case that we receive a packet with a
malformed tail, above marked as trailing JUNK. All previous
chunks are here goodformed, so the stack will eat up all
previous chunks up to this point. In case JUNK does not fit
into a chunk header and there are no more other chunks in
the input queue, or in case JUNK contains a garbage chunk
header, but the encoded chunk length would exceed the skb
tail, or we came here from an entirely different scenario
and the chunk has pdiscard=1 mark (without having had a flush
point), it will happen, that we will excessively queue up
the association's output queue (a correct final chunk may
then turn it into a response flood when flushing the
queue ;)): I ran a simple script with incremental ASCONF
serial numbers and could see the server side consuming
excessive amount of RAM [before/after: up to 2GB and more].
The issue at heart is that the chunk train basically ends
with !end_of_packet and !singleton markers and since commit
2e3216cd54b1 ("sctp: Follow security requirement of responding
with 1 packet") therefore preventing an output queue flush
point in sctp_do_sm() -> sctp_cmd_interpreter() on the input
chunk (chunk = event_arg) even though local_cork is set,
but its precedence has changed since then. In the normal
case, the last chunk with end_of_packet=1 would trigger the
queue flush to accommodate possible outgoing bundling.
In the input queue, sctp_inq_pop() seems to do the right thing
in terms of discarding invalid chunks. So, above JUNK will
not enter the state machine and instead be released and exit
the sctp_assoc_bh_rcv() chunk processing loop. It's simply
the flush point being missing at loop exit. Adding a try-flush
approach on the output queue might not work as the underlying
infrastructure might be long gone at this point due to the
side-effect interpreter run.
One possibility, albeit a bit of a kludge, would be to defer
invalid chunk freeing into the state machine in order to
possibly trigger packet discards and thus indirectly a queue
flush on error. It would surely be better to discard chunks
as in the current, perhaps better controlled environment, but
going back and forth, it's simply architecturally not possible.
I tried various trailing JUNK attack cases and it seems to
look good now.
Joint work with Vlad Yasevich.
Fixes: 2e3216cd54b1 ("sctp: Follow security requirement of responding with 1 packet")
Signed-off-by: Daniel Borkmann <[email protected]>
Signed-off-by: Vlad Yasevich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | sctp_chunk_length_valid(struct sctp_chunk *chunk,
__u16 required_length)
{
__u16 chunk_length = ntohs(chunk->chunk_hdr->length);
/* Previously already marked? */
if (unlikely(chunk->pdiscard))
return 0;
if (unlikely(chunk_length < required_length))
return 0;
return 1;
}
| 166,331 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 setup_remaining_vcs(int src_fd, unsigned src_idx, bool utf8) {
struct console_font_op cfo = {
.op = KD_FONT_OP_GET,
.width = UINT_MAX, .height = UINT_MAX,
.charcount = UINT_MAX,
};
struct unimapinit adv = {};
struct unimapdesc unimapd;
_cleanup_free_ struct unipair* unipairs = NULL;
_cleanup_free_ void *fontbuf = NULL;
unsigned i;
int r;
unipairs = new(struct unipair, USHRT_MAX);
if (!unipairs) {
log_oom();
return;
}
/* get metadata of the current font (width, height, count) */
r = ioctl(src_fd, KDFONTOP, &cfo);
if (r < 0)
log_warning_errno(errno, "KD_FONT_OP_GET failed while trying to get the font metadata: %m");
else {
/* verify parameter sanity first */
if (cfo.width > 32 || cfo.height > 32 || cfo.charcount > 512)
log_warning("Invalid font metadata - width: %u (max 32), height: %u (max 32), count: %u (max 512)",
cfo.width, cfo.height, cfo.charcount);
else {
/*
* Console fonts supported by the kernel are limited in size to 32 x 32 and maximum 512
* characters. Thus with 1 bit per pixel it requires up to 65536 bytes. The height always
* requires 32 per glyph, regardless of the actual height - see the comment above #define
* max_font_size 65536 in drivers/tty/vt/vt.c for more details.
*/
fontbuf = malloc_multiply((cfo.width + 7) / 8 * 32, cfo.charcount);
if (!fontbuf) {
log_oom();
return;
}
/* get fonts from the source console */
cfo.data = fontbuf;
r = ioctl(src_fd, KDFONTOP, &cfo);
if (r < 0)
log_warning_errno(errno, "KD_FONT_OP_GET failed while trying to read the font data: %m");
else {
unimapd.entries = unipairs;
unimapd.entry_ct = USHRT_MAX;
r = ioctl(src_fd, GIO_UNIMAP, &unimapd);
if (r < 0)
log_warning_errno(errno, "GIO_UNIMAP failed while trying to read unicode mappings: %m");
else
cfo.op = KD_FONT_OP_SET;
}
}
}
if (cfo.op != KD_FONT_OP_SET)
log_warning("Fonts will not be copied to remaining consoles");
for (i = 1; i <= 63; i++) {
char ttyname[sizeof("/dev/tty63")];
_cleanup_close_ int fd_d = -1;
if (i == src_idx || verify_vc_allocation(i) < 0)
continue;
/* try to open terminal */
xsprintf(ttyname, "/dev/tty%u", i);
fd_d = open_terminal(ttyname, O_RDWR|O_CLOEXEC|O_NOCTTY);
if (fd_d < 0) {
log_warning_errno(fd_d, "Unable to open tty%u, fonts will not be copied: %m", i);
continue;
}
if (verify_vc_kbmode(fd_d) < 0)
continue;
toggle_utf8(ttyname, fd_d, utf8);
if (cfo.op != KD_FONT_OP_SET)
continue;
r = ioctl(fd_d, KDFONTOP, &cfo);
if (r < 0) {
int last_errno, mode;
/* The fonts couldn't have been copied. It might be due to the
* terminal being in graphical mode. In this case the kernel
* returns -EINVAL which is too generic for distinguishing this
* specific case. So we need to retrieve the terminal mode and if
* the graphical mode is in used, let's assume that something else
* is using the terminal and the failure was expected as we
* shouldn't have tried to copy the fonts. */
last_errno = errno;
if (ioctl(fd_d, KDGETMODE, &mode) >= 0 && mode != KD_TEXT)
log_debug("KD_FONT_OP_SET skipped: tty%u is not in text mode", i);
else
log_warning_errno(last_errno, "KD_FONT_OP_SET failed, fonts will not be copied to tty%u: %m", i);
continue;
}
/*
* copy unicode translation table unimapd is a ushort count and a pointer
* to an array of struct unipair { ushort, ushort }
*/
r = ioctl(fd_d, PIO_UNIMAPCLR, &adv);
if (r < 0) {
log_warning_errno(errno, "PIO_UNIMAPCLR failed, unimaps might be incorrect for tty%u: %m", i);
continue;
}
r = ioctl(fd_d, PIO_UNIMAP, &unimapd);
if (r < 0) {
log_warning_errno(errno, "PIO_UNIMAP failed, unimaps might be incorrect for tty%u: %m", i);
continue;
}
log_debug("Font and unimap successfully copied to %s", ttyname);
}
}
Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check
VT kbd reset check
CWE ID: CWE-255 | static void setup_remaining_vcs(int src_fd, unsigned src_idx, bool utf8) {
struct console_font_op cfo = {
.op = KD_FONT_OP_GET,
.width = UINT_MAX, .height = UINT_MAX,
.charcount = UINT_MAX,
};
struct unimapinit adv = {};
struct unimapdesc unimapd;
_cleanup_free_ struct unipair* unipairs = NULL;
_cleanup_free_ void *fontbuf = NULL;
unsigned i;
int r;
unipairs = new(struct unipair, USHRT_MAX);
if (!unipairs) {
log_oom();
return;
}
/* get metadata of the current font (width, height, count) */
r = ioctl(src_fd, KDFONTOP, &cfo);
if (r < 0)
log_warning_errno(errno, "KD_FONT_OP_GET failed while trying to get the font metadata: %m");
else {
/* verify parameter sanity first */
if (cfo.width > 32 || cfo.height > 32 || cfo.charcount > 512)
log_warning("Invalid font metadata - width: %u (max 32), height: %u (max 32), count: %u (max 512)",
cfo.width, cfo.height, cfo.charcount);
else {
/*
* Console fonts supported by the kernel are limited in size to 32 x 32 and maximum 512
* characters. Thus with 1 bit per pixel it requires up to 65536 bytes. The height always
* requires 32 per glyph, regardless of the actual height - see the comment above #define
* max_font_size 65536 in drivers/tty/vt/vt.c for more details.
*/
fontbuf = malloc_multiply((cfo.width + 7) / 8 * 32, cfo.charcount);
if (!fontbuf) {
log_oom();
return;
}
/* get fonts from the source console */
cfo.data = fontbuf;
r = ioctl(src_fd, KDFONTOP, &cfo);
if (r < 0)
log_warning_errno(errno, "KD_FONT_OP_GET failed while trying to read the font data: %m");
else {
unimapd.entries = unipairs;
unimapd.entry_ct = USHRT_MAX;
r = ioctl(src_fd, GIO_UNIMAP, &unimapd);
if (r < 0)
log_warning_errno(errno, "GIO_UNIMAP failed while trying to read unicode mappings: %m");
else
cfo.op = KD_FONT_OP_SET;
}
}
}
if (cfo.op != KD_FONT_OP_SET)
log_warning("Fonts will not be copied to remaining consoles");
for (i = 1; i <= 63; i++) {
char ttyname[sizeof("/dev/tty63")];
_cleanup_close_ int fd_d = -1;
if (i == src_idx || verify_vc_allocation(i) < 0)
continue;
/* try to open terminal */
xsprintf(ttyname, "/dev/tty%u", i);
fd_d = open_terminal(ttyname, O_RDWR|O_CLOEXEC|O_NOCTTY);
if (fd_d < 0) {
log_warning_errno(fd_d, "Unable to open tty%u, fonts will not be copied: %m", i);
continue;
}
if (vt_verify_kbmode(fd_d) < 0)
continue;
toggle_utf8(ttyname, fd_d, utf8);
if (cfo.op != KD_FONT_OP_SET)
continue;
r = ioctl(fd_d, KDFONTOP, &cfo);
if (r < 0) {
int last_errno, mode;
/* The fonts couldn't have been copied. It might be due to the
* terminal being in graphical mode. In this case the kernel
* returns -EINVAL which is too generic for distinguishing this
* specific case. So we need to retrieve the terminal mode and if
* the graphical mode is in used, let's assume that something else
* is using the terminal and the failure was expected as we
* shouldn't have tried to copy the fonts. */
last_errno = errno;
if (ioctl(fd_d, KDGETMODE, &mode) >= 0 && mode != KD_TEXT)
log_debug("KD_FONT_OP_SET skipped: tty%u is not in text mode", i);
else
log_warning_errno(last_errno, "KD_FONT_OP_SET failed, fonts will not be copied to tty%u: %m", i);
continue;
}
/*
* copy unicode translation table unimapd is a ushort count and a pointer
* to an array of struct unipair { ushort, ushort }
*/
r = ioctl(fd_d, PIO_UNIMAPCLR, &adv);
if (r < 0) {
log_warning_errno(errno, "PIO_UNIMAPCLR failed, unimaps might be incorrect for tty%u: %m", i);
continue;
}
r = ioctl(fd_d, PIO_UNIMAP, &unimapd);
if (r < 0) {
log_warning_errno(errno, "PIO_UNIMAP failed, unimaps might be incorrect for tty%u: %m", i);
continue;
}
log_debug("Font and unimap successfully copied to %s", ttyname);
}
}
| 169,778 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: zsetstrokecolor(i_ctx_t * i_ctx_p)
{
int code;
code = zswapcolors(i_ctx_p);
if (code < 0)
/* Set up for the continuation procedure which will finish by restoring the fill colour space */
/* Make sure the exec stack has enough space */
check_estack(1);
/* Now, the actual continuation routine */
push_op_estack(setstrokecolor_cont);
code = zsetcolor(i_ctx_p);
if (code >= 0)
if (code >= 0)
return o_push_estack;
return code;
}
Commit Message:
CWE ID: CWE-119 | zsetstrokecolor(i_ctx_t * i_ctx_p)
{
int code;
es_ptr iesp = esp; /* preserve exec stack in case of error */
code = zswapcolors(i_ctx_p);
if (code < 0)
/* Set up for the continuation procedure which will finish by restoring the fill colour space */
/* Make sure the exec stack has enough space */
check_estack(1);
/* Now, the actual continuation routine */
push_op_estack(setstrokecolor_cont);
code = zsetcolor(i_ctx_p);
if (code >= 0)
if (code >= 0)
return o_push_estack;
/* Something went wrong, swap back to the non-stroking colour and restore the exec stack */
esp = iesp;
(void)zswapcolors(i_ctx_p);
return code;
}
| 164,699 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: wb_prep(netdissect_options *ndo,
const struct pkt_prep *prep, u_int len)
{
int n;
const struct pgstate *ps;
const u_char *ep = ndo->ndo_snapend;
ND_PRINT((ndo, " wb-prep:"));
if (len < sizeof(*prep)) {
return (-1);
}
n = EXTRACT_32BITS(&prep->pp_n);
ps = (const struct pgstate *)(prep + 1);
while (--n >= 0 && !ND_TTEST(*ps)) {
const struct id_off *io, *ie;
char c = '<';
ND_PRINT((ndo, " %u/%s:%u",
EXTRACT_32BITS(&ps->slot),
ipaddr_string(ndo, &ps->page.p_sid),
EXTRACT_32BITS(&ps->page.p_uid)));
io = (struct id_off *)(ps + 1);
for (ie = io + ps->nid; io < ie && !ND_TTEST(*io); ++io) {
ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id),
EXTRACT_32BITS(&io->off)));
c = ',';
}
ND_PRINT((ndo, ">"));
ps = (struct pgstate *)io;
}
return ((u_char *)ps <= ep? 0 : -1);
}
Commit Message: whiteboard: fixup a few reversed tests (GH #446)
This is a follow-up to commit 3a3ec26.
CWE ID: CWE-20 | wb_prep(netdissect_options *ndo,
const struct pkt_prep *prep, u_int len)
{
int n;
const struct pgstate *ps;
const u_char *ep = ndo->ndo_snapend;
ND_PRINT((ndo, " wb-prep:"));
if (len < sizeof(*prep)) {
return (-1);
}
n = EXTRACT_32BITS(&prep->pp_n);
ps = (const struct pgstate *)(prep + 1);
while (--n >= 0 && ND_TTEST(*ps)) {
const struct id_off *io, *ie;
char c = '<';
ND_PRINT((ndo, " %u/%s:%u",
EXTRACT_32BITS(&ps->slot),
ipaddr_string(ndo, &ps->page.p_sid),
EXTRACT_32BITS(&ps->page.p_uid)));
io = (struct id_off *)(ps + 1);
for (ie = io + ps->nid; io < ie && ND_TTEST(*io); ++io) {
ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id),
EXTRACT_32BITS(&io->off)));
c = ',';
}
ND_PRINT((ndo, ">"));
ps = (struct pgstate *)io;
}
return ((u_char *)ps <= ep? 0 : -1);
}
| 168,893 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
unsigned long addr, unsigned long end,
swp_entry_t entry, struct page *page)
{
pmd_t *pmd;
unsigned long next;
int ret;
pmd = pmd_offset(pud, addr);
do {
next = pmd_addr_end(addr, end);
if (unlikely(pmd_trans_huge(*pmd)))
continue;
if (pmd_none_or_clear_bad(pmd))
continue;
ret = unuse_pte_range(vma, pmd, addr, next, entry, page);
if (ret)
return ret;
} while (pmd++, addr = next, addr != end);
return 0;
}
Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode
commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream.
In some cases it may happen that pmd_none_or_clear_bad() is called with
the mmap_sem hold in read mode. In those cases the huge page faults can
allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a
false positive from pmd_bad() that will not like to see a pmd
materializing as trans huge.
It's not khugepaged causing the problem, khugepaged holds the mmap_sem
in write mode (and all those sites must hold the mmap_sem in read mode
to prevent pagetables to go away from under them, during code review it
seems vm86 mode on 32bit kernels requires that too unless it's
restricted to 1 thread per process or UP builds). The race is only with
the huge pagefaults that can convert a pmd_none() into a
pmd_trans_huge().
Effectively all these pmd_none_or_clear_bad() sites running with
mmap_sem in read mode are somewhat speculative with the page faults, and
the result is always undefined when they run simultaneously. This is
probably why it wasn't common to run into this. For example if the
madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page
fault, the hugepage will not be zapped, if the page fault runs first it
will be zapped.
Altering pmd_bad() not to error out if it finds hugepmds won't be enough
to fix this, because zap_pmd_range would then proceed to call
zap_pte_range (which would be incorrect if the pmd become a
pmd_trans_huge()).
The simplest way to fix this is to read the pmd in the local stack
(regardless of what we read, no need of actual CPU barriers, only
compiler barrier needed), and be sure it is not changing under the code
that computes its value. Even if the real pmd is changing under the
value we hold on the stack, we don't care. If we actually end up in
zap_pte_range it means the pmd was not none already and it was not huge,
and it can't become huge from under us (khugepaged locking explained
above).
All we need is to enforce that there is no way anymore that in a code
path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad
can run into a hugepmd. The overhead of a barrier() is just a compiler
tweak and should not be measurable (I only added it for THP builds). I
don't exclude different compiler versions may have prevented the race
too by caching the value of *pmd on the stack (that hasn't been
verified, but it wouldn't be impossible considering
pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines
and there's no external function called in between pmd_trans_huge and
pmd_none_or_clear_bad).
if (pmd_trans_huge(*pmd)) {
if (next-addr != HPAGE_PMD_SIZE) {
VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));
split_huge_page_pmd(vma->vm_mm, pmd);
} else if (zap_huge_pmd(tlb, vma, pmd, addr))
continue;
/* fall through */
}
if (pmd_none_or_clear_bad(pmd))
Because this race condition could be exercised without special
privileges this was reported in CVE-2012-1179.
The race was identified and fully explained by Ulrich who debugged it.
I'm quoting his accurate explanation below, for reference.
====== start quote =======
mapcount 0 page_mapcount 1
kernel BUG at mm/huge_memory.c:1384!
At some point prior to the panic, a "bad pmd ..." message similar to the
following is logged on the console:
mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).
The "bad pmd ..." message is logged by pmd_clear_bad() before it clears
the page's PMD table entry.
143 void pmd_clear_bad(pmd_t *pmd)
144 {
-> 145 pmd_ERROR(*pmd);
146 pmd_clear(pmd);
147 }
After the PMD table entry has been cleared, there is an inconsistency
between the actual number of PMD table entries that are mapping the page
and the page's map count (_mapcount field in struct page). When the page
is subsequently reclaimed, __split_huge_page() detects this inconsistency.
1381 if (mapcount != page_mapcount(page))
1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1383 mapcount, page_mapcount(page));
-> 1384 BUG_ON(mapcount != page_mapcount(page));
The root cause of the problem is a race of two threads in a multithreaded
process. Thread B incurs a page fault on a virtual address that has never
been accessed (PMD entry is zero) while Thread A is executing an madvise()
system call on a virtual address within the same 2 MB (huge page) range.
virtual address space
.---------------------.
| |
| |
.-|---------------------|
| | |
| | |<-- B(fault)
| | |
2 MB | |/////////////////////|-.
huge < |/////////////////////| > A(range)
page | |/////////////////////|-'
| | |
| | |
'-|---------------------|
| |
| |
'---------------------'
- Thread A is executing an madvise(..., MADV_DONTNEED) system call
on the virtual address range "A(range)" shown in the picture.
sys_madvise
// Acquire the semaphore in shared mode.
down_read(¤t->mm->mmap_sem)
...
madvise_vma
switch (behavior)
case MADV_DONTNEED:
madvise_dontneed
zap_page_range
unmap_vmas
unmap_page_range
zap_pud_range
zap_pmd_range
//
// Assume that this huge page has never been accessed.
// I.e. content of the PMD entry is zero (not mapped).
//
if (pmd_trans_huge(*pmd)) {
// We don't get here due to the above assumption.
}
//
// Assume that Thread B incurred a page fault and
.---------> // sneaks in here as shown below.
| //
| if (pmd_none_or_clear_bad(pmd))
| {
| if (unlikely(pmd_bad(*pmd)))
| pmd_clear_bad
| {
| pmd_ERROR
| // Log "bad pmd ..." message here.
| pmd_clear
| // Clear the page's PMD entry.
| // Thread B incremented the map count
| // in page_add_new_anon_rmap(), but
| // now the page is no longer mapped
| // by a PMD entry (-> inconsistency).
| }
| }
|
v
- Thread B is handling a page fault on virtual address "B(fault)" shown
in the picture.
...
do_page_fault
__do_page_fault
// Acquire the semaphore in shared mode.
down_read_trylock(&mm->mmap_sem)
...
handle_mm_fault
if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))
// We get here due to the above assumption (PMD entry is zero).
do_huge_pmd_anonymous_page
alloc_hugepage_vma
// Allocate a new transparent huge page here.
...
__do_huge_pmd_anonymous_page
...
spin_lock(&mm->page_table_lock)
...
page_add_new_anon_rmap
// Here we increment the page's map count (starts at -1).
atomic_set(&page->_mapcount, 0)
set_pmd_at
// Here we set the page's PMD entry which will be cleared
// when Thread A calls pmd_clear_bad().
...
spin_unlock(&mm->page_table_lock)
The mmap_sem does not prevent the race because both threads are acquiring
it in shared mode (down_read). Thread B holds the page_table_lock while
the page's map count and PMD table entry are updated. However, Thread A
does not synchronize on that lock.
====== end quote =======
[[email protected]: checkpatch fixes]
Reported-by: Ulrich Obergfell <[email protected]>
Signed-off-by: Andrea Arcangeli <[email protected]>
Acked-by: Johannes Weiner <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Dave Jones <[email protected]>
Acked-by: Larry Woodman <[email protected]>
Acked-by: Rik van Riel <[email protected]>
Cc: Mark Salter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-264 | static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
unsigned long addr, unsigned long end,
swp_entry_t entry, struct page *page)
{
pmd_t *pmd;
unsigned long next;
int ret;
pmd = pmd_offset(pud, addr);
do {
next = pmd_addr_end(addr, end);
if (pmd_none_or_trans_huge_or_clear_bad(pmd))
continue;
ret = unuse_pte_range(vma, pmd, addr, next, entry, page);
if (ret)
return ret;
} while (pmd++, addr = next, addr != end);
return 0;
}
| 165,637 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: display_sigset( const char *msg, sigset_t *mask )
{
int signo;
NameTableIterator next_sig( SigNames );
if( msg ) {
dprintf( D_ALWAYS, msg );
}
while( (signo = next_sig()) != -1 ) {
if( sigismember(mask,signo) ) {
dprintf( D_ALWAYS | D_NOHEADER, "%s ", SigNames.get_name(signo) );
}
}
dprintf( D_ALWAYS | D_NOHEADER, "\n" );
}
Commit Message:
CWE ID: CWE-134 | display_sigset( const char *msg, sigset_t *mask )
{
int signo;
NameTableIterator next_sig( SigNames );
if( msg ) {
dprintf( D_ALWAYS, "%s", msg );
}
while( (signo = next_sig()) != -1 ) {
if( sigismember(mask,signo) ) {
dprintf( D_ALWAYS | D_NOHEADER, "%s ", SigNames.get_name(signo) );
}
}
dprintf( D_ALWAYS | D_NOHEADER, "\n" );
}
| 165,385 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: standard_info_part2(standard_display *dp, png_const_structp pp,
png_const_infop pi, int nImages)
{
/* Record cbRow now that it can be found. */
dp->pixel_size = bit_size(pp, png_get_color_type(pp, pi),
png_get_bit_depth(pp, pi));
dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size;
dp->cbRow = png_get_rowbytes(pp, pi);
/* Validate the rowbytes here again. */
if (dp->cbRow != (dp->bit_width+7)/8)
png_error(pp, "bad png_get_rowbytes calculation");
/* Then ensure there is enough space for the output image(s). */
store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | standard_info_part2(standard_display *dp, png_const_structp pp,
png_const_infop pi, int nImages)
{
/* Record cbRow now that it can be found. */
{
png_byte ct = png_get_color_type(pp, pi);
png_byte bd = png_get_bit_depth(pp, pi);
if (bd >= 8 && (ct == PNG_COLOR_TYPE_RGB || ct == PNG_COLOR_TYPE_GRAY) &&
dp->filler)
ct |= 4; /* handle filler as faked alpha channel */
dp->pixel_size = bit_size(pp, ct, bd);
}
dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size;
dp->cbRow = png_get_rowbytes(pp, pi);
/* Validate the rowbytes here again. */
if (dp->cbRow != (dp->bit_width+7)/8)
png_error(pp, "bad png_get_rowbytes calculation");
/* Then ensure there is enough space for the output image(s). */
store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h);
}
| 173,699 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine 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 HeapAllocator::backingFree(void* address) {
if (!address)
return;
ThreadState* state = ThreadState::current();
if (state->sweepForbidden())
return;
ASSERT(!state->isInGC());
BasePage* page = pageFromObject(address);
if (page->isLargeObjectPage() || page->arena()->getThreadState() != state)
return;
HeapObjectHeader* header = HeapObjectHeader::fromPayload(address);
ASSERT(header->checkHeader());
NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage();
state->promptlyFreed(header->gcInfoIndex());
arena->promptlyFreeObject(header);
}
Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect.
This requires changing its signature. This is a preliminary stage to making it
private.
BUG=633030
Review-Url: https://codereview.chromium.org/2698673003
Cr-Commit-Position: refs/heads/master@{#460489}
CWE ID: CWE-119 | void HeapAllocator::backingFree(void* address) {
if (!address)
return;
ThreadState* state = ThreadState::current();
if (state->sweepForbidden())
return;
ASSERT(!state->isInGC());
BasePage* page = pageFromObject(address);
if (page->isLargeObjectPage() || page->arena()->getThreadState() != state)
return;
HeapObjectHeader* header = HeapObjectHeader::fromPayload(address);
header->checkHeader();
NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage();
state->promptlyFreed(header->gcInfoIndex());
arena->promptlyFreeObject(header);
}
| 172,706 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.