prompt
stringlengths 1.19k
236k
| output
int64 0
1
|
---|---|
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) {
xmlChar limit = 0;
xmlChar *buf = NULL;
xmlChar *rep = NULL;
int len = 0;
int buf_size = 0;
int c, l, in_space = 0;
xmlChar *current = NULL;
xmlEntityPtr ent;
if (NXT(0) == '"') {
ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE;
limit = '"';
NEXT;
} else if (NXT(0) == '\'') {
limit = '\'';
ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE;
NEXT;
} else {
xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL);
return(NULL);
}
/*
* allocate a translation buffer.
*/
buf_size = XML_PARSER_BUFFER_SIZE;
buf = (xmlChar *) xmlMallocAtomic(buf_size * sizeof(xmlChar));
if (buf == NULL) goto mem_error;
/*
* OK loop until we reach one of the ending char or a size limit.
*/
c = CUR_CHAR(l);
while ((NXT(0) != limit) && /* checked */
(IS_CHAR(c)) && (c != '<')) {
if (c == 0) break;
if (c == '&') {
in_space = 0;
if (NXT(1) == '#') {
int val = xmlParseCharRef(ctxt);
if (val == '&') {
if (ctxt->replaceEntities) {
if (len > buf_size - 10) {
growBuffer(buf, 10);
}
buf[len++] = '&';
} else {
/*
* The reparsing will be done in xmlStringGetNodeList()
* called by the attribute() function in SAX.c
*/
if (len > buf_size - 10) {
growBuffer(buf, 10);
}
buf[len++] = '&';
buf[len++] = '#';
buf[len++] = '3';
buf[len++] = '8';
buf[len++] = ';';
}
} else if (val != 0) {
if (len > buf_size - 10) {
growBuffer(buf, 10);
}
len += xmlCopyChar(0, &buf[len], val);
}
} else {
ent = xmlParseEntityRef(ctxt);
ctxt->nbentities++;
if (ent != NULL)
ctxt->nbentities += ent->owner;
if ((ent != NULL) &&
(ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
if (len > buf_size - 10) {
growBuffer(buf, 10);
}
if ((ctxt->replaceEntities == 0) &&
(ent->content[0] == '&')) {
buf[len++] = '&';
buf[len++] = '#';
buf[len++] = '3';
buf[len++] = '8';
buf[len++] = ';';
} else {
buf[len++] = ent->content[0];
}
} else if ((ent != NULL) &&
(ctxt->replaceEntities != 0)) {
if (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) {
rep = xmlStringDecodeEntities(ctxt, ent->content,
XML_SUBSTITUTE_REF,
0, 0, 0);
if (rep != NULL) {
current = rep;
while (*current != 0) { /* non input consuming */
if ((*current == 0xD) || (*current == 0xA) ||
(*current == 0x9)) {
buf[len++] = 0x20;
current++;
} else
buf[len++] = *current++;
if (len > buf_size - 10) {
growBuffer(buf, 10);
}
}
xmlFree(rep);
rep = NULL;
}
} else {
if (len > buf_size - 10) {
growBuffer(buf, 10);
}
if (ent->content != NULL)
buf[len++] = ent->content[0];
}
} else if (ent != NULL) {
int i = xmlStrlen(ent->name);
const xmlChar *cur = ent->name;
/*
* This may look absurd but is needed to detect
* entities problems
*/
if ((ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) &&
(ent->content != NULL)) {
rep = xmlStringDecodeEntities(ctxt, ent->content,
XML_SUBSTITUTE_REF, 0, 0, 0);
if (rep != NULL) {
xmlFree(rep);
rep = NULL;
}
}
/*
* Just output the reference
*/
buf[len++] = '&';
while (len > buf_size - i - 10) {
growBuffer(buf, i + 10);
}
for (;i > 0;i--)
buf[len++] = *cur++;
buf[len++] = ';';
}
}
} else {
if ((c == 0x20) || (c == 0xD) || (c == 0xA) || (c == 0x9)) {
if ((len != 0) || (!normalize)) {
if ((!normalize) || (!in_space)) {
COPY_BUF(l,buf,len,0x20);
while (len > buf_size - 10) {
growBuffer(buf, 10);
}
}
in_space = 1;
}
} else {
in_space = 0;
COPY_BUF(l,buf,len,c);
if (len > buf_size - 10) {
growBuffer(buf, 10);
}
}
NEXTL(l);
}
GROW;
c = CUR_CHAR(l);
}
if ((in_space) && (normalize)) {
while (buf[len - 1] == 0x20) len--;
}
buf[len] = 0;
if (RAW == '<') {
xmlFatalErr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, NULL);
} else if (RAW != limit) {
if ((c != 0) && (!IS_CHAR(c))) {
xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR,
"invalid character in attribute value\n");
} else {
xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
"AttValue: ' expected\n");
}
} else
NEXT;
if (attlen != NULL) *attlen = len;
return(buf);
mem_error:
xmlErrMemory(ctxt, NULL);
if (buf != NULL)
xmlFree(buf);
if (rep != NULL)
xmlFree(rep);
return(NULL);
}
Commit Message: Add a check to prevent len from going negative in xmlParseAttValueComplex.
BUG=158249
Review URL: https://chromiumcodereview.appspot.com/11343029
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@164867 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: GF_Err gf_isom_avc_set_inband_config(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex)
{
return gf_isom_avc_config_update_ex(the_file, trackNumber, DescriptionIndex, NULL, 3);
}
Commit Message: fix some exploitable overflows (#994, #997)
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: decompileAction(int n, SWF_ACTION *actions, int maxn)
{
if( n > maxn ) SWF_error("Action overflow!!");
#ifdef DEBUG
fprintf(stderr,"%d:\tACTION[%3.3d]: %s\n",
actions[n].SWF_ACTIONRECORD.Offset, n,
actionName(actions[n].SWF_ACTIONRECORD.ActionCode));
#endif
switch(actions[n].SWF_ACTIONRECORD.ActionCode)
{
case SWFACTION_END:
return 0;
case SWFACTION_CONSTANTPOOL:
decompileCONSTANTPOOL(&actions[n]);
return 0;
case SWFACTION_GOTOLABEL:
return decompileGOTOFRAME(n, actions, maxn,1);
case SWFACTION_GOTOFRAME:
return decompileGOTOFRAME(n, actions, maxn,0);
case SWFACTION_GOTOFRAME2:
return decompileGOTOFRAME2(n, actions, maxn);
case SWFACTION_WAITFORFRAME:
decompileWAITFORFRAME(&actions[n]);
return 0;
case SWFACTION_GETURL2:
decompileGETURL2(&actions[n]);
return 0;
case SWFACTION_GETURL:
decompileGETURL(&actions[n]);
return 0;
case SWFACTION_PUSH:
decompilePUSH(&actions[n]);
return 0;
case SWFACTION_PUSHDUP:
decompilePUSHDUP(&actions[n]);
return 0;
case SWFACTION_STACKSWAP:
decompileSTACKSWAP(&actions[n]);
return 0;
case SWFACTION_SETPROPERTY:
decompileSETPROPERTY(n, actions, maxn);
return 0;
case SWFACTION_GETPROPERTY:
decompileGETPROPERTY(n, actions, maxn);
return 0;
case SWFACTION_GETTIME:
return decompileGETTIME(n, actions, maxn);
case SWFACTION_TRACE:
decompileTRACE(n, actions, maxn);
return 0;
case SWFACTION_CALLFRAME:
decompileCALLFRAME(n, actions, maxn);
return 0;
case SWFACTION_EXTENDS:
decompileEXTENDS(n, actions, maxn);
return 0;
case SWFACTION_INITOBJECT:
decompileINITOBJECT(n, actions, maxn);
return 0;
case SWFACTION_NEWOBJECT:
decompileNEWOBJECT(n, actions, maxn);
return 0;
case SWFACTION_NEWMETHOD:
decompileNEWMETHOD(n, actions, maxn);
return 0;
case SWFACTION_GETMEMBER:
decompileGETMEMBER(n, actions, maxn);
return 0;
case SWFACTION_SETMEMBER:
decompileSETMEMBER(n, actions, maxn);
return 0;
case SWFACTION_GETVARIABLE:
decompileGETVARIABLE(n, actions, maxn);
return 0;
case SWFACTION_SETVARIABLE:
decompileSETVARIABLE(n, actions, maxn, 0);
return 0;
case SWFACTION_DEFINELOCAL:
decompileSETVARIABLE(n, actions, maxn, 1);
return 0;
case SWFACTION_DEFINELOCAL2:
decompileDEFINELOCAL2(n, actions, maxn);
return 0;
case SWFACTION_DECREMENT:
return decompileINCR_DECR(n, actions, maxn, 0);
case SWFACTION_INCREMENT:
return decompileINCR_DECR(n, actions, maxn,1);
case SWFACTION_STOREREGISTER:
decompileSTOREREGISTER(n, actions, maxn);
return 0;
case SWFACTION_JUMP:
return decompileJUMP(n, actions, maxn);
case SWFACTION_RETURN:
decompileRETURN(n, actions, maxn);
return 0;
case SWFACTION_LOGICALNOT:
return decompileLogicalNot(n, actions, maxn);
case SWFACTION_IF:
return decompileIF(n, actions, maxn);
case SWFACTION_WITH:
decompileWITH(n, actions, maxn);
return 0;
case SWFACTION_ENUMERATE:
return decompileENUMERATE(n, actions, maxn, 0);
case SWFACTION_ENUMERATE2 :
return decompileENUMERATE(n, actions, maxn,1);
case SWFACTION_INITARRAY:
return decompileINITARRAY(n, actions, maxn);
case SWFACTION_DEFINEFUNCTION:
return decompileDEFINEFUNCTION(n, actions, maxn,0);
case SWFACTION_DEFINEFUNCTION2:
return decompileDEFINEFUNCTION(n, actions, maxn,1);
case SWFACTION_CALLFUNCTION:
return decompileCALLFUNCTION(n, actions, maxn);
case SWFACTION_CALLMETHOD:
return decompileCALLMETHOD(n, actions, maxn);
case SWFACTION_INSTANCEOF:
case SWFACTION_SHIFTLEFT:
case SWFACTION_SHIFTRIGHT:
case SWFACTION_SHIFTRIGHT2:
case SWFACTION_ADD:
case SWFACTION_ADD2:
case SWFACTION_SUBTRACT:
case SWFACTION_MULTIPLY:
case SWFACTION_DIVIDE:
case SWFACTION_MODULO:
case SWFACTION_BITWISEAND:
case SWFACTION_BITWISEOR:
case SWFACTION_BITWISEXOR:
case SWFACTION_EQUAL:
case SWFACTION_EQUALS2:
case SWFACTION_LESS2:
case SWFACTION_LOGICALAND:
case SWFACTION_LOGICALOR:
case SWFACTION_GREATER:
case SWFACTION_LESSTHAN:
case SWFACTION_STRINGEQ:
case SWFACTION_STRINGCOMPARE:
case SWFACTION_STRICTEQUALS:
return decompileArithmeticOp(n, actions, maxn);
case SWFACTION_POP:
pop();
return 0;
case SWFACTION_STARTDRAG:
return decompileSTARTDRAG(n, actions, maxn);
case SWFACTION_DELETE:
return decompileDELETE(n, actions, maxn,0);
case SWFACTION_DELETE2:
return decompileDELETE(n, actions, maxn,1);
case SWFACTION_TARGETPATH:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"targetPath");
case SWFACTION_TYPEOF:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"typeof");
case SWFACTION_ORD:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"ord");
case SWFACTION_CHR:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"chr");
case SWFACTION_INT:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"int");
case SWFACTION_TOSTRING:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"String");
case SWFACTION_TONUMBER:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"Number");
case SWFACTION_RANDOMNUMBER:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"random");
case SWFACTION_STRINGLENGTH:
return decompileSingleArgBuiltInFunctionCall(n, actions, maxn,"length");
case SWFACTION_PLAY:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"play");
case SWFACTION_STOP:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"stop");
case SWFACTION_NEXTFRAME:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"nextFrame");
case SWFACTION_PREVFRAME:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"prevFrame");
case SWFACTION_ENDDRAG:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"stopDrag");
case SWFACTION_STOPSOUNDS:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"stopAllSounds");
case SWFACTION_TOGGLEQUALITY:
return decompile_Null_ArgBuiltInFunctionCall(n, actions, maxn,"toggleHighQuality");
case SWFACTION_MBSUBSTRING:
case SWFACTION_SUBSTRING:
return decompileSUBSTRING(n, actions, maxn);
case SWFACTION_STRINGCONCAT:
return decompileSTRINGCONCAT(n, actions, maxn);
case SWFACTION_REMOVECLIP:
return decompileREMOVECLIP(n, actions, maxn);
case SWFACTION_DUPLICATECLIP:
return decompileDUPLICATECLIP(n, actions, maxn);
case SWFACTION_SETTARGET:
return decompileSETTARGET(n, actions, maxn,0);
case SWFACTION_SETTARGET2:
return decompileSETTARGET(n, actions, maxn,1);
case SWFACTION_IMPLEMENTSOP:
return decompileIMPLEMENTS(n, actions, maxn);
case SWFACTION_CASTOP:
return decompileCAST(n, actions, maxn);
case SWFACTION_THROW:
return decompileTHROW(n, actions, maxn);
case SWFACTION_TRY:
return decompileTRY(n, actions, maxn);
default:
outputSWF_ACTION(n,&actions[n]);
return 0;
}
}
Commit Message: decompileAction: Prevent heap buffer overflow and underflow with using OpCode
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static js_Ast *callexp(js_State *J)
{
js_Ast *a = newexp(J);
loop:
if (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; }
if (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; }
if (jsP_accept(J, '(')) { a = EXP2(CALL, a, arguments(J)); jsP_expect(J, ')'); goto loop; }
return a;
}
Commit Message:
CWE ID: CWE-674
Target: 1
Example 2:
Code: static void ImportAlphaQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelAlpha(image,ScaleCharToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/129
CWE ID: CWE-284
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: sample(png_const_bytep row, png_byte colour_type, png_byte bit_depth,
png_uint_32 x, unsigned int sample_index)
{
png_uint_32 bit_index, result;
/* Find a sample index for the desired sample: */
x *= bit_depth;
bit_index = x;
if ((colour_type & 1) == 0) /* !palette */
{
if (colour_type & 2)
bit_index *= 3;
if (colour_type & 4)
bit_index += x; /* Alpha channel */
/* Multiple channels; select one: */
if (colour_type & (2+4))
bit_index += sample_index * bit_depth;
}
/* Return the sample from the row as an integer. */
row += bit_index >> 3;
result = *row;
if (bit_depth == 8)
return result;
else if (bit_depth > 8)
return (result << 8) + *++row;
/* Less than 8 bits per sample. */
bit_index &= 7;
return (result >> (8-bit_index-bit_depth)) & ((1U<<bit_depth)-1);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
ExceptionInfo *exception)
{
#define ComplexImageTag "Complex/Image"
CacheView
*Ai_view,
*Ar_view,
*Bi_view,
*Br_view,
*Ci_view,
*Cr_view;
const char
*artifact;
const Image
*Ai_image,
*Ar_image,
*Bi_image,
*Br_image;
double
snr;
Image
*Ci_image,
*complex_images,
*Cr_image,
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (images->next == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",images->filename);
return((Image *) NULL);
}
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
image=DestroyImageList(image);
return(image);
}
image->depth=32UL;
complex_images=NewImageList();
AppendImageToList(&complex_images,image);
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
AppendImageToList(&complex_images,image);
/*
Apply complex mathematics to image pixels.
*/
artifact=GetImageArtifact(image,"complex:snr");
snr=0.0;
if (artifact != (const char *) NULL)
snr=StringToDouble(artifact,(char **) NULL);
Ar_image=images;
Ai_image=images->next;
Br_image=images;
Bi_image=images->next;
if ((images->next->next != (Image *) NULL) &&
(images->next->next->next != (Image *) NULL))
{
Br_image=images->next->next;
Bi_image=images->next->next->next;
}
Cr_image=complex_images;
Ci_image=complex_images->next;
Ar_view=AcquireVirtualCacheView(Ar_image,exception);
Ai_view=AcquireVirtualCacheView(Ai_image,exception);
Br_view=AcquireVirtualCacheView(Br_image,exception);
Bi_view=AcquireVirtualCacheView(Bi_image,exception);
Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(Cr_image,complex_images,Cr_image->rows,1L)
#endif
for (y=0; y < (ssize_t) Cr_image->rows; y++)
{
register const Quantum
*magick_restrict Ai,
*magick_restrict Ar,
*magick_restrict Bi,
*magick_restrict Br;
register Quantum
*magick_restrict Ci,
*magick_restrict Cr;
register ssize_t
x;
if (status == MagickFalse)
continue;
Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Cr_image->columns,1,exception);
Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Cr_image->columns,1,exception);
Br=GetCacheViewVirtualPixels(Br_view,0,y,Cr_image->columns,1,exception);
Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Cr_image->columns,1,exception);
Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);
Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);
if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) ||
(Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) ||
(Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) Cr_image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(Cr_image); i++)
{
switch (op)
{
case AddComplexOperator:
{
Cr[i]=Ar[i]+Br[i];
Ci[i]=Ai[i]+Bi[i];
break;
}
case ConjugateComplexOperator:
default:
{
Cr[i]=Ar[i];
Ci[i]=(-Bi[i]);
break;
}
case DivideComplexOperator:
{
double
gamma;
gamma=PerceptibleReciprocal((double) Br[i]*Br[i]+Bi[i]*Bi[i]+snr);
Cr[i]=gamma*((double) Ar[i]*Br[i]+(double) Ai[i]*Bi[i]);
Ci[i]=gamma*((double) Ai[i]*Br[i]-(double) Ar[i]*Bi[i]);
break;
}
case MagnitudePhaseComplexOperator:
{
Cr[i]=sqrt((double) Ar[i]*Ar[i]+(double) Ai[i]*Ai[i]);
Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5;
break;
}
case MultiplyComplexOperator:
{
Cr[i]=QuantumScale*((double) Ar[i]*Br[i]-(double) Ai[i]*Bi[i]);
Ci[i]=QuantumScale*((double) Ai[i]*Br[i]+(double) Ar[i]*Bi[i]);
break;
}
case RealImaginaryComplexOperator:
{
Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5));
Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5));
break;
}
case SubtractComplexOperator:
{
Cr[i]=Ar[i]-Br[i];
Ci[i]=Ai[i]-Bi[i];
break;
}
}
}
Ar+=GetPixelChannels(Ar_image);
Ai+=GetPixelChannels(Ai_image);
Br+=GetPixelChannels(Br_image);
Bi+=GetPixelChannels(Bi_image);
Cr+=GetPixelChannels(Cr_image);
Ci+=GetPixelChannels(Ci_image);
}
if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
status=MagickFalse;
if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
Cr_view=DestroyCacheView(Cr_view);
Ci_view=DestroyCacheView(Ci_view);
Br_view=DestroyCacheView(Br_view);
Bi_view=DestroyCacheView(Bi_view);
Ar_view=DestroyCacheView(Ar_view);
Ai_view=DestroyCacheView(Ai_view);
if (status == MagickFalse)
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1597
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void ndisc_error_report(struct neighbour *neigh, struct sk_buff *skb)
{
/*
* "The sender MUST return an ICMP
* destination unreachable"
*/
dst_link_failure(skb);
kfree_skb(skb);
}
Commit Message: ipv6: Don't reduce hop limit for an interface
A local route may have a lower hop_limit set than global routes do.
RFC 3756, Section 4.2.7, "Parameter Spoofing"
> 1. The attacker includes a Current Hop Limit of one or another small
> number which the attacker knows will cause legitimate packets to
> be dropped before they reach their destination.
> As an example, one possible approach to mitigate this threat is to
> ignore very small hop limits. The nodes could implement a
> configurable minimum hop limit, and ignore attempts to set it below
> said limit.
Signed-off-by: D.S. Ljungmark <[email protected]>
Acked-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-17
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int handle_opendir(struct fuse* fuse, struct fuse_handler* handler,
const struct fuse_in_header* hdr, const struct fuse_open_in* req)
{
struct node* node;
char path[PATH_MAX];
struct fuse_open_out out;
struct dirhandle *h;
pthread_mutex_lock(&fuse->global->lock);
node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
TRACE("[%d] OPENDIR @ %"PRIx64" (%s)\n", handler->token,
hdr->nodeid, node ? node->name : "?");
pthread_mutex_unlock(&fuse->global->lock);
if (!node) {
return -ENOENT;
}
if (!check_caller_access_to_node(fuse, hdr, node, R_OK)) {
return -EACCES;
}
h = malloc(sizeof(*h));
if (!h) {
return -ENOMEM;
}
TRACE("[%d] OPENDIR %s\n", handler->token, path);
h->d = opendir(path);
if (!h->d) {
free(h);
return -errno;
}
out.fh = ptr_to_id(h);
out.open_flags = 0;
out.padding = 0;
fuse_reply(fuse, hdr->unique, &out, sizeof(out));
return NO_STATUS;
}
Commit Message: Fix overflow in path building
An incorrect size was causing an unsigned value
to wrap, causing it to write past the end of
the buffer.
Bug: 28085658
Change-Id: Ie9625c729cca024d514ba2880ff97209d435a165
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static bool check_allocations(ASS_Shaper *shaper, size_t new_size)
{
if (new_size > shaper->n_glyphs) {
if (!ASS_REALLOC_ARRAY(shaper->event_text, new_size) ||
!ASS_REALLOC_ARRAY(shaper->ctypes, new_size) ||
!ASS_REALLOC_ARRAY(shaper->emblevels, new_size) ||
!ASS_REALLOC_ARRAY(shaper->cmap, new_size))
return false;
}
return true;
}
Commit Message: shaper: fix reallocation
Update the variable that tracks the allocated size. This potentially
improves performance and avoid some side effects, which lead to
undefined behavior in some cases.
Fixes fuzzer test case id:000051,sig:11,sync:fuzzer3,src:004221.
CWE ID: CWE-399
Target: 1
Example 2:
Code: vc4_get_hang_state_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_vc4_get_hang_state *get_state = data;
struct drm_vc4_get_hang_state_bo *bo_state;
struct vc4_hang_state *kernel_state;
struct drm_vc4_get_hang_state *state;
struct vc4_dev *vc4 = to_vc4_dev(dev);
unsigned long irqflags;
u32 i;
int ret = 0;
spin_lock_irqsave(&vc4->job_lock, irqflags);
kernel_state = vc4->hang_state;
if (!kernel_state) {
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
return -ENOENT;
}
state = &kernel_state->user_state;
/* If the user's array isn't big enough, just return the
* required array size.
*/
if (get_state->bo_count < state->bo_count) {
get_state->bo_count = state->bo_count;
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
return 0;
}
vc4->hang_state = NULL;
spin_unlock_irqrestore(&vc4->job_lock, irqflags);
/* Save the user's BO pointer, so we don't stomp it with the memcpy. */
state->bo = get_state->bo;
memcpy(get_state, state, sizeof(*state));
bo_state = kcalloc(state->bo_count, sizeof(*bo_state), GFP_KERNEL);
if (!bo_state) {
ret = -ENOMEM;
goto err_free;
}
for (i = 0; i < state->bo_count; i++) {
struct vc4_bo *vc4_bo = to_vc4_bo(kernel_state->bo[i]);
u32 handle;
ret = drm_gem_handle_create(file_priv, kernel_state->bo[i],
&handle);
if (ret) {
state->bo_count = i - 1;
goto err;
}
bo_state[i].handle = handle;
bo_state[i].paddr = vc4_bo->base.paddr;
bo_state[i].size = vc4_bo->base.base.size;
}
if (copy_to_user((void __user *)(uintptr_t)get_state->bo,
bo_state,
state->bo_count * sizeof(*bo_state)))
ret = -EFAULT;
kfree(bo_state);
err_free:
vc4_free_hang_state(dev, kernel_state);
err:
return ret;
}
Commit Message: drm/vc4: Return -EINVAL on the overflow checks failing.
By failing to set the errno, we'd continue on to trying to set up the
RCL, and then oops on trying to dereference the tile_bo that binning
validation should have set up.
Reported-by: Ingo Molnar <[email protected]>
Signed-off-by: Eric Anholt <[email protected]>
Fixes: d5b1a78a772f ("drm/vc4: Add support for drawing 3D frames.")
CWE ID: CWE-388
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool PrintRenderFrameHelper::FinalizePrintReadyDocument() {
DCHECK(!is_print_ready_metafile_sent_);
print_preview_context_.FinalizePrintReadyDocument();
PdfMetafileSkia* metafile = print_preview_context_.metafile();
PrintHostMsg_DidPreviewDocument_Params preview_params;
if (!CopyMetafileDataToSharedMem(*metafile,
&preview_params.metafile_data_handle)) {
LOG(ERROR) << "CopyMetafileDataToSharedMem failed";
print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED);
return false;
}
preview_params.data_size = metafile->GetDataSize();
preview_params.document_cookie = print_pages_params_->params.document_cookie;
preview_params.expected_pages_count =
print_preview_context_.total_page_count();
preview_params.modifiable = print_preview_context_.IsModifiable();
preview_params.preview_request_id =
print_pages_params_->params.preview_request_id;
is_print_ready_metafile_sent_ = true;
Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(), preview_params));
return true;
}
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: unsigned paravirt_patch_call(void *insnbuf,
const void *target, u16 tgt_clobbers,
unsigned long addr, u16 site_clobbers,
unsigned len)
{
struct branch *b = insnbuf;
unsigned long delta = (unsigned long)target - (addr+5);
if (tgt_clobbers & ~site_clobbers)
return len; /* target would clobber too much for this site */
if (len < 5)
return len; /* call too long for patch site */
b->opcode = 0xe8; /* call */
b->delta = delta;
BUILD_BUG_ON(sizeof(*b) != 5);
return 5;
}
Commit Message: x86/paravirt: Fix spectre-v2 mitigations for paravirt guests
Nadav reported that on guests we're failing to rewrite the indirect
calls to CALLEE_SAVE paravirt functions. In particular the
pv_queued_spin_unlock() call is left unpatched and that is all over the
place. This obviously wrecks Spectre-v2 mitigation (for paravirt
guests) which relies on not actually having indirect calls around.
The reason is an incorrect clobber test in paravirt_patch_call(); this
function rewrites an indirect call with a direct call to the _SAME_
function, there is no possible way the clobbers can be different
because of this.
Therefore remove this clobber check. Also put WARNs on the other patch
failure case (not enough room for the instruction) which I've not seen
trigger in my (limited) testing.
Three live kernel image disassemblies for lock_sock_nested (as a small
function that illustrates the problem nicely). PRE is the current
situation for guests, POST is with this patch applied and NATIVE is with
or without the patch for !guests.
PRE:
(gdb) disassemble lock_sock_nested
Dump of assembler code for function lock_sock_nested:
0xffffffff817be970 <+0>: push %rbp
0xffffffff817be971 <+1>: mov %rdi,%rbp
0xffffffff817be974 <+4>: push %rbx
0xffffffff817be975 <+5>: lea 0x88(%rbp),%rbx
0xffffffff817be97c <+12>: callq 0xffffffff819f7160 <_cond_resched>
0xffffffff817be981 <+17>: mov %rbx,%rdi
0xffffffff817be984 <+20>: callq 0xffffffff819fbb00 <_raw_spin_lock_bh>
0xffffffff817be989 <+25>: mov 0x8c(%rbp),%eax
0xffffffff817be98f <+31>: test %eax,%eax
0xffffffff817be991 <+33>: jne 0xffffffff817be9ba <lock_sock_nested+74>
0xffffffff817be993 <+35>: movl $0x1,0x8c(%rbp)
0xffffffff817be99d <+45>: mov %rbx,%rdi
0xffffffff817be9a0 <+48>: callq *0xffffffff822299e8
0xffffffff817be9a7 <+55>: pop %rbx
0xffffffff817be9a8 <+56>: pop %rbp
0xffffffff817be9a9 <+57>: mov $0x200,%esi
0xffffffff817be9ae <+62>: mov $0xffffffff817be993,%rdi
0xffffffff817be9b5 <+69>: jmpq 0xffffffff81063ae0 <__local_bh_enable_ip>
0xffffffff817be9ba <+74>: mov %rbp,%rdi
0xffffffff817be9bd <+77>: callq 0xffffffff817be8c0 <__lock_sock>
0xffffffff817be9c2 <+82>: jmp 0xffffffff817be993 <lock_sock_nested+35>
End of assembler dump.
POST:
(gdb) disassemble lock_sock_nested
Dump of assembler code for function lock_sock_nested:
0xffffffff817be970 <+0>: push %rbp
0xffffffff817be971 <+1>: mov %rdi,%rbp
0xffffffff817be974 <+4>: push %rbx
0xffffffff817be975 <+5>: lea 0x88(%rbp),%rbx
0xffffffff817be97c <+12>: callq 0xffffffff819f7160 <_cond_resched>
0xffffffff817be981 <+17>: mov %rbx,%rdi
0xffffffff817be984 <+20>: callq 0xffffffff819fbb00 <_raw_spin_lock_bh>
0xffffffff817be989 <+25>: mov 0x8c(%rbp),%eax
0xffffffff817be98f <+31>: test %eax,%eax
0xffffffff817be991 <+33>: jne 0xffffffff817be9ba <lock_sock_nested+74>
0xffffffff817be993 <+35>: movl $0x1,0x8c(%rbp)
0xffffffff817be99d <+45>: mov %rbx,%rdi
0xffffffff817be9a0 <+48>: callq 0xffffffff810a0c20 <__raw_callee_save___pv_queued_spin_unlock>
0xffffffff817be9a5 <+53>: xchg %ax,%ax
0xffffffff817be9a7 <+55>: pop %rbx
0xffffffff817be9a8 <+56>: pop %rbp
0xffffffff817be9a9 <+57>: mov $0x200,%esi
0xffffffff817be9ae <+62>: mov $0xffffffff817be993,%rdi
0xffffffff817be9b5 <+69>: jmpq 0xffffffff81063aa0 <__local_bh_enable_ip>
0xffffffff817be9ba <+74>: mov %rbp,%rdi
0xffffffff817be9bd <+77>: callq 0xffffffff817be8c0 <__lock_sock>
0xffffffff817be9c2 <+82>: jmp 0xffffffff817be993 <lock_sock_nested+35>
End of assembler dump.
NATIVE:
(gdb) disassemble lock_sock_nested
Dump of assembler code for function lock_sock_nested:
0xffffffff817be970 <+0>: push %rbp
0xffffffff817be971 <+1>: mov %rdi,%rbp
0xffffffff817be974 <+4>: push %rbx
0xffffffff817be975 <+5>: lea 0x88(%rbp),%rbx
0xffffffff817be97c <+12>: callq 0xffffffff819f7160 <_cond_resched>
0xffffffff817be981 <+17>: mov %rbx,%rdi
0xffffffff817be984 <+20>: callq 0xffffffff819fbb00 <_raw_spin_lock_bh>
0xffffffff817be989 <+25>: mov 0x8c(%rbp),%eax
0xffffffff817be98f <+31>: test %eax,%eax
0xffffffff817be991 <+33>: jne 0xffffffff817be9ba <lock_sock_nested+74>
0xffffffff817be993 <+35>: movl $0x1,0x8c(%rbp)
0xffffffff817be99d <+45>: mov %rbx,%rdi
0xffffffff817be9a0 <+48>: movb $0x0,(%rdi)
0xffffffff817be9a3 <+51>: nopl 0x0(%rax)
0xffffffff817be9a7 <+55>: pop %rbx
0xffffffff817be9a8 <+56>: pop %rbp
0xffffffff817be9a9 <+57>: mov $0x200,%esi
0xffffffff817be9ae <+62>: mov $0xffffffff817be993,%rdi
0xffffffff817be9b5 <+69>: jmpq 0xffffffff81063ae0 <__local_bh_enable_ip>
0xffffffff817be9ba <+74>: mov %rbp,%rdi
0xffffffff817be9bd <+77>: callq 0xffffffff817be8c0 <__lock_sock>
0xffffffff817be9c2 <+82>: jmp 0xffffffff817be993 <lock_sock_nested+35>
End of assembler dump.
Fixes: 63f70270ccd9 ("[PATCH] i386: PARAVIRT: add common patching machinery")
Fixes: 3010a0663fd9 ("x86/paravirt, objtool: Annotate indirect calls")
Reported-by: Nadav Amit <[email protected]>
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Reviewed-by: Juergen Gross <[email protected]>
Cc: Konrad Rzeszutek Wilk <[email protected]>
Cc: Boris Ostrovsky <[email protected]>
Cc: David Woodhouse <[email protected]>
Cc: [email protected]
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int ciedefgrange(i_ctx_t * i_ctx_p, ref *space, float *ptr)
{
int code;
ref CIEdict, *tempref;
code = array_get(imemory, space, 1, &CIEdict);
if (code < 0)
return code;
/* If we have a RangeDEFG, get the values from that */
code = dict_find_string(&CIEdict, "RangeDEFG", &tempref);
if (code > 0 && !r_has_type(tempref, t_null)) {
code = get_cie_param_array(imemory, tempref, 8, ptr);
if (code < 0)
return code;
} else {
/* Default values for a CIEBasedDEFG */
memcpy(ptr, default_0_1, 8*sizeof(float));
}
return 0;
}
Commit Message:
CWE ID: CWE-704
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void PrintPreviewDataSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
if (!EndsWith(path, "/print.pdf", true)) {
ChromeWebUIDataSource::StartDataRequest(path, is_incognito, request_id);
return;
}
scoped_refptr<base::RefCountedBytes> data;
std::vector<std::string> url_substr;
base::SplitString(path, '/', &url_substr);
int page_index = 0;
if (url_substr.size() == 3 && base::StringToInt(url_substr[1], &page_index)) {
PrintPreviewDataService::GetInstance()->GetDataEntry(
url_substr[0], page_index, &data);
}
if (data.get()) {
SendResponse(request_id, data);
return;
}
scoped_refptr<base::RefCountedBytes> empty_bytes(new base::RefCountedBytes);
SendResponse(request_id, empty_bytes);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int store, int raw, zval **subarray)
{
u_short type, class, dlen;
u_long ttl;
long n, i;
u_short s;
u_char *tp, *p;
char name[MAXHOSTNAMELEN];
int have_v6_break = 0, in_v6_break = 0;
*subarray = NULL;
n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, sizeof(name) - 2);
if (n < 0) {
return NULL;
}
cp += n;
GETSHORT(type, cp);
GETSHORT(class, cp);
GETLONG(ttl, cp);
GETSHORT(dlen, cp);
if (type_to_fetch != T_ANY && type != type_to_fetch) {
cp += dlen;
return cp;
}
if (!store) {
cp += dlen;
return cp;
}
ALLOC_INIT_ZVAL(*subarray);
array_init(*subarray);
add_assoc_string(*subarray, "host", name, 1);
add_assoc_string(*subarray, "class", "IN", 1);
add_assoc_long(*subarray, "ttl", ttl);
if (raw) {
add_assoc_long(*subarray, "type", type);
add_assoc_stringl(*subarray, "data", (char*) cp, (uint) dlen, 1);
cp += dlen;
return cp;
}
switch (type) {
case DNS_T_A:
add_assoc_string(*subarray, "type", "A", 1);
snprintf(name, sizeof(name), "%d.%d.%d.%d", cp[0], cp[1], cp[2], cp[3]);
add_assoc_string(*subarray, "ip", name, 1);
cp += dlen;
break;
case DNS_T_MX:
add_assoc_string(*subarray, "type", "MX", 1);
GETSHORT(n, cp);
add_assoc_long(*subarray, "pri", n);
/* no break; */
case DNS_T_CNAME:
if (type == DNS_T_CNAME) {
add_assoc_string(*subarray, "type", "CNAME", 1);
}
/* no break; */
case DNS_T_NS:
if (type == DNS_T_NS) {
add_assoc_string(*subarray, "type", "NS", 1);
}
/* no break; */
case DNS_T_PTR:
if (type == DNS_T_PTR) {
add_assoc_string(*subarray, "type", "PTR", 1);
}
n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(*subarray, "target", name, 1);
break;
case DNS_T_HINFO:
/* See RFC 1010 for values */
add_assoc_string(*subarray, "type", "HINFO", 1);
n = *cp & 0xFF;
cp++;
add_assoc_stringl(*subarray, "cpu", (char*)cp, n, 1);
cp += n;
n = *cp & 0xFF;
cp++;
add_assoc_stringl(*subarray, "os", (char*)cp, n, 1);
cp += n;
break;
case DNS_T_TXT:
{
int ll = 0;
zval *entries = NULL;
add_assoc_string(*subarray, "type", "TXT", 1);
tp = emalloc(dlen + 1);
MAKE_STD_ZVAL(entries);
array_init(entries);
while (ll < dlen) {
n = cp[ll];
if ((ll + n) >= dlen) {
n = dlen - (ll + 1);
}
memcpy(tp + ll , cp + ll + 1, n);
add_next_index_stringl(entries, cp + ll + 1, n, 1);
ll = ll + n + 1;
}
tp[dlen] = '\0';
cp += dlen;
add_assoc_stringl(*subarray, "txt", tp, (dlen>0)?dlen - 1:0, 0);
add_assoc_zval(*subarray, "entries", entries);
}
break;
case DNS_T_SOA:
add_assoc_string(*subarray, "type", "SOA", 1);
n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) -2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(*subarray, "mname", name, 1);
n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) -2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(*subarray, "rname", name, 1);
GETLONG(n, cp);
add_assoc_long(*subarray, "serial", n);
GETLONG(n, cp);
add_assoc_long(*subarray, "refresh", n);
GETLONG(n, cp);
add_assoc_long(*subarray, "retry", n);
GETLONG(n, cp);
add_assoc_long(*subarray, "expire", n);
GETLONG(n, cp);
add_assoc_long(*subarray, "minimum-ttl", n);
break;
case DNS_T_AAAA:
tp = (u_char*)name;
for(i=0; i < 8; i++) {
GETSHORT(s, cp);
if (s != 0) {
if (tp > (u_char *)name) {
in_v6_break = 0;
tp[0] = ':';
tp++;
}
tp += sprintf((char*)tp,"%x",s);
} else {
if (!have_v6_break) {
have_v6_break = 1;
in_v6_break = 1;
tp[0] = ':';
tp++;
} else if (!in_v6_break) {
tp[0] = ':';
tp++;
tp[0] = '0';
tp++;
}
}
}
if (have_v6_break && in_v6_break) {
tp[0] = ':';
tp++;
}
tp[0] = '\0';
add_assoc_string(*subarray, "type", "AAAA", 1);
add_assoc_string(*subarray, "ipv6", name, 1);
break;
case DNS_T_A6:
p = cp;
add_assoc_string(*subarray, "type", "A6", 1);
n = ((int)cp[0]) & 0xFF;
cp++;
add_assoc_long(*subarray, "masklen", n);
tp = (u_char*)name;
if (n > 15) {
have_v6_break = 1;
in_v6_break = 1;
tp[0] = ':';
tp++;
}
if (n % 16 > 8) {
/* Partial short */
if (cp[0] != 0) {
if (tp > (u_char *)name) {
in_v6_break = 0;
tp[0] = ':';
tp++;
}
sprintf((char*)tp, "%x", cp[0] & 0xFF);
} else {
if (!have_v6_break) {
have_v6_break = 1;
in_v6_break = 1;
tp[0] = ':';
tp++;
} else if (!in_v6_break) {
tp[0] = ':';
tp++;
tp[0] = '0';
tp++;
}
}
cp++;
}
for (i = (n + 8) / 16; i < 8; i++) {
GETSHORT(s, cp);
if (s != 0) {
if (tp > (u_char *)name) {
in_v6_break = 0;
tp[0] = ':';
tp++;
}
tp += sprintf((char*)tp,"%x",s);
} else {
if (!have_v6_break) {
have_v6_break = 1;
in_v6_break = 1;
tp[0] = ':';
tp++;
} else if (!in_v6_break) {
tp[0] = ':';
tp++;
tp[0] = '0';
tp++;
}
}
}
if (have_v6_break && in_v6_break) {
tp[0] = ':';
tp++;
}
tp[0] = '\0';
add_assoc_string(*subarray, "ipv6", name, 1);
if (cp < p + dlen) {
n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(*subarray, "chain", name, 1);
}
break;
case DNS_T_SRV:
add_assoc_string(*subarray, "type", "SRV", 1);
GETSHORT(n, cp);
add_assoc_long(*subarray, "pri", n);
GETSHORT(n, cp);
add_assoc_long(*subarray, "weight", n);
GETSHORT(n, cp);
add_assoc_long(*subarray, "port", n);
n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(*subarray, "target", name, 1);
break;
case DNS_T_NAPTR:
add_assoc_string(*subarray, "type", "NAPTR", 1);
GETSHORT(n, cp);
add_assoc_long(*subarray, "order", n);
GETSHORT(n, cp);
add_assoc_long(*subarray, "pref", n);
n = (cp[0] & 0xFF);
add_assoc_stringl(*subarray, "flags", (char*)++cp, n, 1);
cp += n;
n = (cp[0] & 0xFF);
add_assoc_stringl(*subarray, "services", (char*)++cp, n, 1);
cp += n;
n = (cp[0] & 0xFF);
add_assoc_stringl(*subarray, "regex", (char*)++cp, n, 1);
cp += n;
n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(*subarray, "replacement", name, 1);
break;
default:
zval_ptr_dtor(subarray);
*subarray = NULL;
cp += dlen;
break;
}
return cp;
}
Commit Message: Fixed Sec Bug #67717 segfault in dns_get_record CVE-2014-3597
Incomplete fix for CVE-2014-4049
Check possible buffer overflow
- pass real buffer end to dn_expand calls
- check buffer len before each read
CWE ID: CWE-119
Target: 1
Example 2:
Code: DebuggerFunction::DebuggerFunction()
: client_host_(NULL) {
}
Commit Message: [DevTools] Do not allow Page.setDownloadBehavior for extensions
Bug: 866426
Change-Id: I71b672978e1a8ec779ede49da16b21198567d3a4
Reviewed-on: https://chromium-review.googlesource.com/c/1270007
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598004}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void opj_tcd_destroy(opj_tcd_t *tcd) {
if (tcd) {
opj_tcd_free_tile(tcd);
if (tcd->tcd_image) {
opj_free(tcd->tcd_image);
tcd->tcd_image = 00;
}
opj_free(tcd);
}
}
Commit Message: Add sanity check for tile coordinates (#823)
Coordinates are casted from OPJ_UINT32 to OPJ_INT32
Add sanity check for negative values and upper bound becoming lower
than lower bound.
See also
https://pdfium.googlesource.com/pdfium/+/b6befb2ed2485a3805cddea86dc7574510178ea9
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: cmsSEQ* CMSEXPORT cmsAllocProfileSequenceDescription(cmsContext ContextID, cmsUInt32Number n)
{
cmsSEQ* Seq;
cmsUInt32Number i;
if (n == 0) return NULL;
if (n > 255) return NULL;
Seq = (cmsSEQ*) _cmsMallocZero(ContextID, sizeof(cmsSEQ));
if (Seq == NULL) return NULL;
Seq -> ContextID = ContextID;
Seq -> seq = (cmsPSEQDESC*) _cmsCalloc(ContextID, n, sizeof(cmsPSEQDESC));
Seq -> n = n;
for (i=0; i < n; i++) {
Seq -> seq[i].Manufacturer = NULL;
Seq -> seq[i].Model = NULL;
Seq -> seq[i].Description = NULL;
}
return Seq;
}
Commit Message: Non happy-path fixes
CWE ID:
Target: 1
Example 2:
Code: void FrameSelection::Clear() {
granularity_ = TextGranularity::kCharacter;
if (granularity_strategy_)
granularity_strategy_->Clear();
SetSelectionAndEndTyping(SelectionInDOMTree());
is_handle_visible_ = false;
is_directional_ = ShouldAlwaysUseDirectionalSelection(frame_);
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline int aead_len(struct xfrm_algo_aead *alg)
{
return sizeof(*alg) + ((alg->alg_key_len + 7) / 8);
}
Commit Message: xfrm_user: return error pointer instead of NULL
When dump_one_state() returns an error, e.g. because of a too small
buffer to dump the whole xfrm state, xfrm_state_netlink() returns NULL
instead of an error pointer. But its callers expect an error pointer
and therefore continue to operate on a NULL skbuff.
This could lead to a privilege escalation (execution of user code in
kernel context) if the attacker has CAP_NET_ADMIN and is able to map
address 0.
Signed-off-by: Mathias Krause <[email protected]>
Acked-by: Steffen Klassert <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static const SSL_METHOD *ssl23_get_server_method(int ver)
{
#ifndef OPENSSL_NO_SSL2
if (ver == SSL2_VERSION)
return(SSLv2_server_method());
#endif
if (ver == SSL3_VERSION)
return(SSLv3_server_method());
else if (ver == TLS1_VERSION)
return(TLSv1_server_method());
else if (ver == TLS1_1_VERSION)
return(TLSv1_1_server_method());
else
return(NULL);
}
Commit Message:
CWE ID: CWE-310
Target: 1
Example 2:
Code: bool ieee80211_tx_prepare_skb(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, struct sk_buff *skb,
int band, struct ieee80211_sta **sta)
{
struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif);
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct ieee80211_tx_data tx;
if (ieee80211_tx_prepare(sdata, &tx, skb) == TX_DROP)
return false;
info->band = band;
info->control.vif = vif;
info->hw_queue = vif->hw_queue[skb_get_queue_mapping(skb)];
if (invoke_tx_handlers(&tx))
return false;
if (sta) {
if (tx.sta)
*sta = &tx.sta->sta;
else
*sta = NULL;
}
return true;
}
Commit Message: mac80211: fix fragmentation code, particularly for encryption
The "new" fragmentation code (since my rewrite almost 5 years ago)
erroneously sets skb->len rather than using skb_trim() to adjust
the length of the first fragment after copying out all the others.
This leaves the skb tail pointer pointing to after where the data
originally ended, and thus causes the encryption MIC to be written
at that point, rather than where it belongs: immediately after the
data.
The impact of this is that if software encryption is done, then
a) encryption doesn't work for the first fragment, the connection
becomes unusable as the first fragment will never be properly
verified at the receiver, the MIC is practically guaranteed to
be wrong
b) we leak up to 8 bytes of plaintext (!) of the packet out into
the air
This is only mitigated by the fact that many devices are capable
of doing encryption in hardware, in which case this can't happen
as the tail pointer is irrelevant in that case. Additionally,
fragmentation is not used very frequently and would normally have
to be configured manually.
Fix this by using skb_trim() properly.
Cc: [email protected]
Fixes: 2de8e0d999b8 ("mac80211: rewrite fragmentation")
Reported-by: Jouni Malinen <[email protected]>
Signed-off-by: Johannes Berg <[email protected]>
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int __kprobes do_page_fault(unsigned long addr, unsigned int esr,
struct pt_regs *regs)
{
struct task_struct *tsk;
struct mm_struct *mm;
int fault, sig, code;
unsigned long vm_flags = VM_READ | VM_WRITE;
unsigned int mm_flags = FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
tsk = current;
mm = tsk->mm;
/* Enable interrupts if they were enabled in the parent context. */
if (interrupts_enabled(regs))
local_irq_enable();
/*
* If we're in an interrupt or have no user context, we must not take
* the fault.
*/
if (in_atomic() || !mm)
goto no_context;
if (user_mode(regs))
mm_flags |= FAULT_FLAG_USER;
if (esr & ESR_LNX_EXEC) {
vm_flags = VM_EXEC;
} else if ((esr & ESR_EL1_WRITE) && !(esr & ESR_EL1_CM)) {
vm_flags = VM_WRITE;
mm_flags |= FAULT_FLAG_WRITE;
}
/*
* As per x86, we may deadlock here. However, since the kernel only
* validly references user space from well defined areas of the code,
* we can bug out early if this is from code which shouldn't.
*/
if (!down_read_trylock(&mm->mmap_sem)) {
if (!user_mode(regs) && !search_exception_tables(regs->pc))
goto no_context;
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();
#ifdef CONFIG_DEBUG_VM
if (!user_mode(regs) && !search_exception_tables(regs->pc))
goto no_context;
#endif
}
fault = __do_page_fault(mm, addr, mm_flags, vm_flags, tsk);
/*
* If we need to retry but a fatal signal is pending, handle the
* signal first. We do not need to release the mmap_sem because it
* would already be released in __lock_page_or_retry in mm/filemap.c.
*/
if ((fault & VM_FAULT_RETRY) && fatal_signal_pending(current))
return 0;
/*
* 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.
*/
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, addr);
if (mm_flags & FAULT_FLAG_ALLOW_RETRY) {
if (fault & VM_FAULT_MAJOR) {
tsk->maj_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs,
addr);
} else {
tsk->min_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs,
addr);
}
if (fault & VM_FAULT_RETRY) {
/*
* Clear FAULT_FLAG_ALLOW_RETRY to avoid any risk of
* starvation.
*/
mm_flags &= ~FAULT_FLAG_ALLOW_RETRY;
goto retry;
}
}
up_read(&mm->mmap_sem);
/*
* Handle the "normal" case first - VM_FAULT_MAJOR / VM_FAULT_MINOR
*/
if (likely(!(fault & (VM_FAULT_ERROR | VM_FAULT_BADMAP |
VM_FAULT_BADACCESS))))
return 0;
/*
* If we are in kernel mode at this point, we have no context to
* handle this fault with.
*/
if (!user_mode(regs))
goto no_context;
if (fault & VM_FAULT_OOM) {
/*
* We ran out of memory, call the OOM killer, and return to
* userspace (which will retry the fault, or kill us if we got
* oom-killed).
*/
pagefault_out_of_memory();
return 0;
}
if (fault & VM_FAULT_SIGBUS) {
/*
* We had some memory, but were unable to successfully fix up
* this page fault.
*/
sig = SIGBUS;
code = BUS_ADRERR;
} else {
/*
* Something tried to access memory that isn't in our memory
* map.
*/
sig = SIGSEGV;
code = fault == VM_FAULT_BADACCESS ?
SEGV_ACCERR : SEGV_MAPERR;
}
__do_user_fault(tsk, addr, esr, sig, code, regs);
return 0;
no_context:
__do_kernel_fault(mm, addr, esr, regs);
return 0;
}
Commit Message: Revert "arm64: Introduce execute-only page access permissions"
This reverts commit bc07c2c6e9ed125d362af0214b6313dca180cb08.
While the aim is increased security for --x memory maps, it does not
protect against kernel level reads. Until SECCOMP is implemented for
arm64, revert this patch to avoid giving a false idea of execute-only
mappings.
Signed-off-by: Catalin Marinas <[email protected]>
CWE ID: CWE-19
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool Plugin::LoadNaClModuleContinuationIntern(ErrorInfo* error_info) {
if (using_ipc_proxy_)
return true;
if (!main_subprocess_.StartSrpcServices()) {
error_info->SetReport(ERROR_SRPC_CONNECTION_FAIL,
"SRPC connection failure for " +
main_subprocess_.description());
return false;
}
if (!main_subprocess_.StartJSObjectProxy(this, error_info)) {
return false;
}
PLUGIN_PRINTF(("Plugin::LoadNaClModule (%s)\n",
main_subprocess_.detailed_description().c_str()));
return true;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: Ins_SROUND( INS_ARG )
{
DO_SROUND
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void JPEGSetImageSamplingFactor(struct jpeg_decompress_struct *jpeg_info, Image *image,ExceptionInfo *exception)
{
char
sampling_factor[MagickPathExtent];
switch (jpeg_info->out_color_space)
{
case JCS_CMYK:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Colorspace: CMYK");
(void) FormatLocaleString(sampling_factor,MagickPathExtent,
"%dx%d,%dx%d,%dx%d,%dx%d",jpeg_info->comp_info[0].h_samp_factor,
jpeg_info->comp_info[0].v_samp_factor,
jpeg_info->comp_info[1].h_samp_factor,
jpeg_info->comp_info[1].v_samp_factor,
jpeg_info->comp_info[2].h_samp_factor,
jpeg_info->comp_info[2].v_samp_factor,
jpeg_info->comp_info[3].h_samp_factor,
jpeg_info->comp_info[3].v_samp_factor);
break;
}
case JCS_GRAYSCALE:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: GRAYSCALE");
(void) FormatLocaleString(sampling_factor,MagickPathExtent,"%dx%d",
jpeg_info->comp_info[0].h_samp_factor,
jpeg_info->comp_info[0].v_samp_factor);
break;
}
case JCS_RGB:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Colorspace: RGB");
(void) FormatLocaleString(sampling_factor,MagickPathExtent,
"%dx%d,%dx%d,%dx%d",jpeg_info->comp_info[0].h_samp_factor,
jpeg_info->comp_info[0].v_samp_factor,
jpeg_info->comp_info[1].h_samp_factor,
jpeg_info->comp_info[1].v_samp_factor,
jpeg_info->comp_info[2].h_samp_factor,
jpeg_info->comp_info[2].v_samp_factor);
break;
}
default:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Colorspace: %d",
jpeg_info->out_color_space);
(void) FormatLocaleString(sampling_factor,MagickPathExtent,
"%dx%d,%dx%d,%dx%d,%dx%d",jpeg_info->comp_info[0].h_samp_factor,
jpeg_info->comp_info[0].v_samp_factor,
jpeg_info->comp_info[1].h_samp_factor,
jpeg_info->comp_info[1].v_samp_factor,
jpeg_info->comp_info[2].h_samp_factor,
jpeg_info->comp_info[2].v_samp_factor,
jpeg_info->comp_info[3].h_samp_factor,
jpeg_info->comp_info[3].v_samp_factor);
break;
}
}
(void) SetImageProperty(image,"jpeg:sampling-factor",sampling_factor,
exception);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Sampling Factors: %s",
sampling_factor);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1641
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GDataFileSystem::OnSearch(const SearchCallback& callback,
GetDocumentsParams* params,
GDataFileError error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (error != GDATA_FILE_OK) {
if (!callback.is_null())
callback.Run(error, GURL(), scoped_ptr<std::vector<SearchResultInfo> >());
return;
}
std::vector<SearchResultInfo>* results(new std::vector<SearchResultInfo>());
DCHECK_EQ(1u, params->feed_list->size());
DocumentFeed* feed = params->feed_list->at(0);
GURL next_feed;
feed->GetNextFeedURL(&next_feed);
if (feed->entries().empty()) {
scoped_ptr<std::vector<SearchResultInfo> > result_vec(results);
if (!callback.is_null())
callback.Run(error, next_feed, result_vec.Pass());
return;
}
for (size_t i = 0; i < feed->entries().size(); ++i) {
DocumentEntry* doc = const_cast<DocumentEntry*>(feed->entries()[i]);
scoped_ptr<GDataEntry> entry(
GDataEntry::FromDocumentEntry(NULL, doc, directory_service_.get()));
if (!entry.get())
continue;
DCHECK_EQ(doc->resource_id(), entry->resource_id());
DCHECK(!entry->is_deleted());
std::string entry_resource_id = entry->resource_id();
if (entry->AsGDataFile()) {
scoped_ptr<GDataFile> entry_as_file(entry.release()->AsGDataFile());
directory_service_->RefreshFile(entry_as_file.Pass());
DCHECK(!entry.get());
}
directory_service_->GetEntryByResourceIdAsync(entry_resource_id,
base::Bind(&AddEntryToSearchResults,
results,
callback,
base::Bind(&GDataFileSystem::CheckForUpdates, ui_weak_ptr_),
error,
i+1 == feed->entries().size(),
next_feed));
}
}
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
Target: 1
Example 2:
Code: vhost_net_ubuf_alloc(struct vhost_virtqueue *vq, bool zcopy)
{
struct vhost_net_ubuf_ref *ubufs;
/* No zero copy backend? Nothing to count. */
if (!zcopy)
return NULL;
ubufs = kmalloc(sizeof(*ubufs), GFP_KERNEL);
if (!ubufs)
return ERR_PTR(-ENOMEM);
kref_init(&ubufs->kref);
init_waitqueue_head(&ubufs->wait);
ubufs->vq = vq;
return ubufs;
}
Commit Message: vhost-net: fix use-after-free in vhost_net_flush
vhost_net_ubuf_put_and_wait has a confusing name:
it will actually also free it's argument.
Thus since commit 1280c27f8e29acf4af2da914e80ec27c3dbd5c01
"vhost-net: flush outstanding DMAs on memory change"
vhost_net_flush tries to use the argument after passing it
to vhost_net_ubuf_put_and_wait, this results
in use after free.
To fix, don't free the argument in vhost_net_ubuf_put_and_wait,
add an new API for callers that want to free ubufs.
Acked-by: Asias He <[email protected]>
Acked-by: Jason Wang <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: status_t OMXNodeInstance::updateGraphicBufferInMeta(
OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer,
OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
return updateGraphicBufferInMeta_l(
portIndex, graphicBuffer, buffer, header,
portIndex == kPortIndexOutput /* updateCodecBuffer */);
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long long Chapters::Atom::GetStartTimecode() const
{
return m_start_timecode;
}
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
Target: 1
Example 2:
Code: cluster_init (void)
{
cluster_hash = hash_create (cluster_hash_key_make, cluster_hash_cmp);
}
Commit Message:
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WallpaperManagerBase::LoadWallpaper(
const AccountId& account_id,
const WallpaperInfo& info,
bool update_wallpaper,
MovableOnDestroyCallbackHolder on_finish) {
base::FilePath wallpaper_dir;
base::FilePath wallpaper_path;
if (info.type == ONLINE || info.type == DEFAULT) {
if (info.location.empty()) {
if (base::SysInfo::IsRunningOnChromeOS()) {
NOTREACHED() << "User wallpaper info appears to be broken: "
<< account_id.Serialize();
} else {
LOG(WARNING) << "User wallpaper info is empty: "
<< account_id.Serialize();
return;
}
}
}
if (info.type == ONLINE) {
std::string file_name = GURL(info.location).ExtractFileName();
WallpaperResolution resolution = GetAppropriateResolution();
if (info.layout != WALLPAPER_LAYOUT_STRETCH &&
resolution == WALLPAPER_RESOLUTION_SMALL) {
file_name = base::FilePath(file_name)
.InsertBeforeExtension(kSmallWallpaperSuffix)
.value();
}
DCHECK(dir_chromeos_wallpapers_path_id != -1);
CHECK(PathService::Get(dir_chromeos_wallpapers_path_id,
&wallpaper_dir));
wallpaper_path = wallpaper_dir.Append(file_name);
CustomWallpaperMap::iterator it = wallpaper_cache_.find(account_id);
if (it != wallpaper_cache_.end() &&
it->second.first == wallpaper_path &&
!it->second.second.isNull())
return;
loaded_wallpapers_for_test_++;
StartLoad(account_id, info, update_wallpaper, wallpaper_path,
std::move(on_finish));
} else if (info.type == DEFAULT) {
base::FilePath user_data_dir;
DCHECK(dir_user_data_path_id != -1);
PathService::Get(dir_user_data_path_id, &user_data_dir);
wallpaper_path = user_data_dir.Append(info.location);
StartLoad(account_id, info, update_wallpaper, wallpaper_path,
std::move(on_finish));
} else {
LOG(ERROR) << "Wallpaper reverts to default unexpected.";
DoSetDefaultWallpaper(account_id, std::move(on_finish));
}
}
Commit Message: [reland] Do not set default wallpaper unless it should do so.
[email protected], [email protected]
Bug: 751382
Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda
Reviewed-on: https://chromium-review.googlesource.com/619754
Commit-Queue: Xiaoqian Dai <[email protected]>
Reviewed-by: Alexander Alekseev <[email protected]>
Reviewed-by: Biao She <[email protected]>
Cr-Original-Commit-Position: refs/heads/master@{#498325}
Reviewed-on: https://chromium-review.googlesource.com/646430
Cr-Commit-Position: refs/heads/master@{#498982}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: const Chapters::Edition* Chapters::GetEdition(int idx) const
{
if (idx < 0)
return NULL;
if (idx >= m_editions_count)
return NULL;
return m_editions + idx;
}
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
Target: 1
Example 2:
Code: kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
{
return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
}
Commit Message: KVM: use after free in kvm_ioctl_create_device()
We should move the ops->destroy(dev) after the list_del(&dev->vm_node)
so that we don't use "dev" after freeing it.
Fixes: a28ebea2adc4 ("KVM: Protect device ops->create and list_add with kvm->lock")
Signed-off-by: Dan Carpenter <[email protected]>
Reviewed-by: David Hildenbrand <[email protected]>
Signed-off-by: Radim Krčmář <[email protected]>
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: double AutofillDownloadManager::GetPositiveUploadRate() const {
return positive_upload_rate_;
}
Commit Message: Add support for the "uploadrequired" attribute for Autofill query responses
BUG=84693
TEST=unit_tests --gtest_filter=AutofillDownloadTest.QueryAndUploadTest
Review URL: http://codereview.chromium.org/6969090
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87729 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void JNI_WebApkUpdateManager_StoreWebApkUpdateRequestToFile(
JNIEnv* env,
const JavaParamRef<jstring>& java_update_request_path,
const JavaParamRef<jstring>& java_start_url,
const JavaParamRef<jstring>& java_scope,
const JavaParamRef<jstring>& java_name,
const JavaParamRef<jstring>& java_short_name,
const JavaParamRef<jstring>& java_primary_icon_url,
const JavaParamRef<jobject>& java_primary_icon_bitmap,
const JavaParamRef<jstring>& java_badge_icon_url,
const JavaParamRef<jobject>& java_badge_icon_bitmap,
const JavaParamRef<jobjectArray>& java_icon_urls,
const JavaParamRef<jobjectArray>& java_icon_hashes,
jint java_display_mode,
jint java_orientation,
jlong java_theme_color,
jlong java_background_color,
const JavaParamRef<jstring>& java_web_manifest_url,
const JavaParamRef<jstring>& java_webapk_package,
jint java_webapk_version,
jboolean java_is_manifest_stale,
jint java_update_reason,
const JavaParamRef<jobject>& java_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
std::string update_request_path =
ConvertJavaStringToUTF8(env, java_update_request_path);
ShortcutInfo info(GURL(ConvertJavaStringToUTF8(env, java_start_url)));
info.scope = GURL(ConvertJavaStringToUTF8(env, java_scope));
info.name = ConvertJavaStringToUTF16(env, java_name);
info.short_name = ConvertJavaStringToUTF16(env, java_short_name);
info.user_title = info.short_name;
info.display = static_cast<blink::WebDisplayMode>(java_display_mode);
info.orientation =
static_cast<blink::WebScreenOrientationLockType>(java_orientation);
info.theme_color = (int64_t)java_theme_color;
info.background_color = (int64_t)java_background_color;
info.best_primary_icon_url =
GURL(ConvertJavaStringToUTF8(env, java_primary_icon_url));
info.best_badge_icon_url =
GURL(ConvertJavaStringToUTF8(env, java_badge_icon_url));
info.manifest_url = GURL(ConvertJavaStringToUTF8(env, java_web_manifest_url));
base::android::AppendJavaStringArrayToStringVector(env, java_icon_urls,
&info.icon_urls);
std::vector<std::string> icon_hashes;
base::android::AppendJavaStringArrayToStringVector(env, java_icon_hashes,
&icon_hashes);
std::map<std::string, std::string> icon_url_to_murmur2_hash;
for (size_t i = 0; i < info.icon_urls.size(); ++i)
icon_url_to_murmur2_hash[info.icon_urls[i]] = icon_hashes[i];
gfx::JavaBitmap java_primary_icon_bitmap_lock(java_primary_icon_bitmap);
SkBitmap primary_icon =
gfx::CreateSkBitmapFromJavaBitmap(java_primary_icon_bitmap_lock);
primary_icon.setImmutable();
SkBitmap badge_icon;
if (!java_badge_icon_bitmap.is_null()) {
gfx::JavaBitmap java_badge_icon_bitmap_lock(java_badge_icon_bitmap);
gfx::CreateSkBitmapFromJavaBitmap(java_badge_icon_bitmap_lock);
badge_icon.setImmutable();
}
std::string webapk_package;
ConvertJavaStringToUTF8(env, java_webapk_package, &webapk_package);
WebApkUpdateReason update_reason =
static_cast<WebApkUpdateReason>(java_update_reason);
WebApkInstaller::StoreUpdateRequestToFile(
base::FilePath(update_request_path), info, primary_icon, badge_icon,
webapk_package, std::to_string(java_webapk_version),
icon_url_to_murmur2_hash, java_is_manifest_stale, update_reason,
base::BindOnce(&base::android::RunBooleanCallbackAndroid,
ScopedJavaGlobalRef<jobject>(java_callback)));
}
Commit Message: [Android WebAPK] Send share target information in WebAPK updates
This CL plumbs through share target information for WebAPK updates.
Chromium detects Web Manifest updates (including Web Manifest share
target updates) and requests an update.
Currently, depending on whether the Web Manifest is for an intranet
site, the updated WebAPK would either:
- no longer be able handle share intents (even if the Web Manifest
share target information was not deleted)
- be created with the same share intent handlers as the current WebAPK
(regardless of whether the Web Manifest share target information has
changed).
This CL plumbs through the share target information from
WebApkUpdateDataFetcher#onDataAvailable() to
WebApkUpdateManager::StoreWebApkUpdateRequestToFile()
BUG=912945
Change-Id: Ie416570533abc848eeb23de8c197b44f2a1fd028
Reviewed-on: https://chromium-review.googlesource.com/c/1369709
Commit-Queue: Peter Kotwicz <[email protected]>
Reviewed-by: Dominick Ng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616429}
CWE ID: CWE-200
Target: 1
Example 2:
Code: int usbnet_get_settings (struct net_device *net, struct ethtool_cmd *cmd)
{
struct usbnet *dev = netdev_priv(net);
if (!dev->mii.mdio_read)
return -EOPNOTSUPP;
return mii_ethtool_gset(&dev->mii, cmd);
}
Commit Message: usbnet: cleanup after bind() in probe()
In case bind() works, but a later error forces bailing
in probe() in error cases work and a timer may be scheduled.
They must be killed. This fixes an error case related to
the double free reported in
http://www.spinics.net/lists/netdev/msg367669.html
and needs to go on top of Linus' fix to cdc-ncm.
Signed-off-by: Oliver Neukum <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void process_blob(struct rev_info *revs,
struct blob *blob,
show_object_fn show,
struct strbuf *path,
const char *name,
void *cb_data)
{
struct object *obj = &blob->object;
if (!revs->blob_objects)
return;
if (!obj)
die("bad blob object");
if (obj->flags & (UNINTERESTING | SEEN))
return;
obj->flags |= SEEN;
show(obj, path, name, cb_data);
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[email protected]>
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int SafeSock::handle_incoming_packet()
{
/* SOCKET_ALTERNATE_LENGTH_TYPE is void on this platform, and
since noone knows what that void* is supposed to point to
in recvfrom, I'm going to predict the "fromlen" variable
the recvfrom uses is a size_t sized quantity since
size_t is how you count bytes right? Stupid Solaris. */
bool last;
int seqNo, length;
_condorMsgID mID;
void* data;
int index;
int received;
_condorInMsg *tempMsg, *delMsg, *prev = NULL;
time_t curTime;
if( _msgReady ) {
char const *existing_msg_type;
bool existing_consumed;
if( _longMsg ) {
existing_msg_type = "long";
existing_consumed = _longMsg->consumed();
}
else {
existing_msg_type = "short";
existing_consumed = _shortMsg.consumed();
}
dprintf( D_ALWAYS,
"ERROR: receiving new UDP message but found a %s "
"message still waiting to be closed (consumed=%d). "
"Closing it now.\n",
existing_msg_type, existing_consumed );
stream_coding saved_coding = _coding;
_coding = stream_decode;
end_of_message();
_coding = saved_coding;
}
received = condor_recvfrom(_sock, _shortMsg.dataGram,
SAFE_MSG_MAX_PACKET_SIZE, 0, _who);
if(received < 0) {
dprintf(D_NETWORK, "recvfrom failed: errno = %d\n", errno);
return FALSE;
}
char str[50];
sprintf(str, sock_to_string(_sock));
dprintf( D_NETWORK, "RECV %d bytes at %s from %s\n",
received, str, _who.to_sinful().Value());
length = received;
_shortMsg.reset(); // To be sure
bool is_full_message = _shortMsg.getHeader(received, last, seqNo, length, mID, data);
if ( length <= 0 || length > SAFE_MSG_MAX_PACKET_SIZE ) {
dprintf(D_ALWAYS,"IO: Incoming datagram improperly sized\n");
return FALSE;
}
if ( is_full_message ) {
_shortMsg.curIndex = 0;
_msgReady = true;
_whole++;
if(_whole == 1)
_avgSwhole = length;
else
_avgSwhole = ((_whole - 1) * _avgSwhole + length) / _whole;
_noMsgs++;
dprintf( D_NETWORK, "\tFull msg [%d bytes]\n", length);
return TRUE;
}
dprintf( D_NETWORK, "\tFrag [%d bytes]\n", length);
/* long message */
curTime = (unsigned long)time(NULL);
index = labs(mID.ip_addr + mID.time + mID.msgNo) % SAFE_SOCK_HASH_BUCKET_SIZE;
tempMsg = _inMsgs[index];
while(tempMsg != NULL && !same(tempMsg->msgID, mID)) {
prev = tempMsg;
tempMsg = tempMsg->nextMsg;
if(curTime - prev->lastTime > _tOutBtwPkts) {
dprintf(D_NETWORK, "found timed out msg: cur=%lu, msg=%lu\n",
curTime, prev->lastTime);
delMsg = prev;
prev = delMsg->prevMsg;
if(prev)
prev->nextMsg = delMsg->nextMsg;
else // delMsg is the 1st message in the chain
_inMsgs[index] = tempMsg;
if(tempMsg)
tempMsg->prevMsg = prev;
_deleted++;
if(_deleted == 1)
_avgSdeleted = delMsg->msgLen;
else {
_avgSdeleted = ((_deleted - 1) * _avgSdeleted + delMsg->msgLen) / _deleted;
}
dprintf(D_NETWORK, "Deleting timeouted message:\n");
delMsg->dumpMsg();
delete delMsg;
}
}
if(tempMsg != NULL) { // found
if (seqNo == 0) {
tempMsg->set_sec(_shortMsg.isDataMD5ed(),
_shortMsg.md(),
_shortMsg.isDataEncrypted());
}
bool rst = tempMsg->addPacket(last, seqNo, length, data);
if (rst) {
_longMsg = tempMsg;
_msgReady = true;
_whole++;
if(_whole == 1)
_avgSwhole = _longMsg->msgLen;
else
_avgSwhole = ((_whole - 1) * _avgSwhole + _longMsg->msgLen) / _whole;
return TRUE;
}
return FALSE;
} else { // not found
if(prev) { // add a new message at the end of the chain
prev->nextMsg = new _condorInMsg(mID, last, seqNo, length, data,
_shortMsg.isDataMD5ed(),
_shortMsg.md(),
_shortMsg.isDataEncrypted(), prev);
if(!prev->nextMsg) {
EXCEPT("Error:handle_incomming_packet: Out of Memory");
}
} else { // first message in the bucket
_inMsgs[index] = new _condorInMsg(mID, last, seqNo, length, data,
_shortMsg.isDataMD5ed(),
_shortMsg.md(),
_shortMsg.isDataEncrypted(), NULL);
if(!_inMsgs[index]) {
EXCEPT("Error:handle_incomming_packet: Out of Memory");
}
}
_noMsgs++;
return FALSE;
}
}
Commit Message:
CWE ID: CWE-134
Target: 1
Example 2:
Code: fz_default_output_intent(fz_context *ctx, const fz_default_colorspaces *default_cs)
{
if (default_cs)
return default_cs->oi;
else
return NULL;
}
Commit Message:
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int PaintLayerScrollableArea::ScrollSize(
ScrollbarOrientation orientation) const {
IntSize scroll_dimensions =
MaximumScrollOffsetInt() - MinimumScrollOffsetInt();
return (orientation == kHorizontalScrollbar) ? scroll_dimensions.Width()
: scroll_dimensions.Height();
}
Commit Message: Always call UpdateCompositedScrollOffset, not just for the root layer
Bug: 927560
Change-Id: I1d5522aae4f11dd3f5b8947bb089bac1bf19bdb4
Reviewed-on: https://chromium-review.googlesource.com/c/1452701
Reviewed-by: Chris Harrelson <[email protected]>
Commit-Queue: Mason Freed <[email protected]>
Cr-Commit-Position: refs/heads/master@{#628942}
CWE ID: CWE-79
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool Init(const IPC::ChannelHandle& channel_handle,
PP_Module pp_module,
PP_GetInterface_Func local_get_interface,
const ppapi::Preferences& preferences,
SyncMessageStatusReceiver* status_receiver) {
dispatcher_delegate_.reset(new ProxyChannelDelegate);
dispatcher_.reset(new ppapi::proxy::HostDispatcher(
pp_module, local_get_interface, status_receiver));
if (!dispatcher_->InitHostWithChannel(dispatcher_delegate_.get(),
channel_handle,
true, // Client.
preferences)) {
dispatcher_.reset();
dispatcher_delegate_.reset();
return false;
}
return true;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: void NavigationControllerImpl::ClearAllScreenshots() {
screenshot_manager_->ClearAllScreenshots();
}
Commit Message: Delete unneeded pending entries in DidFailProvisionalLoad to prevent a spoof.
BUG=280512
BUG=278899
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/23978003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@222146 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static GList *find_words_in_text_buffer(int page,
GtkTextView *tev,
GList *words,
GList *ignore_sitem_list,
GtkTextIter start_find,
GtkTextIter end_find,
bool case_insensitive
)
{
GtkTextBuffer *buffer = gtk_text_view_get_buffer(tev);
gtk_text_buffer_set_modified(buffer, FALSE);
GList *found_words = NULL;
GtkTextIter start_match;
GtkTextIter end_match;
for (GList *w = words; w; w = g_list_next(w))
{
gtk_text_buffer_get_start_iter(buffer, &start_find);
const char *search_word = w->data;
while (search_word && search_word[0] && gtk_text_iter_forward_search(&start_find, search_word,
GTK_TEXT_SEARCH_TEXT_ONLY | (case_insensitive ? GTK_TEXT_SEARCH_CASE_INSENSITIVE : 0),
&start_match,
&end_match, NULL))
{
search_item_t *found_word = sitem_new(
page,
buffer,
tev,
start_match,
end_match
);
int offset = gtk_text_iter_get_offset(&end_match);
gtk_text_buffer_get_iter_at_offset(buffer, &start_find, offset);
if (sitem_is_in_sitemlist(found_word, ignore_sitem_list))
{
sitem_free(found_word);
continue;
}
found_words = g_list_prepend(found_words, found_word);
}
}
return found_words;
}
Commit Message: wizard: fix save users changes after reviewing dump dir files
If the user reviewed the dump dir's files during reporting the crash, the
changes was thrown away and original data was passed to the bugzilla bug
report.
report-gtk saves the first text view buffer and then reloads data from the
reported problem directory, which causes that the changes made to those text
views are thrown away.
Function save_text_if_changed(), except of saving text, also reload the files
from dump dir and update gui state from the dump dir. The commit moves the
reloading and updating gui functions away from this function.
Related to rhbz#1270235
Signed-off-by: Matej Habrnal <[email protected]>
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static boolean str_fill_input_buffer(j_decompress_ptr cinfo)
{
int c;
struct str_src_mgr * src = (struct str_src_mgr *)cinfo->src;
if (src->abort) return FALSE;
if (src->index == 0) {
c = 0xFF;
src->index++;
src->index++;
}
else if (src->index == 1) {
c = 0xD8;
src->index++;
}
else c = src->str->getChar();
if (c != EOF)
{
src->buffer = c;
src->pub.next_input_byte = &src->buffer;
src->pub.bytes_in_buffer = 1;
return TRUE;
}
else return FALSE;
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: vrend_insert_format_swizzle(int override_format, struct vrend_format_table *entry, uint32_t bindings, uint8_t swizzle[4])
{
int i;
tex_conv_table[override_format] = *entry;
tex_conv_table[override_format].bindings = bindings;
tex_conv_table[override_format].flags = VREND_BIND_NEED_SWIZZLE;
for (i = 0; i < 4; i++)
tex_conv_table[override_format].swizzle[i] = swizzle[i];
}
Commit Message:
CWE ID: CWE-772
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static unsigned char *DecodeImage(Image *blob,Image *image,
size_t bytes_per_line,const unsigned int bits_per_pixel,size_t *extent,
ExceptionInfo *exception)
{
MagickSizeType
number_pixels;
register ssize_t
i;
register unsigned char
*p,
*q;
size_t
bytes_per_pixel,
length,
row_bytes,
scanline_length,
width;
ssize_t
count,
j,
y;
unsigned char
*pixels,
*scanline;
/*
Determine pixel buffer size.
*/
if (bits_per_pixel <= 8)
bytes_per_line&=0x7fff;
width=image->columns;
bytes_per_pixel=1;
if (bits_per_pixel == 16)
{
bytes_per_pixel=2;
width*=2;
}
else
if (bits_per_pixel == 32)
width*=image->alpha_trait ? 4 : 3;
if (bytes_per_line == 0)
bytes_per_line=width;
row_bytes=(size_t) (image->columns | 0x8000);
if (image->storage_class == DirectClass)
row_bytes=(size_t) ((4*image->columns) | 0x8000);
/*
Allocate pixel and scanline buffer.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->rows,row_bytes*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
return((unsigned char *) NULL);
*extent=row_bytes*image->rows*sizeof(*pixels);
(void) ResetMagickMemory(pixels,0,*extent);
scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,2*
sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
return((unsigned char *) NULL);
if (bytes_per_line < 8)
{
/*
Pixels are already uncompressed.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=pixels+y*width*GetPixelChannels(image);;
number_pixels=bytes_per_line;
count=ReadBlob(blob,(size_t) number_pixels,scanline);
if (count != (ssize_t) number_pixels)
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"UnableToUncompressImage","`%s'",
image->filename);
break;
}
p=ExpandBuffer(scanline,&number_pixels,bits_per_pixel);
if ((q+number_pixels) > (pixels+(*extent)))
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"UnableToUncompressImage","`%s'",
image->filename);
break;
}
(void) CopyMagickMemory(q,p,(size_t) number_pixels);
}
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
return(pixels);
}
/*
Uncompress RLE pixels into uncompressed pixel buffer.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=pixels+y*width;
if (bytes_per_line > 200)
scanline_length=ReadBlobMSBShort(blob);
else
scanline_length=1UL*ReadBlobByte(blob);
if (scanline_length >= row_bytes)
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"UnableToUncompressImage","`%s'",image->filename);
break;
}
count=ReadBlob(blob,scanline_length,scanline);
if (count != (ssize_t) scanline_length)
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"UnableToUncompressImage","`%s'",image->filename);
break;
}
for (j=0; j < (ssize_t) scanline_length; )
if ((scanline[j] & 0x80) == 0)
{
length=(size_t) ((scanline[j] & 0xff)+1);
number_pixels=length*bytes_per_pixel;
p=ExpandBuffer(scanline+j+1,&number_pixels,bits_per_pixel);
if ((q-pixels+number_pixels) <= *extent)
(void) CopyMagickMemory(q,p,(size_t) number_pixels);
q+=number_pixels;
j+=(ssize_t) (length*bytes_per_pixel+1);
}
else
{
length=(size_t) (((scanline[j] ^ 0xff) & 0xff)+2);
number_pixels=bytes_per_pixel;
p=ExpandBuffer(scanline+j+1,&number_pixels,bits_per_pixel);
for (i=0; i < (ssize_t) length; i++)
{
if ((q-pixels+number_pixels) <= *extent)
(void) CopyMagickMemory(q,p,(size_t) number_pixels);
q+=number_pixels;
}
j+=(ssize_t) bytes_per_pixel+1;
}
}
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
return(pixels);
}
Commit Message:
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: _PUBLIC_ size_t strlen_m_ext_handle(struct smb_iconv_handle *ic,
const char *s, charset_t src_charset, charset_t dst_charset)
{
size_t count = 0;
#ifdef DEVELOPER
switch (dst_charset) {
case CH_DOS:
case CH_UNIX:
smb_panic("cannot call strlen_m_ext() with a variable dest charset (must be UTF16* or UTF8)");
default:
break;
}
switch (src_charset) {
case CH_UTF16LE:
case CH_UTF16BE:
smb_panic("cannot call strlen_m_ext() with a UTF16 src charset (must be DOS, UNIX, DISPLAY or UTF8)");
default:
break;
}
#endif
if (!s) {
return 0;
}
while (*s && !(((uint8_t)*s) & 0x80)) {
s++;
count++;
}
if (!*s) {
return count;
}
while (*s) {
size_t c_size;
codepoint_t c = next_codepoint_handle_ext(ic, s, src_charset, &c_size);
s += c_size;
switch (dst_charset) {
case CH_UTF16BE:
case CH_UTF16MUNGED:
if (c < 0x10000) {
/* Unicode char fits into 16 bits. */
count += 1;
} else {
/* Double-width unicode char - 32 bits. */
count += 2;
}
break;
case CH_UTF8:
/*
* this only checks ranges, and does not
* check for invalid codepoints
*/
if (c < 0x80) {
count += 1;
} else if (c < 0x800) {
count += 2;
} else if (c < 0x10000) {
count += 3;
} else {
count += 4;
}
break;
default:
/*
* non-unicode encoding:
* assume that each codepoint fits into
* one unit in the destination encoding.
*/
count += 1;
}
}
return count;
}
Commit Message:
CWE ID: CWE-200
Target: 1
Example 2:
Code: TestInputMethodManager* imm() { return input_method_manager_; }
Commit Message: Clear |composing_text_| after CommitText() is called.
|composing_text_| of InputConnectionImpl should be cleared after
CommitText() is called. Otherwise, FinishComposingText() will commit the
same text twice.
Bug: 899736
Test: unit_tests
Change-Id: Idb22d968ffe95d946789fbe62454e8e79cb0b384
Reviewed-on: https://chromium-review.googlesource.com/c/1304773
Commit-Queue: Yusuke Sato <[email protected]>
Reviewed-by: Yusuke Sato <[email protected]>
Cr-Commit-Position: refs/heads/master@{#603518}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void AudioRendererHost::DoSendPausedMessage(
media::AudioOutputController* controller) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
AudioEntry* entry = LookupByController(controller);
if (!entry)
return;
Send(new AudioMsg_NotifyStreamStateChanged(
entry->stream_id, media::AudioOutputIPCDelegate::kPaused));
}
Commit Message: Improve validation when creating audio streams.
BUG=166795
Review URL: https://codereview.chromium.org/11647012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173981 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int nfc_llcp_send_cc(struct nfc_llcp_sock *sock)
{
struct nfc_llcp_local *local;
struct sk_buff *skb;
u8 *miux_tlv = NULL, miux_tlv_length;
u8 *rw_tlv = NULL, rw_tlv_length, rw;
int err;
u16 size = 0;
__be16 miux;
pr_debug("Sending CC\n");
local = sock->local;
if (local == NULL)
return -ENODEV;
/* If the socket parameters are not set, use the local ones */
miux = be16_to_cpu(sock->miux) > LLCP_MAX_MIUX ?
local->miux : sock->miux;
rw = sock->rw > LLCP_MAX_RW ? local->rw : sock->rw;
miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&miux, 0,
&miux_tlv_length);
size += miux_tlv_length;
rw_tlv = nfc_llcp_build_tlv(LLCP_TLV_RW, &rw, 0, &rw_tlv_length);
size += rw_tlv_length;
skb = llcp_allocate_pdu(sock, LLCP_PDU_CC, size);
if (skb == NULL) {
err = -ENOMEM;
goto error_tlv;
}
llcp_add_tlv(skb, miux_tlv, miux_tlv_length);
llcp_add_tlv(skb, rw_tlv, rw_tlv_length);
skb_queue_tail(&local->tx_queue, skb);
err = 0;
error_tlv:
if (err)
pr_err("error %d\n", err);
kfree(miux_tlv);
kfree(rw_tlv);
return err;
}
Commit Message: net: nfc: Fix NULL dereference on nfc_llcp_build_tlv fails
KASAN report this:
BUG: KASAN: null-ptr-deref in nfc_llcp_build_gb+0x37f/0x540 [nfc]
Read of size 3 at addr 0000000000000000 by task syz-executor.0/5401
CPU: 0 PID: 5401 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
Call Trace:
__dump_stack lib/dump_stack.c:77 [inline]
dump_stack+0xfa/0x1ce lib/dump_stack.c:113
kasan_report+0x171/0x18d mm/kasan/report.c:321
memcpy+0x1f/0x50 mm/kasan/common.c:130
nfc_llcp_build_gb+0x37f/0x540 [nfc]
nfc_llcp_register_device+0x6eb/0xb50 [nfc]
nfc_register_device+0x50/0x1d0 [nfc]
nfcsim_device_new+0x394/0x67d [nfcsim]
? 0xffffffffc1080000
nfcsim_init+0x6b/0x1000 [nfcsim]
do_one_initcall+0xfa/0x5ca init/main.c:887
do_init_module+0x204/0x5f6 kernel/module.c:3460
load_module+0x66b2/0x8570 kernel/module.c:3808
__do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902
do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f9cb79dcc58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 0000000020000280 RDI: 0000000000000003
RBP: 00007f9cb79dcc70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007f9cb79dd6bc
R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004
nfc_llcp_build_tlv will return NULL on fails, caller should check it,
otherwise will trigger a NULL dereference.
Reported-by: Hulk Robot <[email protected]>
Fixes: eda21f16a5ed ("NFC: Set MIU and RW values from CONNECT and CC LLCP frames")
Fixes: d646960f7986 ("NFC: Initial LLCP support")
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-476
Target: 1
Example 2:
Code: BGD_DECLARE(gdImagePtr) gdImageCreateTrueColor (int sx, int sy)
{
int i;
gdImagePtr im;
if (overflow2(sx, sy)) {
return NULL;
}
if (overflow2(sizeof (int *), sy)) {
return 0;
}
if (overflow2(sizeof(int), sx)) {
return NULL;
}
im = (gdImage *) gdMalloc (sizeof (gdImage));
if (!im) {
return 0;
}
memset (im, 0, sizeof (gdImage));
im->tpixels = (int **) gdMalloc (sizeof (int *) * sy);
if (!im->tpixels) {
gdFree(im);
return 0;
}
im->polyInts = 0;
im->polyAllocated = 0;
im->brush = 0;
im->tile = 0;
im->style = 0;
for (i = 0; (i < sy); i++) {
im->tpixels[i] = (int *) gdCalloc (sx, sizeof (int));
if (!im->tpixels[i]) {
/* 2.0.34 */
i--;
while (i >= 0) {
gdFree(im->tpixels[i]);
i--;
}
gdFree(im->tpixels);
gdFree(im);
return 0;
}
}
im->sx = sx;
im->sy = sy;
im->transparent = (-1);
im->interlace = 0;
im->trueColor = 1;
/* 2.0.2: alpha blending is now on by default, and saving of alpha is
off by default. This allows font antialiasing to work as expected
on the first try in JPEGs -- quite important -- and also allows
for smaller PNGs when saving of alpha channel is not really
desired, which it usually isn't! */
im->saveAlphaFlag = 0;
im->alphaBlendingFlag = 1;
im->thick = 1;
im->AA = 0;
im->cx1 = 0;
im->cy1 = 0;
im->cx2 = im->sx - 1;
im->cy2 = im->sy - 1;
im->res_x = GD_RESOLUTION;
im->res_y = GD_RESOLUTION;
im->interpolation = NULL;
im->interpolation_id = GD_BILINEAR_FIXED;
return im;
}
Commit Message: fix #215 gdImageFillToBorder stack-overflow when invalid color is used
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: BnMemory::~BnMemory() {
}
Commit Message: Sanity check IMemory access versus underlying mmap
Bug 26877992
Change-Id: Ibbf4b1061e4675e4e96bc944a865b53eaf6984fe
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: CompositedLayerRasterInvalidatorTest& Properties(
const RefCountedPropertyTreeState& state) {
data_.chunks.back().properties = state;
return *this;
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID:
Target: 1
Example 2:
Code: void ContentSecurityPolicy::SetOverrideURLForSelf(const KURL& url) {
scoped_refptr<const SecurityOrigin> origin = SecurityOrigin::Create(url);
self_protocol_ = origin->Protocol();
self_source_ =
new CSPSource(this, self_protocol_, origin->Host(), origin->Port(),
String(), CSPSource::kNoWildcard, CSPSource::kNoWildcard);
}
Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener
Spec PR: https://github.com/w3c/webappsec-csp/pull/358
Bug: 905301, 894228, 836148
Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a
Reviewed-on: https://chromium-review.googlesource.com/c/1314633
Commit-Queue: Andy Paicu <[email protected]>
Reviewed-by: Mike West <[email protected]>
Cr-Commit-Position: refs/heads/master@{#610850}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: SPL_METHOD(DirectoryIterator, getBasename)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *suffix = 0, *fname;
int slen = 0;
size_t flen;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) {
return;
}
php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC);
RETURN_STRINGL(fname, flen, 0);
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadWPGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
typedef struct
{
size_t FileId;
MagickOffsetType DataOffset;
unsigned int ProductType;
unsigned int FileType;
unsigned char MajorVersion;
unsigned char MinorVersion;
unsigned int EncryptKey;
unsigned int Reserved;
} WPGHeader;
typedef struct
{
unsigned char RecType;
size_t RecordLength;
} WPGRecord;
typedef struct
{
unsigned char Class;
unsigned char RecType;
size_t Extension;
size_t RecordLength;
} WPG2Record;
typedef struct
{
unsigned HorizontalUnits;
unsigned VerticalUnits;
unsigned char PosSizePrecision;
} WPG2Start;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType1;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned char Depth;
unsigned char Compression;
} WPG2BitmapType1;
typedef struct
{
unsigned int RotAngle;
unsigned int LowLeftX;
unsigned int LowLeftY;
unsigned int UpRightX;
unsigned int UpRightY;
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType2;
typedef struct
{
unsigned int StartIndex;
unsigned int NumOfEntries;
} WPGColorMapRec;
/*
typedef struct {
size_t PS_unknown1;
unsigned int PS_unknown2;
unsigned int PS_unknown3;
} WPGPSl1Record;
*/
Image
*image;
unsigned int
status;
WPGHeader
Header;
WPGRecord
Rec;
WPG2Record
Rec2;
WPG2Start StartWPG;
WPGBitmapType1
BitmapHeader1;
WPG2BitmapType1
Bitmap2Header1;
WPGBitmapType2
BitmapHeader2;
WPGColorMapRec
WPG_Palette;
int
i,
bpp,
WPG2Flags;
ssize_t
ldblk;
size_t
one;
unsigned char
*BImgBuff;
tCTM CTM; /*current transform matrix*/
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
one=1;
image=AcquireImage(image_info);
image->depth=8;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read WPG image.
*/
Header.FileId=ReadBlobLSBLong(image);
Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image);
Header.ProductType=ReadBlobLSBShort(image);
Header.FileType=ReadBlobLSBShort(image);
Header.MajorVersion=ReadBlobByte(image);
Header.MinorVersion=ReadBlobByte(image);
Header.EncryptKey=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (Header.EncryptKey!=0)
ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported");
image->columns = 1;
image->rows = 1;
image->colors = 0;
bpp=0;
BitmapHeader2.RotAngle=0;
switch(Header.FileType)
{
case 1: /* WPG level 1 */
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec.RecordLength;
switch(Rec.RecType)
{
case 0x0B: /* bitmap type 1 */
BitmapHeader1.Width=ReadBlobLSBShort(image);
BitmapHeader1.Height=ReadBlobLSBShort(image);
if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader1.Depth=ReadBlobLSBShort(image);
BitmapHeader1.HorzRes=ReadBlobLSBShort(image);
BitmapHeader1.VertRes=ReadBlobLSBShort(image);
if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=BitmapHeader1.HorzRes/470.0;
image->y_resolution=BitmapHeader1.VertRes/470.0;
}
image->columns=BitmapHeader1.Width;
image->rows=BitmapHeader1.Height;
bpp=BitmapHeader1.Depth;
goto UnpackRaster;
case 0x0E: /*Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (!AcquireImageColormap(image,image->colors))
goto NoMemory;
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
}
break;
case 0x11: /* Start PS l1 */
if(Rec.RecordLength > 8)
image=ExtractPostscript(image,image_info,
TellBlob(image)+8, /* skip PS header in the wpg */
(ssize_t) Rec.RecordLength-8,exception);
break;
case 0x14: /* bitmap type 2 */
BitmapHeader2.RotAngle=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftX=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftY=ReadBlobLSBShort(image);
BitmapHeader2.UpRightX=ReadBlobLSBShort(image);
BitmapHeader2.UpRightY=ReadBlobLSBShort(image);
BitmapHeader2.Width=ReadBlobLSBShort(image);
BitmapHeader2.Height=ReadBlobLSBShort(image);
if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader2.Depth=ReadBlobLSBShort(image);
BitmapHeader2.HorzRes=ReadBlobLSBShort(image);
BitmapHeader2.VertRes=ReadBlobLSBShort(image);
image->units=PixelsPerCentimeterResolution;
image->page.width=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0);
image->page.height=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0);
image->page.x=(int) (BitmapHeader2.LowLeftX/470.0);
image->page.y=(int) (BitmapHeader2.LowLeftX/470.0);
if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes)
{
image->x_resolution=BitmapHeader2.HorzRes/470.0;
image->y_resolution=BitmapHeader2.VertRes/470.0;
}
image->columns=BitmapHeader2.Width;
image->rows=BitmapHeader2.Height;
bpp=BitmapHeader2.Depth;
UnpackRaster:
if ((image->colors == 0) && (bpp != 24))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors))
{
NoMemory:
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
/* printf("Load default colormap \n"); */
for (i=0; (i < (int) image->colors) && (i < 256); i++)
{
image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red);
image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green);
image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue);
}
}
else
{
if (bpp < 24)
if ( (image->colors < (one << bpp)) && (bpp != 24) )
image->colormap=(PixelPacket *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
if (bpp == 1)
{
if(image->colormap[0].red==0 &&
image->colormap[0].green==0 &&
image->colormap[0].blue==0 &&
image->colormap[1].red==0 &&
image->colormap[1].green==0 &&
image->colormap[1].blue==0)
{ /* fix crippled monochrome palette */
image->colormap[1].red =
image->colormap[1].green =
image->colormap[1].blue = QuantumRange;
}
}
if(UnpackWPGRaster(image,bpp) < 0)
/* The raster cannot be unpacked */
{
DecompressionFailed:
ThrowReaderException(CoderError,"UnableToDecompressImage");
}
if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping)
{
/* flop command */
if(BitmapHeader2.RotAngle & 0x8000)
{
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
}
/* flip command */
if(BitmapHeader2.RotAngle & 0x2000)
{
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
}
/* rotate command */
if(BitmapHeader2.RotAngle & 0x0FFF)
{
Image
*rotate_image;
rotate_image=RotateImage(image,(BitmapHeader2.RotAngle &
0x0FFF), exception);
if (rotate_image != (Image *) NULL) {
DuplicateBlob(rotate_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,rotate_image);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
break;
case 0x1B: /* Postscript l2 */
if(Rec.RecordLength>0x3C)
image=ExtractPostscript(image,image_info,
TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */
(ssize_t) Rec.RecordLength-0x3C,exception);
break;
}
}
break;
case 2: /* WPG level 2 */
(void) memset(CTM,0,sizeof(CTM));
StartWPG.PosSizePrecision = 0;
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec2.Class=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rec2.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec2.Extension);
Rd_WP_DWORD(image,&Rec2.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec2.RecordLength;
switch(Rec2.RecType)
{
case 1:
StartWPG.HorizontalUnits=ReadBlobLSBShort(image);
StartWPG.VerticalUnits=ReadBlobLSBShort(image);
StartWPG.PosSizePrecision=ReadBlobByte(image);
break;
case 0x0C: /* Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((char)
ReadBlobByte(image));
(void) ReadBlobByte(image); /*Opacity??*/
}
break;
case 0x0E:
Bitmap2Header1.Width=ReadBlobLSBShort(image);
Bitmap2Header1.Height=ReadBlobLSBShort(image);
if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
Bitmap2Header1.Depth=ReadBlobByte(image);
Bitmap2Header1.Compression=ReadBlobByte(image);
if(Bitmap2Header1.Compression > 1)
continue; /*Unknown compression method */
switch(Bitmap2Header1.Depth)
{
case 1:
bpp=1;
break;
case 2:
bpp=2;
break;
case 3:
bpp=4;
break;
case 4:
bpp=8;
break;
case 8:
bpp=24;
break;
default:
continue; /*Ignore raster with unknown depth*/
}
image->columns=Bitmap2Header1.Width;
image->rows=Bitmap2Header1.Height;
if ((image->colors == 0) && (bpp != 24))
{
size_t
one;
one=1;
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors))
goto NoMemory;
}
else
{
if(bpp < 24)
if( image->colors<(one << bpp) && bpp!=24 )
image->colormap=(PixelPacket *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
switch(Bitmap2Header1.Compression)
{
case 0: /*Uncompressed raster*/
{
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t)
ldblk,sizeof(*BImgBuff));
if (BImgBuff == (unsigned char *) NULL)
goto NoMemory;
for(i=0; i< (ssize_t) image->rows; i++)
{
(void) ReadBlob(image,ldblk,BImgBuff);
InsertRow(BImgBuff,i,image,bpp);
}
if(BImgBuff)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);;
break;
}
case 1: /*RLE for WPG2 */
{
if( UnpackWPG2Raster(image,bpp) < 0)
goto DecompressionFailed;
break;
}
}
if(CTM[0][0]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0;
Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll);
Tx(1,2)=0; Tx(2,2)=1; */
}
if(CTM[1][1]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
float_matrix Tx(3,3);
Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0;
Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll);
Tx(2,2)=1; */
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x12: /* Postscript WPG2*/
i=ReadBlobLSBShort(image);
if(Rec2.RecordLength > (unsigned int) i)
image=ExtractPostscript(image,image_info,
TellBlob(image)+i, /*skip PS header in the wpg2*/
(ssize_t) (Rec2.RecordLength-i-2),exception);
break;
case 0x1B: /*bitmap rectangle*/
WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM);
(void) WPG2Flags;
break;
}
}
break;
default:
{
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
}
}
Finish:
(void) CloseBlob(image);
{
Image
*p;
ssize_t
scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers.
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=(size_t) scene++;
}
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,
"ImageFileDoesNotContainAnyImageData");
return(image);
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: static long ec_device_ioctl_readmem(struct cros_ec_dev *ec, void __user *arg)
{
struct cros_ec_device *ec_dev = ec->ec_dev;
struct cros_ec_readmem s_mem = { };
long num;
/* Not every platform supports direct reads */
if (!ec_dev->cmd_readmem)
return -ENOTTY;
if (copy_from_user(&s_mem, arg, sizeof(s_mem)))
return -EFAULT;
num = ec_dev->cmd_readmem(ec_dev, s_mem.offset, s_mem.bytes,
s_mem.buffer);
if (num <= 0)
return num;
if (copy_to_user((void __user *)arg, &s_mem, sizeof(s_mem)))
return -EFAULT;
return 0;
}
Commit Message: platform/chrome: cros_ec_dev - double fetch bug in ioctl
We verify "u_cmd.outsize" and "u_cmd.insize" but we need to make sure
that those values have not changed between the two copy_from_user()
calls. Otherwise it could lead to a buffer overflow.
Additionally, cros_ec_cmd_xfer() can set s_cmd->insize to a lower value.
We should use the new smaller value so we don't copy too much data to
the user.
Reported-by: Pengfei Wang <[email protected]>
Fixes: a841178445bb ('mfd: cros_ec: Use a zero-length array for command data')
Signed-off-by: Dan Carpenter <[email protected]>
Reviewed-by: Kees Cook <[email protected]>
Tested-by: Gwendal Grignou <[email protected]>
Cc: <[email protected]> # v4.2+
Signed-off-by: Olof Johansson <[email protected]>
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Track::GetContentEncodingByIndex(unsigned long idx) const {
const ptrdiff_t count =
content_encoding_entries_end_ - content_encoding_entries_;
assert(count >= 0);
if (idx >= static_cast<unsigned long>(count))
return NULL;
return content_encoding_entries_[idx];
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: struct nfs_open_context *nfs_find_open_context(struct inode *inode, struct rpc_cred *cred, int mode)
{
struct nfs_inode *nfsi = NFS_I(inode);
struct nfs_open_context *pos, *ctx = NULL;
spin_lock(&inode->i_lock);
list_for_each_entry(pos, &nfsi->open_files, list) {
if (cred != NULL && pos->cred != cred)
continue;
if ((pos->mode & mode) == mode) {
ctx = get_nfs_open_context(pos);
break;
}
}
spin_unlock(&inode->i_lock);
return ctx;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: bool ExtensionApiTest::RunComponentExtensionTestWithArg(
const std::string& extension_name,
const char* custom_arg) {
return RunExtensionTestImpl(extension_name, std::string(), custom_arg,
kFlagEnableFileAccess | kFlagLoadAsComponent);
}
Commit Message: Call CanCaptureVisiblePage in page capture API.
Currently the pageCapture permission allows access
to arbitrary local files and chrome:// pages which
can be a security concern. In order to address this,
the page capture API needs to be changed similar to
the captureVisibleTab API. The API will now only allow
extensions to capture otherwise-restricted URLs if the
user has granted activeTab. In addition, file:// URLs are
only capturable with the "Allow on file URLs" option enabled.
Bug: 893087
Change-Id: I6d6225a3efb70fc033e2e1c031c633869afac624
Reviewed-on: https://chromium-review.googlesource.com/c/1330689
Commit-Queue: Bettina Dea <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Varun Khaneja <[email protected]>
Cr-Commit-Position: refs/heads/master@{#615248}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: _WM_ParseNewMus(uint8_t *mus_data, uint32_t mus_size) {
uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A };
uint32_t mus_song_ofs = 0;
uint32_t mus_song_len = 0;
uint16_t mus_ch_cnt1 = 0;
uint16_t mus_ch_cnt2 = 0;
uint16_t mus_no_instr = 0;
uint32_t mus_data_ofs = 0;
uint16_t * mus_mid_instr = NULL;
uint16_t mus_instr_cnt = 0;
struct _mdi *mus_mdi;
uint32_t mus_divisions = 60;
float tempo_f = 0.0;
uint16_t mus_freq = 0;
float samples_per_tick_f = 0.0;
uint8_t mus_event[] = { 0, 0, 0, 0 };
uint8_t mus_event_size = 0;
uint8_t mus_prev_vol[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
uint32_t setup_ret = 0;
uint32_t mus_ticks = 0;
uint32_t sample_count = 0;
float sample_count_f = 0.0;
float sample_remainder = 0.0;
uint16_t pitchbend_tmp = 0;
if (mus_size < 17) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, "File too short", 0);
return NULL;
}
if (memcmp(mus_data, mus_hdr, 4)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, NULL, 0);
return NULL;
}
mus_song_len = (mus_data[5] << 8) | mus_data[4];
mus_song_ofs = (mus_data[7] << 8) | mus_data[6];
mus_ch_cnt1 = (mus_data[9] << 8) | mus_data[8];
mus_ch_cnt2 = (mus_data[11] << 8) | mus_data[10];
UNUSED(mus_ch_cnt1);
UNUSED(mus_ch_cnt2);
mus_no_instr = (mus_data[13] << 8) | mus_data[12];
mus_data_ofs = 16;
if (mus_size < (mus_data_ofs + (mus_no_instr << 1) + mus_song_len)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, "File too short", 0);
return NULL;
}
mus_mid_instr = malloc(mus_no_instr * sizeof(uint16_t));
for (mus_instr_cnt = 0; mus_instr_cnt < mus_no_instr; mus_instr_cnt++) {
mus_mid_instr[mus_instr_cnt] = (mus_data[mus_data_ofs + 1] << 8) | mus_data[mus_data_ofs];
mus_data_ofs += 2;
}
mus_data_ofs = mus_song_ofs;
mus_freq = _cvt_get_option(WM_CO_FREQUENCY);
if (mus_freq == 0) mus_freq = 140;
if ((_WM_MixerOptions & WM_MO_ROUNDTEMPO)) {
tempo_f = (float) (60000000 / mus_freq) + 0.5f;
} else {
tempo_f = (float) (60000000 / mus_freq);
}
samples_per_tick_f = _WM_GetSamplesPerTick(mus_divisions, (uint32_t)tempo_f);
mus_mdi = _WM_initMDI();
_WM_midi_setup_divisions(mus_mdi, mus_divisions);
_WM_midi_setup_tempo(mus_mdi, (uint32_t)tempo_f);
do {
_mus_build_event:
#if 1
MUS_EVENT_DEBUG("Before", mus_data[mus_data_ofs], 0);
if ((mus_data[mus_data_ofs] & 0x0f) == 0x0f) {
mus_data[mus_data_ofs] = (mus_data[mus_data_ofs] & 0xf0) | 0x09;
} else if ((mus_data[mus_data_ofs] & 0x0f) == 0x09) {
mus_data[mus_data_ofs] = (mus_data[mus_data_ofs] & 0xf0) | 0x0f;
}
MUS_EVENT_DEBUG("After", mus_data[mus_data_ofs], 0);
#endif
switch ((mus_data[mus_data_ofs] >> 4) & 0x07) {
case 0: // Note Off
mus_event_size = 2;
mus_event[0] = 0x80 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = mus_data[mus_data_ofs + 1];
mus_event[2] = 0;
mus_event[3] = 0;
break;
case 1: // Note On
if (mus_data[mus_data_ofs + 1] & 0x80) {
mus_event_size = 3;
mus_event[0] = 0x90 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = mus_data[mus_data_ofs + 1] & 0x7f;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
mus_prev_vol[mus_data[mus_data_ofs] & 0x0f] = mus_event[2];
} else {
mus_event_size = 2;
mus_event[0] = 0x90 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = mus_data[mus_data_ofs + 1];
mus_event[2] = mus_prev_vol[mus_data[mus_data_ofs] & 0x0f];
mus_event[3] = 0;
}
break;
case 2: // Pitch Bend
mus_event_size = 2;
mus_event[0] = 0xe0 | (mus_data[mus_data_ofs] & 0x0f);
pitchbend_tmp = mus_data[mus_data_ofs + 1] << 6;
mus_event[1] = pitchbend_tmp & 0x7f;
mus_event[2] = (pitchbend_tmp >> 7) & 0x7f;
mus_event[3] = 0;
break;
case 3:
mus_event_size = 2;
switch (mus_data[mus_data_ofs + 1]) {
case 10: // All Sounds Off
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 120;
mus_event[2] = 0;
mus_event[3] = 0;
break;
case 11: // All Notes Off
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 123;
mus_event[2] = 0;
mus_event[3] = 0;
break;
case 12: // Mono (Not supported by WildMIDI)
/*
**************************
FIXME: Add dummy mdi event
**************************
*/
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 126;
mus_event[2] = 0;
mus_event[3] = 0;
break;
case 13: // Poly (Not supported by WildMIDI)
/*
**************************
FIXME: Add dummy mdi event
**************************
*/
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 127;
mus_event[2] = 0;
mus_event[3] = 0;
break;
case 14: // Reset All Controllers
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 121;
mus_event[2] = 0;
mus_event[3] = 0;
break;
default: // Unsupported
goto _mus_next_data;
}
break;
case 4:
mus_event_size = 3;
switch (mus_data[mus_data_ofs + 1]) {
case 0: // Patch
/*
*************************************************
FIXME: Check if setting is MIDI or MUS instrument
*************************************************
*/
mus_event[0] = 0xc0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = mus_data[mus_data_ofs + 2];
mus_event[2] = 0;
mus_event[3] = 0;
break;
case 1: // Bank Select
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 0;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
case 2: // Modulation (Not supported by WildMidi)
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 1;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
case 3: // Volume
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 7;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
case 4: // Pan
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 10;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
case 5: // Expression
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 11;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
case 6: // Reverb (Not supported by WildMidi)
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 91;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
case 7: // Chorus (Not supported by WildMidi)
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 93;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
case 8: // Sustain
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 64;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
case 9: // Soft Peddle (Not supported by WildMidi)
mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f);
mus_event[1] = 67;
mus_event[2] = mus_data[mus_data_ofs + 2];
mus_event[3] = 0;
break;
default: // Unsupported
goto _mus_next_data;
}
break;
case 5:
mus_event_size = 1;
goto _mus_next_data;
break;
case 6:
goto _mus_end_of_song;
break;
case 7:
mus_event_size = 1;
goto _mus_next_data;
break;
}
setup_ret = _WM_SetupMidiEvent(mus_mdi, (uint8_t *)mus_event, 0);
if (setup_ret == 0) {
goto _mus_end;
}
_mus_next_data:
if (!(mus_data[mus_data_ofs] & 0x80)) {
mus_data_ofs += mus_event_size;
goto _mus_build_event;
}
mus_data_ofs += mus_event_size;
mus_ticks = 0;
do {
mus_ticks = (mus_ticks << 7) | (mus_data[mus_data_ofs++] & 0x7f);
} while (mus_data[mus_data_ofs - 1] & 0x80);
sample_count_f = ((float)mus_ticks * samples_per_tick_f) + sample_remainder;
sample_count = (uint32_t)sample_count_f;
sample_remainder = sample_count_f - (float)sample_count;
mus_mdi->events[mus_mdi->event_count - 1].samples_to_next = sample_count;
mus_mdi->extra_info.approx_total_samples += sample_count;
} while (mus_data_ofs < mus_size);
_mus_end_of_song:
if ((mus_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0);
goto _mus_end;
}
_WM_midi_setup_endoftrack(mus_mdi);
mus_mdi->extra_info.current_sample = 0;
mus_mdi->current_event = &mus_mdi->events[0];
mus_mdi->samples_to_mix = 0;
mus_mdi->note = NULL;
_WM_ResetToStart(mus_mdi);
_mus_end:
free(mus_mid_instr);
if (mus_mdi->reverb) return (mus_mdi);
_WM_freeMDI(mus_mdi);
return NULL;
}
Commit Message: Add a new size parameter to _WM_SetupMidiEvent() so that it knows
where to stop reading, and adjust its users properly. Fixes bug #175
(CVE-2017-11661, CVE-2017-11662, CVE-2017-11663, CVE-2017-11664.)
CWE ID: CWE-125
Output: | 1 |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 33