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
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: IHEVCD_ERROR_T ihevcd_parse_slice_data(codec_t *ps_codec) { IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; WORD32 end_of_slice_flag; sps_t *ps_sps; pps_t *ps_pps; slice_header_t *ps_slice_hdr; WORD32 end_of_pic; tile_t *ps_tile, *ps_tile_prev; WORD32 i; WORD32 ctb_addr; WORD32 tile_idx; WORD32 cabac_init_idc; WORD32 ctb_size; WORD32 num_ctb_in_row; WORD32 num_min4x4_in_ctb; WORD32 slice_qp; WORD32 slice_start_ctb_idx; WORD32 tile_start_ctb_idx; ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr_base; ps_pps = ps_codec->s_parse.ps_pps_base; ps_sps = ps_codec->s_parse.ps_sps_base; /* Get current slice header, pps and sps */ ps_slice_hdr += (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)); ps_pps += ps_slice_hdr->i1_pps_id; ps_sps += ps_pps->i1_sps_id; if(0 != ps_codec->s_parse.i4_cur_slice_idx) { if(!ps_slice_hdr->i1_dependent_slice_flag) { ps_codec->s_parse.i4_cur_independent_slice_idx = ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1); } } ctb_size = 1 << ps_sps->i1_log2_ctb_size; num_min4x4_in_ctb = (ctb_size / 4) * (ctb_size / 4); num_ctb_in_row = ps_sps->i2_pic_wd_in_ctb; /* Update the parse context */ if(0 == ps_codec->i4_slice_error) { ps_codec->s_parse.i4_ctb_x = ps_slice_hdr->i2_ctb_x; ps_codec->s_parse.i4_ctb_y = ps_slice_hdr->i2_ctb_y; } ps_codec->s_parse.ps_pps = ps_pps; ps_codec->s_parse.ps_sps = ps_sps; ps_codec->s_parse.ps_slice_hdr = ps_slice_hdr; /* Derive Tile positions for the current CTB */ /* Change this to lookup if required */ ihevcd_get_tile_pos(ps_pps, ps_sps, ps_codec->s_parse.i4_ctb_x, ps_codec->s_parse.i4_ctb_y, &ps_codec->s_parse.i4_ctb_tile_x, &ps_codec->s_parse.i4_ctb_tile_y, &tile_idx); ps_codec->s_parse.ps_tile = ps_pps->ps_tile + tile_idx; ps_codec->s_parse.i4_cur_tile_idx = tile_idx; ps_tile = ps_codec->s_parse.ps_tile; if(tile_idx) ps_tile_prev = ps_tile - 1; else ps_tile_prev = ps_tile; /* If the present slice is dependent, then store the previous * independent slices' ctb x and y values for decoding process */ if(0 == ps_codec->i4_slice_error) { if(1 == ps_slice_hdr->i1_dependent_slice_flag) { /*If slice is present at the start of a new tile*/ if((0 == ps_codec->s_parse.i4_ctb_tile_x) && (0 == ps_codec->s_parse.i4_ctb_tile_y)) { ps_codec->s_parse.i4_ctb_slice_x = 0; ps_codec->s_parse.i4_ctb_slice_y = 0; } } if(!ps_slice_hdr->i1_dependent_slice_flag) { ps_codec->s_parse.i4_ctb_slice_x = 0; ps_codec->s_parse.i4_ctb_slice_y = 0; } } /* Frame level initializations */ if((0 == ps_codec->s_parse.i4_ctb_y) && (0 == ps_codec->s_parse.i4_ctb_x)) { ret = ihevcd_parse_pic_init(ps_codec); RETURN_IF((ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS), ret); ps_codec->s_parse.pu4_pic_tu_idx[0] = 0; ps_codec->s_parse.pu4_pic_pu_idx[0] = 0; ps_codec->s_parse.i4_cur_independent_slice_idx = 0; ps_codec->s_parse.i4_ctb_tile_x = 0; ps_codec->s_parse.i4_ctb_tile_y = 0; } { /* Updating the poc list of current slice to ps_mv_buf */ mv_buf_t *ps_mv_buf = ps_codec->s_parse.ps_cur_mv_buf; if(ps_slice_hdr->i1_num_ref_idx_l1_active != 0) { for(i = 0; i < ps_slice_hdr->i1_num_ref_idx_l1_active; i++) { ps_mv_buf->ai4_l1_collocated_poc[(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))][i] = ((pic_buf_t *)ps_slice_hdr->as_ref_pic_list1[i].pv_pic_buf)->i4_abs_poc; ps_mv_buf->ai1_l1_collocated_poc_lt[(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))][i] = ((pic_buf_t *)ps_slice_hdr->as_ref_pic_list1[i].pv_pic_buf)->u1_used_as_ref; } } if(ps_slice_hdr->i1_num_ref_idx_l0_active != 0) { for(i = 0; i < ps_slice_hdr->i1_num_ref_idx_l0_active; i++) { ps_mv_buf->ai4_l0_collocated_poc[(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))][i] = ((pic_buf_t *)ps_slice_hdr->as_ref_pic_list0[i].pv_pic_buf)->i4_abs_poc; ps_mv_buf->ai1_l0_collocated_poc_lt[(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))][i] = ((pic_buf_t *)ps_slice_hdr->as_ref_pic_list0[i].pv_pic_buf)->u1_used_as_ref; } } } /*Initialize the low delay flag at the beginning of every slice*/ if((0 == ps_codec->s_parse.i4_ctb_slice_x) || (0 == ps_codec->s_parse.i4_ctb_slice_y)) { /* Lowdelay flag */ WORD32 cur_poc, ref_list_poc, flag = 1; cur_poc = ps_slice_hdr->i4_abs_pic_order_cnt; for(i = 0; i < ps_slice_hdr->i1_num_ref_idx_l0_active; i++) { ref_list_poc = ((mv_buf_t *)ps_slice_hdr->as_ref_pic_list0[i].pv_mv_buf)->i4_abs_poc; if(ref_list_poc > cur_poc) { flag = 0; break; } } if(flag && (ps_slice_hdr->i1_slice_type == BSLICE)) { for(i = 0; i < ps_slice_hdr->i1_num_ref_idx_l1_active; i++) { ref_list_poc = ((mv_buf_t *)ps_slice_hdr->as_ref_pic_list1[i].pv_mv_buf)->i4_abs_poc; if(ref_list_poc > cur_poc) { flag = 0; break; } } } ps_slice_hdr->i1_low_delay_flag = flag; } /* initialize the cabac init idc based on slice type */ if(ps_slice_hdr->i1_slice_type == ISLICE) { cabac_init_idc = 0; } else if(ps_slice_hdr->i1_slice_type == PSLICE) { cabac_init_idc = ps_slice_hdr->i1_cabac_init_flag ? 2 : 1; } else { cabac_init_idc = ps_slice_hdr->i1_cabac_init_flag ? 1 : 2; } slice_qp = ps_slice_hdr->i1_slice_qp_delta + ps_pps->i1_pic_init_qp; slice_qp = CLIP3(slice_qp, 0, 51); /*Update QP value for every indepndent slice or for every dependent slice that begins at the start of a new tile*/ if((0 == ps_slice_hdr->i1_dependent_slice_flag) || ((1 == ps_slice_hdr->i1_dependent_slice_flag) && ((0 == ps_codec->s_parse.i4_ctb_tile_x) && (0 == ps_codec->s_parse.i4_ctb_tile_y)))) { ps_codec->s_parse.u4_qp = slice_qp; } /*Cabac init at the beginning of a slice*/ if((1 == ps_slice_hdr->i1_dependent_slice_flag) && (!((ps_codec->s_parse.i4_ctb_tile_x == 0) && (ps_codec->s_parse.i4_ctb_tile_y == 0)))) { if((0 == ps_pps->i1_entropy_coding_sync_enabled_flag) || (ps_pps->i1_entropy_coding_sync_enabled_flag && (0 != ps_codec->s_parse.i4_ctb_x))) { ihevcd_cabac_reset(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm); } } else if((0 == ps_pps->i1_entropy_coding_sync_enabled_flag) || (ps_pps->i1_entropy_coding_sync_enabled_flag && (0 != ps_codec->s_parse.i4_ctb_x))) { ihevcd_cabac_init(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm, slice_qp, cabac_init_idc, &gau1_ihevc_cab_ctxts[cabac_init_idc][slice_qp][0]); } do { { WORD32 cur_ctb_idx = ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * (ps_sps->i2_pic_wd_in_ctb); if(1 == ps_codec->i4_num_cores && 0 == cur_ctb_idx % RESET_TU_BUF_NCTB) { ps_codec->s_parse.ps_tu = ps_codec->s_parse.ps_pic_tu; ps_codec->s_parse.i4_pic_tu_idx = 0; } } end_of_pic = 0; /* Section:7.3.7 Coding tree unit syntax */ /* coding_tree_unit() inlined here */ /* If number of cores is greater than 1, then add job to the queue */ /* At the start of ctb row parsing in a tile, queue a job for processing the current tile row */ ps_codec->s_parse.i4_ctb_num_pcm_blks = 0; /*At the beginning of each tile-which is not the beginning of a slice, cabac context must be initialized. * Hence, check for the tile beginning here */ if(((0 == ps_codec->s_parse.i4_ctb_tile_x) && (0 == ps_codec->s_parse.i4_ctb_tile_y)) && (!((ps_tile->u1_pos_x == 0) && (ps_tile->u1_pos_y == 0))) && (!((0 == ps_codec->s_parse.i4_ctb_slice_x) && (0 == ps_codec->s_parse.i4_ctb_slice_y)))) { slice_qp = ps_slice_hdr->i1_slice_qp_delta + ps_pps->i1_pic_init_qp; slice_qp = CLIP3(slice_qp, 0, 51); ps_codec->s_parse.u4_qp = slice_qp; ihevcd_get_tile_pos(ps_pps, ps_sps, ps_codec->s_parse.i4_ctb_x, ps_codec->s_parse.i4_ctb_y, &ps_codec->s_parse.i4_ctb_tile_x, &ps_codec->s_parse.i4_ctb_tile_y, &tile_idx); ps_codec->s_parse.ps_tile = ps_pps->ps_tile + tile_idx; ps_codec->s_parse.i4_cur_tile_idx = tile_idx; ps_tile_prev = ps_tile - 1; tile_start_ctb_idx = ps_tile->u1_pos_x + ps_tile->u1_pos_y * (ps_sps->i2_pic_wd_in_ctb); slice_start_ctb_idx = ps_slice_hdr->i2_ctb_x + ps_slice_hdr->i2_ctb_y * (ps_sps->i2_pic_wd_in_ctb); /*For slices that span across multiple tiles*/ if(slice_start_ctb_idx < tile_start_ctb_idx) { /* 2 Cases * 1 - slice spans across frame-width- but does not start from 1st column * 2 - Slice spans across multiple tiles anywhere is a frame */ ps_codec->s_parse.i4_ctb_slice_y = ps_tile->u1_pos_y - ps_slice_hdr->i2_ctb_y; if(!(((ps_slice_hdr->i2_ctb_x + ps_tile_prev->u2_wd) % ps_sps->i2_pic_wd_in_ctb) == ps_tile->u1_pos_x)) //Case 2 { if(ps_slice_hdr->i2_ctb_y <= ps_tile->u1_pos_y) { if(ps_slice_hdr->i2_ctb_x > ps_tile->u1_pos_x) { ps_codec->s_parse.i4_ctb_slice_y -= 1; } } } /*ps_codec->s_parse.i4_ctb_slice_y = ps_tile->u1_pos_y - ps_slice_hdr->i2_ctb_y; if (ps_slice_hdr->i2_ctb_y <= ps_tile->u1_pos_y) { if (ps_slice_hdr->i2_ctb_x > ps_tile->u1_pos_x ) { ps_codec->s_parse.i4_ctb_slice_y -= 1 ; } }*/ } /* Cabac init is done unconditionally at the start of the tile irrespective * of whether it is a dependent or an independent slice */ { ihevcd_cabac_init(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm, slice_qp, cabac_init_idc, &gau1_ihevc_cab_ctxts[cabac_init_idc][slice_qp][0]); } } /* If number of cores is greater than 1, then add job to the queue */ /* At the start of ctb row parsing in a tile, queue a job for processing the current tile row */ if(0 == ps_codec->s_parse.i4_ctb_tile_x) { if(1 < ps_codec->i4_num_cores) { proc_job_t s_job; IHEVCD_ERROR_T ret; s_job.i4_cmd = CMD_PROCESS; s_job.i2_ctb_cnt = (WORD16)ps_tile->u2_wd; s_job.i2_ctb_x = (WORD16)ps_codec->s_parse.i4_ctb_x; s_job.i2_ctb_y = (WORD16)ps_codec->s_parse.i4_ctb_y; s_job.i2_slice_idx = (WORD16)ps_codec->s_parse.i4_cur_slice_idx; s_job.i4_tu_coeff_data_ofst = (UWORD8 *)ps_codec->s_parse.pv_tu_coeff_data - (UWORD8 *)ps_codec->s_parse.pv_pic_tu_coeff_data; ret = ihevcd_jobq_queue((jobq_t *)ps_codec->s_parse.pv_proc_jobq, &s_job, sizeof(proc_job_t), 1); if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS) return ret; } else { process_ctxt_t *ps_proc = &ps_codec->as_process[0]; WORD32 tu_coeff_data_ofst = (UWORD8 *)ps_codec->s_parse.pv_tu_coeff_data - (UWORD8 *)ps_codec->s_parse.pv_pic_tu_coeff_data; /* If the codec is running in single core mode, * initialize zeroth process context * TODO: Dual core mode might need a different implementation instead of jobq */ ps_proc->i4_ctb_cnt = ps_tile->u2_wd; ps_proc->i4_ctb_x = ps_codec->s_parse.i4_ctb_x; ps_proc->i4_ctb_y = ps_codec->s_parse.i4_ctb_y; ps_proc->i4_cur_slice_idx = ps_codec->s_parse.i4_cur_slice_idx; ihevcd_init_proc_ctxt(ps_proc, tu_coeff_data_ofst); } } /* Restore cabac context model from top right CTB if entropy sync is enabled */ if(ps_pps->i1_entropy_coding_sync_enabled_flag) { /*TODO Handle single CTB and top-right belonging to a different slice */ if(0 == ps_codec->s_parse.i4_ctb_x) { WORD32 default_ctxt = 0; if((0 == ps_codec->s_parse.i4_ctb_slice_y) && (!ps_slice_hdr->i1_dependent_slice_flag)) default_ctxt = 1; if(1 == ps_sps->i2_pic_wd_in_ctb) default_ctxt = 1; ps_codec->s_parse.u4_qp = slice_qp; if(default_ctxt) { ihevcd_cabac_init(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm, slice_qp, cabac_init_idc, &gau1_ihevc_cab_ctxts[cabac_init_idc][slice_qp][0]); } else { ihevcd_cabac_init(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm, slice_qp, cabac_init_idc, (const UWORD8 *)&ps_codec->s_parse.s_cabac.au1_ctxt_models_sync); } } } if(0 == ps_codec->i4_slice_error) { if(ps_slice_hdr->i1_slice_sao_luma_flag || ps_slice_hdr->i1_slice_sao_chroma_flag) ihevcd_parse_sao(ps_codec); } else { sao_t *ps_sao = ps_codec->s_parse.ps_pic_sao + ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * ps_sps->i2_pic_wd_in_ctb; /* Default values */ ps_sao->b3_y_type_idx = 0; ps_sao->b3_cb_type_idx = 0; ps_sao->b3_cr_type_idx = 0; } { WORD32 ctb_indx; ctb_indx = ps_codec->s_parse.i4_ctb_x + ps_sps->i2_pic_wd_in_ctb * ps_codec->s_parse.i4_ctb_y; ps_codec->s_parse.s_bs_ctxt.pu1_pic_qp_const_in_ctb[ctb_indx >> 3] |= (1 << (ctb_indx & 7)); { UWORD16 *pu1_slice_idx = ps_codec->s_parse.pu1_slice_idx; pu1_slice_idx[ctb_indx] = ps_codec->s_parse.i4_cur_independent_slice_idx; } } if(0 == ps_codec->i4_slice_error) { ihevcd_parse_coding_quadtree(ps_codec, (ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size), (ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size), ps_sps->i1_log2_ctb_size, 0); } else { tu_t *ps_tu = ps_codec->s_parse.ps_tu; pu_t *ps_pu = ps_codec->s_parse.ps_pu; ps_tu->b1_cb_cbf = 0; ps_tu->b1_cr_cbf = 0; ps_tu->b1_y_cbf = 0; ps_tu->b4_pos_x = 0; ps_tu->b4_pos_y = 0; ps_tu->b1_transquant_bypass = 0; ps_tu->b3_size = (ps_sps->i1_log2_ctb_size - 2); ps_tu->b7_qp = ps_codec->s_parse.u4_qp; ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE; ps_tu->b6_luma_intra_mode = INTRA_PRED_NONE; ps_tu->b1_first_tu_in_cu = 1; ps_codec->s_parse.ps_tu++; ps_codec->s_parse.s_cu.i4_tu_cnt++; ps_codec->s_parse.i4_pic_tu_idx++; ps_codec->s_parse.s_cu.i4_pred_mode = PRED_MODE_SKIP; ps_codec->s_parse.s_cu.i4_part_mode = PART_2Nx2N; ps_pu->b2_part_idx = 0; ps_pu->b4_pos_x = 0; ps_pu->b4_pos_y = 0; ps_pu->b4_wd = (ctb_size >> 2) - 1; ps_pu->b4_ht = (ctb_size >> 2) - 1; ps_pu->b1_intra_flag = 0; ps_pu->b3_part_mode = ps_codec->s_parse.s_cu.i4_part_mode; ps_pu->b1_merge_flag = 1; ps_pu->b3_merge_idx = 0; ps_codec->s_parse.ps_pu++; ps_codec->s_parse.i4_pic_pu_idx++; } if(0 == ps_codec->i4_slice_error) end_of_slice_flag = ihevcd_cabac_decode_terminate(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm); else end_of_slice_flag = 0; AEV_TRACE("end_of_slice_flag", end_of_slice_flag, ps_codec->s_parse.s_cabac.u4_range); /* In case of tiles or entropy sync, terminate cabac and copy cabac context backed up at the end of top-right CTB */ if(ps_pps->i1_tiles_enabled_flag || ps_pps->i1_entropy_coding_sync_enabled_flag) { WORD32 end_of_tile = 0; WORD32 end_of_tile_row = 0; /* Take a back up of cabac context models if entropy sync is enabled */ if(ps_pps->i1_entropy_coding_sync_enabled_flag || ps_pps->i1_tiles_enabled_flag) { if(1 == ps_codec->s_parse.i4_ctb_x) { WORD32 size = sizeof(ps_codec->s_parse.s_cabac.au1_ctxt_models); memcpy(&ps_codec->s_parse.s_cabac.au1_ctxt_models_sync, &ps_codec->s_parse.s_cabac.au1_ctxt_models, size); } } /* Since tiles and entropy sync are not enabled simultaneously, the following will not result in any problems */ if((ps_codec->s_parse.i4_ctb_tile_x + 1) == (ps_tile->u2_wd)) { end_of_tile_row = 1; if((ps_codec->s_parse.i4_ctb_tile_y + 1) == ps_tile->u2_ht) end_of_tile = 1; } if((0 == end_of_slice_flag) && ((ps_pps->i1_tiles_enabled_flag && end_of_tile) || (ps_pps->i1_entropy_coding_sync_enabled_flag && end_of_tile_row))) { WORD32 end_of_sub_stream_one_bit; end_of_sub_stream_one_bit = ihevcd_cabac_decode_terminate(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm); AEV_TRACE("end_of_sub_stream_one_bit", end_of_sub_stream_one_bit, ps_codec->s_parse.s_cabac.u4_range); /* TODO: Remove the check for offset when HM is updated to include a byte unconditionally even for aligned location */ /* For Ittiam streams this check should not be there, for HM9.1 streams this should be there */ if(ps_codec->s_parse.s_bitstrm.u4_bit_ofst % 8) ihevcd_bits_flush_to_byte_boundary(&ps_codec->s_parse.s_bitstrm); UNUSED(end_of_sub_stream_one_bit); } } { WORD32 ctb_indx; ctb_addr = ps_codec->s_parse.i4_ctb_y * num_ctb_in_row + ps_codec->s_parse.i4_ctb_x; ctb_indx = ++ctb_addr; /* Store pu_idx for next CTB in frame level pu_idx array */ if((ps_tile->u2_wd == (ps_codec->s_parse.i4_ctb_tile_x + 1)) && (ps_tile->u2_wd != ps_sps->i2_pic_wd_in_ctb)) { ctb_indx = (ps_sps->i2_pic_wd_in_ctb * (ps_codec->s_parse.i4_ctb_tile_y + 1 + ps_tile->u1_pos_y)) + ps_tile->u1_pos_x; //idx is the beginning of next row in current tile. if(ps_tile->u2_ht == (ps_codec->s_parse.i4_ctb_tile_y + 1)) { if((ps_tile->u2_wd + ps_tile->u1_pos_x == ps_sps->i2_pic_wd_in_ctb) && ((ps_tile->u2_ht + ps_tile->u1_pos_y == ps_sps->i2_pic_ht_in_ctb))) { ctb_indx = ctb_addr; //Next continuous ctb address } else //Not last tile's end , but a tile end { tile_t *ps_next_tile = ps_codec->s_parse.ps_tile + 1; ctb_indx = ps_next_tile->u1_pos_x + (ps_next_tile->u1_pos_y * ps_sps->i2_pic_wd_in_ctb); //idx is the beginning of first row in next tile. } } } ps_codec->s_parse.pu4_pic_pu_idx[ctb_indx] = ps_codec->s_parse.i4_pic_pu_idx; ps_codec->s_parse.i4_next_pu_ctb_cnt = ctb_indx; ps_codec->s_parse.pu1_pu_map += num_min4x4_in_ctb; /* Store tu_idx for next CTB in frame level tu_idx array */ if(1 == ps_codec->i4_num_cores) { ctb_indx = (0 == ctb_addr % RESET_TU_BUF_NCTB) ? RESET_TU_BUF_NCTB : ctb_addr % RESET_TU_BUF_NCTB; if((ps_tile->u2_wd == (ps_codec->s_parse.i4_ctb_tile_x + 1)) && (ps_tile->u2_wd != ps_sps->i2_pic_wd_in_ctb)) { ctb_indx = (ps_sps->i2_pic_wd_in_ctb * (ps_codec->s_parse.i4_ctb_tile_y + 1 + ps_tile->u1_pos_y)) + ps_tile->u1_pos_x; //idx is the beginning of next row in current tile. if(ps_tile->u2_ht == (ps_codec->s_parse.i4_ctb_tile_y + 1)) { if((ps_tile->u2_wd + ps_tile->u1_pos_x == ps_sps->i2_pic_wd_in_ctb) && ((ps_tile->u2_ht + ps_tile->u1_pos_y == ps_sps->i2_pic_ht_in_ctb))) { ctb_indx = (0 == ctb_addr % RESET_TU_BUF_NCTB) ? RESET_TU_BUF_NCTB : ctb_addr % RESET_TU_BUF_NCTB; } else //Not last tile's end , but a tile end { tile_t *ps_next_tile = ps_codec->s_parse.ps_tile + 1; ctb_indx = ps_next_tile->u1_pos_x + (ps_next_tile->u1_pos_y * ps_sps->i2_pic_wd_in_ctb); //idx is the beginning of first row in next tile. } } } ps_codec->s_parse.i4_next_tu_ctb_cnt = ctb_indx; ps_codec->s_parse.pu4_pic_tu_idx[ctb_indx] = ps_codec->s_parse.i4_pic_tu_idx; } else { ctb_indx = ctb_addr; if((ps_tile->u2_wd == (ps_codec->s_parse.i4_ctb_tile_x + 1)) && (ps_tile->u2_wd != ps_sps->i2_pic_wd_in_ctb)) { ctb_indx = (ps_sps->i2_pic_wd_in_ctb * (ps_codec->s_parse.i4_ctb_tile_y + 1 + ps_tile->u1_pos_y)) + ps_tile->u1_pos_x; //idx is the beginning of next row in current tile. if(ps_tile->u2_ht == (ps_codec->s_parse.i4_ctb_tile_y + 1)) { if((ps_tile->u2_wd + ps_tile->u1_pos_x == ps_sps->i2_pic_wd_in_ctb) && ((ps_tile->u2_ht + ps_tile->u1_pos_y == ps_sps->i2_pic_ht_in_ctb))) { ctb_indx = ctb_addr; } else //Not last tile's end , but a tile end { tile_t *ps_next_tile = ps_codec->s_parse.ps_tile + 1; ctb_indx = ps_next_tile->u1_pos_x + (ps_next_tile->u1_pos_y * ps_sps->i2_pic_wd_in_ctb); //idx is the beginning of first row in next tile. } } } ps_codec->s_parse.i4_next_tu_ctb_cnt = ctb_indx; ps_codec->s_parse.pu4_pic_tu_idx[ctb_indx] = ps_codec->s_parse.i4_pic_tu_idx; } ps_codec->s_parse.pu1_tu_map += num_min4x4_in_ctb; } /* QP array population has to be done if deblocking is enabled in the picture * but some of the slices in the pic have it disabled */ if((0 != ps_codec->i4_disable_deblk_pic) && (1 == ps_slice_hdr->i1_slice_disable_deblocking_filter_flag)) { bs_ctxt_t *ps_bs_ctxt = &ps_codec->s_parse.s_bs_ctxt; WORD32 log2_ctb_size = ps_sps->i1_log2_ctb_size; UWORD8 *pu1_qp; WORD32 qp_strd; WORD32 u4_qp_const_in_ctb; WORD32 cur_ctb_idx; WORD32 next_ctb_idx; WORD32 cur_tu_idx; WORD32 i4_ctb_tu_cnt; tu_t *ps_tu; cur_ctb_idx = ps_codec->s_parse.i4_ctb_x + ps_sps->i2_pic_wd_in_ctb * ps_codec->s_parse.i4_ctb_y; /* ctb_size/8 elements per CTB */ qp_strd = ps_sps->i2_pic_wd_in_ctb << (log2_ctb_size - 3); pu1_qp = ps_bs_ctxt->pu1_pic_qp + ((ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * qp_strd) << (log2_ctb_size - 3)); u4_qp_const_in_ctb = ps_bs_ctxt->pu1_pic_qp_const_in_ctb[cur_ctb_idx >> 3] & (1 << (cur_ctb_idx & 7)); next_ctb_idx = ps_codec->s_parse.i4_next_tu_ctb_cnt; if(1 == ps_codec->i4_num_cores) { i4_ctb_tu_cnt = ps_codec->s_parse.pu4_pic_tu_idx[next_ctb_idx] - ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx % RESET_TU_BUF_NCTB]; cur_tu_idx = ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx % RESET_TU_BUF_NCTB]; } else { i4_ctb_tu_cnt = ps_codec->s_parse.pu4_pic_tu_idx[next_ctb_idx] - ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx]; cur_tu_idx = ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx]; } ps_tu = &ps_codec->s_parse.ps_pic_tu[cur_tu_idx]; if(u4_qp_const_in_ctb) { pu1_qp[0] = ps_tu->b7_qp; } else { for(i = 0; i < i4_ctb_tu_cnt; i++, ps_tu++) { WORD32 start_pos_x; WORD32 start_pos_y; WORD32 tu_size; /* start_pos_x and start_pos_y are in units of min TU size (4x4) */ start_pos_x = ps_tu->b4_pos_x; start_pos_y = ps_tu->b4_pos_y; tu_size = 1 << (ps_tu->b3_size + 2); tu_size >>= 2; /* TU size divided by 4 */ if(0 == (start_pos_x & 1) && 0 == (start_pos_y & 1)) { WORD32 row, col; for(row = start_pos_y; row < start_pos_y + tu_size; row += 2) { for(col = start_pos_x; col < start_pos_x + tu_size; col += 2) { pu1_qp[(row >> 1) * qp_strd + (col >> 1)] = ps_tu->b7_qp; } } } } } } if(ps_codec->i4_num_cores <= MV_PRED_NUM_CORES_THRESHOLD) { /*************************************************/ /**************** MV pred **********************/ /*************************************************/ WORD8 u1_top_ctb_avail = 1; WORD8 u1_left_ctb_avail = 1; WORD8 u1_top_lt_ctb_avail = 1; WORD8 u1_top_rt_ctb_avail = 1; WORD16 i2_wd_in_ctb; tile_start_ctb_idx = ps_tile->u1_pos_x + ps_tile->u1_pos_y * (ps_sps->i2_pic_wd_in_ctb); slice_start_ctb_idx = ps_slice_hdr->i2_ctb_x + ps_slice_hdr->i2_ctb_y * (ps_sps->i2_pic_wd_in_ctb); if((slice_start_ctb_idx < tile_start_ctb_idx)) { i2_wd_in_ctb = ps_sps->i2_pic_wd_in_ctb; } else { i2_wd_in_ctb = ps_tile->u2_wd; } /* slice and tile boundaries */ if((0 == ps_codec->s_parse.i4_ctb_y) || (0 == ps_codec->s_parse.i4_ctb_tile_y)) { u1_top_ctb_avail = 0; u1_top_lt_ctb_avail = 0; u1_top_rt_ctb_avail = 0; } if((0 == ps_codec->s_parse.i4_ctb_x) || (0 == ps_codec->s_parse.i4_ctb_tile_x)) { u1_left_ctb_avail = 0; u1_top_lt_ctb_avail = 0; if((0 == ps_codec->s_parse.i4_ctb_slice_y) || (0 == ps_codec->s_parse.i4_ctb_tile_y)) { u1_top_ctb_avail = 0; if((i2_wd_in_ctb - 1) != ps_codec->s_parse.i4_ctb_slice_x) //TODO: For tile, not implemented { u1_top_rt_ctb_avail = 0; } } } /*For slices not beginning at start of a ctb row*/ else if(ps_codec->s_parse.i4_ctb_x > 0) { if((0 == ps_codec->s_parse.i4_ctb_slice_y) || (0 == ps_codec->s_parse.i4_ctb_tile_y)) { u1_top_ctb_avail = 0; u1_top_lt_ctb_avail = 0; if(0 == ps_codec->s_parse.i4_ctb_slice_x) { u1_left_ctb_avail = 0; } if((i2_wd_in_ctb - 1) != ps_codec->s_parse.i4_ctb_slice_x) { u1_top_rt_ctb_avail = 0; } } else if((1 == ps_codec->s_parse.i4_ctb_slice_y) && (0 == ps_codec->s_parse.i4_ctb_slice_x)) { u1_top_lt_ctb_avail = 0; } } if(((ps_sps->i2_pic_wd_in_ctb - 1) == ps_codec->s_parse.i4_ctb_x) || ((ps_tile->u2_wd - 1) == ps_codec->s_parse.i4_ctb_tile_x)) { u1_top_rt_ctb_avail = 0; } if(PSLICE == ps_slice_hdr->i1_slice_type || BSLICE == ps_slice_hdr->i1_slice_type) { mv_ctxt_t s_mv_ctxt; process_ctxt_t *ps_proc; UWORD32 *pu4_ctb_top_pu_idx; UWORD32 *pu4_ctb_left_pu_idx; UWORD32 *pu4_ctb_top_left_pu_idx; WORD32 i4_ctb_pu_cnt; WORD32 cur_ctb_idx; WORD32 next_ctb_idx; WORD32 cur_pu_idx; ps_proc = &ps_codec->as_process[(ps_codec->i4_num_cores == 1) ? 1 : (ps_codec->i4_num_cores - 1)]; cur_ctb_idx = ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * (ps_sps->i2_pic_wd_in_ctb); next_ctb_idx = ps_codec->s_parse.i4_next_pu_ctb_cnt; i4_ctb_pu_cnt = ps_codec->s_parse.pu4_pic_pu_idx[next_ctb_idx] - ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx]; cur_pu_idx = ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx]; pu4_ctb_top_pu_idx = ps_proc->pu4_pic_pu_idx_top + (ps_codec->s_parse.i4_ctb_x * ctb_size / MIN_PU_SIZE); pu4_ctb_left_pu_idx = ps_proc->pu4_pic_pu_idx_left; pu4_ctb_top_left_pu_idx = &ps_proc->u4_ctb_top_left_pu_idx; /* Initializing s_mv_ctxt */ { s_mv_ctxt.ps_pps = ps_pps; s_mv_ctxt.ps_sps = ps_sps; s_mv_ctxt.ps_slice_hdr = ps_slice_hdr; s_mv_ctxt.i4_ctb_x = ps_codec->s_parse.i4_ctb_x; s_mv_ctxt.i4_ctb_y = ps_codec->s_parse.i4_ctb_y; s_mv_ctxt.ps_pu = &ps_codec->s_parse.ps_pic_pu[cur_pu_idx]; s_mv_ctxt.ps_pic_pu = ps_codec->s_parse.ps_pic_pu; s_mv_ctxt.ps_tile = ps_tile; s_mv_ctxt.pu4_pic_pu_idx_map = ps_proc->pu4_pic_pu_idx_map; s_mv_ctxt.pu4_pic_pu_idx = ps_codec->s_parse.pu4_pic_pu_idx; s_mv_ctxt.pu1_pic_pu_map = ps_codec->s_parse.pu1_pic_pu_map; s_mv_ctxt.i4_ctb_pu_cnt = i4_ctb_pu_cnt; s_mv_ctxt.i4_ctb_start_pu_idx = cur_pu_idx; s_mv_ctxt.u1_top_ctb_avail = u1_top_ctb_avail; s_mv_ctxt.u1_top_rt_ctb_avail = u1_top_rt_ctb_avail; s_mv_ctxt.u1_top_lt_ctb_avail = u1_top_lt_ctb_avail; s_mv_ctxt.u1_left_ctb_avail = u1_left_ctb_avail; } ihevcd_get_mv_ctb(&s_mv_ctxt, pu4_ctb_top_pu_idx, pu4_ctb_left_pu_idx, pu4_ctb_top_left_pu_idx); } else { WORD32 num_minpu_in_ctb = (ctb_size / MIN_PU_SIZE) * (ctb_size / MIN_PU_SIZE); UWORD8 *pu1_pic_pu_map_ctb = ps_codec->s_parse.pu1_pic_pu_map + (ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * ps_sps->i2_pic_wd_in_ctb) * num_minpu_in_ctb; process_ctxt_t *ps_proc = &ps_codec->as_process[(ps_codec->i4_num_cores == 1) ? 1 : (ps_codec->i4_num_cores - 1)]; WORD32 row, col; WORD32 pu_cnt; WORD32 num_pu_per_ctb; WORD32 cur_ctb_idx; WORD32 next_ctb_idx; WORD32 ctb_start_pu_idx; UWORD32 *pu4_nbr_pu_idx = ps_proc->pu4_pic_pu_idx_map; WORD32 nbr_pu_idx_strd = MAX_CTB_SIZE / MIN_PU_SIZE + 2; pu_t *ps_pu; for(row = 0; row < ctb_size / MIN_PU_SIZE; row++) { for(col = 0; col < ctb_size / MIN_PU_SIZE; col++) { pu1_pic_pu_map_ctb[row * ctb_size / MIN_PU_SIZE + col] = 0; } } /* Neighbor PU idx update inside CTB */ /* 1byte per 4x4. Indicates the PU idx that 4x4 block belongs to */ cur_ctb_idx = ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * (ps_sps->i2_pic_wd_in_ctb); next_ctb_idx = ps_codec->s_parse.i4_next_pu_ctb_cnt; num_pu_per_ctb = ps_codec->s_parse.pu4_pic_pu_idx[next_ctb_idx] - ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx]; ctb_start_pu_idx = ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx]; ps_pu = &ps_codec->s_parse.ps_pic_pu[ctb_start_pu_idx]; for(pu_cnt = 0; pu_cnt < num_pu_per_ctb; pu_cnt++, ps_pu++) { UWORD32 cur_pu_idx; WORD32 pu_ht = (ps_pu->b4_ht + 1) << 2; WORD32 pu_wd = (ps_pu->b4_wd + 1) << 2; cur_pu_idx = ctb_start_pu_idx + pu_cnt; for(row = 0; row < pu_ht / MIN_PU_SIZE; row++) for(col = 0; col < pu_wd / MIN_PU_SIZE; col++) pu4_nbr_pu_idx[(1 + ps_pu->b4_pos_x + col) + (1 + ps_pu->b4_pos_y + row) * nbr_pu_idx_strd] = cur_pu_idx; } /* Updating Top and Left pointers */ { WORD32 rows_remaining = ps_sps->i2_pic_height_in_luma_samples - (ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size); WORD32 ctb_size_left = MIN(ctb_size, rows_remaining); /* Top Left */ /* saving top left before updating top ptr, as updating top ptr will overwrite the top left for the next ctb */ ps_proc->u4_ctb_top_left_pu_idx = ps_proc->pu4_pic_pu_idx_top[(ps_codec->s_parse.i4_ctb_x * ctb_size / MIN_PU_SIZE) + ctb_size / MIN_PU_SIZE - 1]; for(i = 0; i < ctb_size / MIN_PU_SIZE; i++) { /* Left */ /* Last column of au4_nbr_pu_idx */ ps_proc->pu4_pic_pu_idx_left[i] = pu4_nbr_pu_idx[(ctb_size / MIN_PU_SIZE) + (i + 1) * nbr_pu_idx_strd]; /* Top */ /* Last row of au4_nbr_pu_idx */ ps_proc->pu4_pic_pu_idx_top[(ps_codec->s_parse.i4_ctb_x * ctb_size / MIN_PU_SIZE) + i] = pu4_nbr_pu_idx[(ctb_size_left / MIN_PU_SIZE) * nbr_pu_idx_strd + i + 1]; } } } /*************************************************/ /****************** BS, QP *********************/ /*************************************************/ /* Check if deblock is disabled for the current slice or if it is disabled for the current picture * because of disable deblock api */ if(0 == ps_codec->i4_disable_deblk_pic) { /* Boundary strength calculation is done irrespective of whether deblocking is disabled * in the slice or not, to handle deblocking slice boundaries */ if((0 == ps_codec->i4_slice_error)) { WORD32 i4_ctb_tu_cnt; WORD32 cur_ctb_idx, next_ctb_idx; WORD32 cur_pu_idx; WORD32 cur_tu_idx; process_ctxt_t *ps_proc; ps_proc = &ps_codec->as_process[(ps_codec->i4_num_cores == 1) ? 1 : (ps_codec->i4_num_cores - 1)]; cur_ctb_idx = ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * (ps_sps->i2_pic_wd_in_ctb); cur_pu_idx = ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx]; next_ctb_idx = ps_codec->s_parse.i4_next_tu_ctb_cnt; if(1 == ps_codec->i4_num_cores) { i4_ctb_tu_cnt = ps_codec->s_parse.pu4_pic_tu_idx[next_ctb_idx] - ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx % RESET_TU_BUF_NCTB]; cur_tu_idx = ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx % RESET_TU_BUF_NCTB]; } else { i4_ctb_tu_cnt = ps_codec->s_parse.pu4_pic_tu_idx[next_ctb_idx] - ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx]; cur_tu_idx = ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx]; } ps_codec->s_parse.s_bs_ctxt.ps_pps = ps_codec->s_parse.ps_pps; ps_codec->s_parse.s_bs_ctxt.ps_sps = ps_codec->s_parse.ps_sps; ps_codec->s_parse.s_bs_ctxt.ps_codec = ps_codec; ps_codec->s_parse.s_bs_ctxt.i4_ctb_tu_cnt = i4_ctb_tu_cnt; ps_codec->s_parse.s_bs_ctxt.i4_ctb_x = ps_codec->s_parse.i4_ctb_x; ps_codec->s_parse.s_bs_ctxt.i4_ctb_y = ps_codec->s_parse.i4_ctb_y; ps_codec->s_parse.s_bs_ctxt.i4_ctb_tile_x = ps_codec->s_parse.i4_ctb_tile_x; ps_codec->s_parse.s_bs_ctxt.i4_ctb_tile_y = ps_codec->s_parse.i4_ctb_tile_y; ps_codec->s_parse.s_bs_ctxt.i4_ctb_slice_x = ps_codec->s_parse.i4_ctb_slice_x; ps_codec->s_parse.s_bs_ctxt.i4_ctb_slice_y = ps_codec->s_parse.i4_ctb_slice_y; ps_codec->s_parse.s_bs_ctxt.ps_tu = &ps_codec->s_parse.ps_pic_tu[cur_tu_idx]; ps_codec->s_parse.s_bs_ctxt.ps_pu = &ps_codec->s_parse.ps_pic_pu[cur_pu_idx]; ps_codec->s_parse.s_bs_ctxt.pu4_pic_pu_idx_map = ps_proc->pu4_pic_pu_idx_map; ps_codec->s_parse.s_bs_ctxt.i4_next_pu_ctb_cnt = ps_codec->s_parse.i4_next_pu_ctb_cnt; ps_codec->s_parse.s_bs_ctxt.i4_next_tu_ctb_cnt = ps_codec->s_parse.i4_next_tu_ctb_cnt; ps_codec->s_parse.s_bs_ctxt.pu1_slice_idx = ps_codec->s_parse.pu1_slice_idx; ps_codec->s_parse.s_bs_ctxt.ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr; ps_codec->s_parse.s_bs_ctxt.ps_tile = ps_codec->s_parse.ps_tile; if(ISLICE == ps_slice_hdr->i1_slice_type) { ihevcd_ctb_boundary_strength_islice(&ps_codec->s_parse.s_bs_ctxt); } else { ihevcd_ctb_boundary_strength_pbslice(&ps_codec->s_parse.s_bs_ctxt); } } /* Boundary strength is set to zero if deblocking is disabled for the current slice */ if(0 != ps_slice_hdr->i1_slice_disable_deblocking_filter_flag) { WORD32 bs_strd = (ps_sps->i2_pic_wd_in_ctb + 1) * (ctb_size * ctb_size / 8 / 16); UWORD32 *pu4_vert_bs = (UWORD32 *)((UWORD8 *)ps_codec->s_parse.s_bs_ctxt.pu4_pic_vert_bs + ps_codec->s_parse.i4_ctb_x * (ctb_size * ctb_size / 8 / 16) + ps_codec->s_parse.i4_ctb_y * bs_strd); UWORD32 *pu4_horz_bs = (UWORD32 *)((UWORD8 *)ps_codec->s_parse.s_bs_ctxt.pu4_pic_horz_bs + ps_codec->s_parse.i4_ctb_x * (ctb_size * ctb_size / 8 / 16) + ps_codec->s_parse.i4_ctb_y * bs_strd); memset(pu4_vert_bs, 0, (ctb_size / 8) * (ctb_size / 4) / 8 * 2); memset(pu4_horz_bs, 0, (ctb_size / 8) * (ctb_size / 4) / 8 * 2); } } } DATA_SYNC(); /* Update the parse status map */ { sps_t *ps_sps = ps_codec->s_parse.ps_sps; UWORD8 *pu1_buf; WORD32 idx; idx = (ps_codec->s_parse.i4_ctb_x); idx += ((ps_codec->s_parse.i4_ctb_y) * ps_sps->i2_pic_wd_in_ctb); pu1_buf = (ps_codec->pu1_parse_map + idx); *pu1_buf = 1; } /* Increment CTB x and y positions */ ps_codec->s_parse.i4_ctb_tile_x++; ps_codec->s_parse.i4_ctb_x++; ps_codec->s_parse.i4_ctb_slice_x++; /*If tiles are enabled, handle the slice counters differently*/ if(ps_pps->i1_tiles_enabled_flag) { tile_start_ctb_idx = ps_tile->u1_pos_x + ps_tile->u1_pos_y * (ps_sps->i2_pic_wd_in_ctb); slice_start_ctb_idx = ps_slice_hdr->i2_ctb_x + ps_slice_hdr->i2_ctb_y * (ps_sps->i2_pic_wd_in_ctb); if((slice_start_ctb_idx < tile_start_ctb_idx)) { if(ps_codec->s_parse.i4_ctb_slice_x == (ps_tile->u1_pos_x + ps_tile->u2_wd)) { /* Reached end of slice row within a tile /frame */ ps_codec->s_parse.i4_ctb_slice_y++; ps_codec->s_parse.i4_ctb_slice_x = ps_tile->u1_pos_x; //todo:Check } } else if(ps_codec->s_parse.i4_ctb_slice_x == (ps_tile->u2_wd)) { ps_codec->s_parse.i4_ctb_slice_y++; ps_codec->s_parse.i4_ctb_slice_x = 0; } } else { if(ps_codec->s_parse.i4_ctb_slice_x == ps_tile->u2_wd) { /* Reached end of slice row within a tile /frame */ ps_codec->s_parse.i4_ctb_slice_y++; ps_codec->s_parse.i4_ctb_slice_x = 0; } } if(ps_codec->s_parse.i4_ctb_tile_x == (ps_tile->u2_wd)) { /* Reached end of tile row */ ps_codec->s_parse.i4_ctb_tile_x = 0; ps_codec->s_parse.i4_ctb_x = ps_tile->u1_pos_x; ps_codec->s_parse.i4_ctb_tile_y++; ps_codec->s_parse.i4_ctb_y++; if(ps_codec->s_parse.i4_ctb_tile_y == (ps_tile->u2_ht)) { /* Reached End of Tile */ ps_codec->s_parse.i4_ctb_tile_y = 0; ps_codec->s_parse.i4_ctb_tile_x = 0; ps_codec->s_parse.ps_tile++; if((ps_tile->u2_ht + ps_tile->u1_pos_y == ps_sps->i2_pic_ht_in_ctb) && (ps_tile->u2_wd + ps_tile->u1_pos_x == ps_sps->i2_pic_wd_in_ctb)) { /* Reached end of frame */ end_of_pic = 1; ps_codec->s_parse.i4_ctb_x = 0; ps_codec->s_parse.i4_ctb_y = ps_sps->i2_pic_ht_in_ctb; } else { /* Initialize ctb_x and ctb_y to start of next tile */ ps_tile = ps_codec->s_parse.ps_tile; ps_codec->s_parse.i4_ctb_x = ps_tile->u1_pos_x; ps_codec->s_parse.i4_ctb_y = ps_tile->u1_pos_y; ps_codec->s_parse.i4_ctb_tile_y = 0; ps_codec->s_parse.i4_ctb_tile_x = 0; ps_codec->s_parse.i4_ctb_slice_x = ps_tile->u1_pos_x; ps_codec->s_parse.i4_ctb_slice_y = ps_tile->u1_pos_y; } } } ps_codec->s_parse.i4_next_ctb_indx = ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * ps_sps->i2_pic_wd_in_ctb; /* If the current slice is in error, check if the next slice's address * is reached and mark the end_of_slice flag */ if(ps_codec->i4_slice_error) { slice_header_t *ps_slice_hdr_next = ps_slice_hdr + 1; WORD32 next_slice_addr = ps_slice_hdr_next->i2_ctb_x + ps_slice_hdr_next->i2_ctb_y * ps_sps->i2_pic_wd_in_ctb; if(ps_codec->s_parse.i4_next_ctb_indx == next_slice_addr) end_of_slice_flag = 1; } /* If the codec is running in single core mode * then call process function for current CTB */ if((1 == ps_codec->i4_num_cores) && (ps_codec->s_parse.i4_ctb_tile_x == 0)) { process_ctxt_t *ps_proc = &ps_codec->as_process[0]; ps_proc->i4_ctb_cnt = ps_proc->ps_tile->u2_wd; ihevcd_process(ps_proc); } /* If the bytes for the current slice are exhausted * set end_of_slice flag to 1 * This slice will be treated as incomplete */ if((UWORD8 *)ps_codec->s_parse.s_bitstrm.pu1_buf_max + BITSTRM_OFF_THRS < ((UWORD8 *)ps_codec->s_parse.s_bitstrm.pu4_buf + (ps_codec->s_parse.s_bitstrm.u4_bit_ofst / 8))) { if(0 == ps_codec->i4_slice_error) end_of_slice_flag = 1; } if(end_of_pic) break; } while(!end_of_slice_flag); /* Increment the slice index for parsing next slice */ if(0 == end_of_pic) { while(1) { WORD32 parse_slice_idx; parse_slice_idx = ps_codec->s_parse.i4_cur_slice_idx; parse_slice_idx++; { /* If the next slice header is not initialized, update cur_slice_idx and break */ if((1 == ps_codec->i4_num_cores) || (0 != (parse_slice_idx & (MAX_SLICE_HDR_CNT - 1)))) { ps_codec->s_parse.i4_cur_slice_idx = parse_slice_idx; break; } /* If the next slice header is initialised, wait for the parsed slices to be processed */ else { WORD32 ctb_indx = 0; while(ctb_indx != ps_sps->i4_pic_size_in_ctb) { WORD32 parse_status = *(ps_codec->pu1_parse_map + ctb_indx); volatile WORD32 proc_status = *(ps_codec->pu1_proc_map + ctb_indx) & 1; if(parse_status == proc_status) ctb_indx++; } ps_codec->s_parse.i4_cur_slice_idx = parse_slice_idx; break; } } } } else { #if FRAME_ILF_PAD if(FRAME_ILF_PAD && 1 == ps_codec->i4_num_cores) { if(ps_slice_hdr->i4_abs_pic_order_cnt == 0) { DUMP_PRE_ILF(ps_codec->as_process[0].pu1_cur_pic_luma, ps_codec->as_process[0].pu1_cur_pic_chroma, ps_sps->i2_pic_width_in_luma_samples, ps_sps->i2_pic_height_in_luma_samples, ps_codec->i4_strd); DUMP_BS(ps_codec->as_process[0].s_bs_ctxt.pu4_pic_vert_bs, ps_codec->as_process[0].s_bs_ctxt.pu4_pic_horz_bs, ps_sps->i2_pic_wd_in_ctb * (ctb_size * ctb_size / 8 / 16) * ps_sps->i2_pic_ht_in_ctb, (ps_sps->i2_pic_wd_in_ctb + 1) * (ctb_size * ctb_size / 8 / 16) * ps_sps->i2_pic_ht_in_ctb); DUMP_QP(ps_codec->as_process[0].s_bs_ctxt.pu1_pic_qp, (ps_sps->i2_pic_height_in_luma_samples * ps_sps->i2_pic_width_in_luma_samples) / (MIN_CU_SIZE * MIN_CU_SIZE)); DUMP_QP_CONST_IN_CTB(ps_codec->as_process[0].s_bs_ctxt.pu1_pic_qp_const_in_ctb, (ps_sps->i2_pic_height_in_luma_samples * ps_sps->i2_pic_width_in_luma_samples) / (MIN_CTB_SIZE * MIN_CTB_SIZE) / 8); DUMP_NO_LOOP_FILTER(ps_codec->as_process[0].pu1_pic_no_loop_filter_flag, (ps_sps->i2_pic_width_in_luma_samples / MIN_CU_SIZE) * (ps_sps->i2_pic_height_in_luma_samples / MIN_CU_SIZE) / 8); DUMP_OFFSETS(ps_slice_hdr->i1_beta_offset_div2, ps_slice_hdr->i1_tc_offset_div2, ps_pps->i1_pic_cb_qp_offset, ps_pps->i1_pic_cr_qp_offset); } ps_codec->s_parse.s_deblk_ctxt.ps_pps = ps_codec->s_parse.ps_pps; ps_codec->s_parse.s_deblk_ctxt.ps_sps = ps_codec->s_parse.ps_sps; ps_codec->s_parse.s_deblk_ctxt.ps_codec = ps_codec; ps_codec->s_parse.s_deblk_ctxt.ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr; ps_codec->s_parse.s_deblk_ctxt.is_chroma_yuv420sp_vu = (ps_codec->e_ref_chroma_fmt == IV_YUV_420SP_VU); ps_codec->s_parse.s_sao_ctxt.ps_pps = ps_codec->s_parse.ps_pps; ps_codec->s_parse.s_sao_ctxt.ps_sps = ps_codec->s_parse.ps_sps; ps_codec->s_parse.s_sao_ctxt.ps_codec = ps_codec; ps_codec->s_parse.s_sao_ctxt.ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr; ihevcd_ilf_pad_frame(&ps_codec->s_parse.s_deblk_ctxt, &ps_codec->s_parse.s_sao_ctxt); } #endif ps_codec->s_parse.i4_end_of_frame = 1; } return ret; } Commit Message: Return error from cabac init if offset is greater than range When the offset was greater than range, the bitstream was read more than the valid range in leaf-level cabac parsing modules. Error check was added to cabac init to fix this issue. Additionally end of slice and slice error were signalled to suppress further parsing of current slice. Bug: 34897036 Change-Id: I1263f1d1219684ffa6e952c76e5a08e9a933c9d2 (cherry picked from commit 3b175da88a1807d19cdd248b74bce60e57f05c6a) (cherry picked from commit b92314c860d01d754ef579eafe55d7377962b3ba) CWE ID: CWE-119 Target: 1 Example 2: Code: GahpServer *GahpServer::FindOrCreateGahpServer(const char *id, const char *path, const ArgList *args) { int rc; GahpServer *server = NULL; if ( path == NULL ) { path = GAHPCLIENT_DEFAULT_SERVER_PATH; } rc = GahpServersById.lookup( HashKey( id ), server ); if ( rc != 0 ) { server = new GahpServer( id, path, args ); ASSERT(server); GahpServersById.insert( HashKey( id ), server ); } else { ASSERT(server); } return server; } Commit Message: CWE ID: CWE-134 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 ftrace_nr_registered_ops(void) { struct ftrace_ops *ops; int cnt = 0; mutex_lock(&ftrace_lock); for (ops = ftrace_ops_list; ops != &ftrace_list_end; ops = ops->next) cnt++; mutex_unlock(&ftrace_lock); return cnt; } Commit Message: tracing: Fix possible NULL pointer dereferences Currently set_ftrace_pid and set_graph_function files use seq_lseek for their fops. However seq_open() is called only for FMODE_READ in the fops->open() so that if an user tries to seek one of those file when she open it for writing, it sees NULL seq_file and then panic. It can be easily reproduced with following command: $ cd /sys/kernel/debug/tracing $ echo 1234 | sudo tee -a set_ftrace_pid In this example, GNU coreutils' tee opens the file with fopen(, "a") and then the fopen() internally calls lseek(). Link: http://lkml.kernel.org/r/[email protected] Cc: Frederic Weisbecker <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Namhyung Kim <[email protected]> Cc: [email protected] Signed-off-by: Namhyung Kim <[email protected]> Signed-off-by: Steven Rostedt <[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: void Document::DispatchUnloadEvents() { PluginScriptForbiddenScope forbid_plugin_destructor_scripting; if (parser_) parser_->StopParsing(); if (load_event_progress_ == kLoadEventNotRun) return; if (load_event_progress_ <= kUnloadEventInProgress) { Element* current_focused_element = FocusedElement(); if (auto* input = ToHTMLInputElementOrNull(current_focused_element)) input->EndEditing(); if (load_event_progress_ < kPageHideInProgress) { load_event_progress_ = kPageHideInProgress; if (LocalDOMWindow* window = domWindow()) { const TimeTicks pagehide_event_start = CurrentTimeTicks(); window->DispatchEvent( PageTransitionEvent::Create(EventTypeNames::pagehide, false), this); const TimeTicks pagehide_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL( CustomCountHistogram, pagehide_histogram, ("DocumentEventTiming.PageHideDuration", 0, 10000000, 50)); pagehide_histogram.Count( (pagehide_event_end - pagehide_event_start).InMicroseconds()); } if (!frame_) return; mojom::PageVisibilityState visibility_state = GetPageVisibilityState(); load_event_progress_ = kUnloadVisibilityChangeInProgress; if (visibility_state != mojom::PageVisibilityState::kHidden) { const TimeTicks pagevisibility_hidden_event_start = CurrentTimeTicks(); DispatchEvent(Event::CreateBubble(EventTypeNames::visibilitychange)); const TimeTicks pagevisibility_hidden_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL(CustomCountHistogram, pagevisibility_histogram, ("DocumentEventTiming.PageVibilityHiddenDuration", 0, 10000000, 50)); pagevisibility_histogram.Count((pagevisibility_hidden_event_end - pagevisibility_hidden_event_start) .InMicroseconds()); DispatchEvent( Event::CreateBubble(EventTypeNames::webkitvisibilitychange)); } if (!frame_) return; frame_->Loader().SaveScrollAnchor(); DocumentLoader* document_loader = frame_->Loader().GetProvisionalDocumentLoader(); load_event_progress_ = kUnloadEventInProgress; Event* unload_event(Event::Create(EventTypeNames::unload)); if (document_loader && document_loader->GetTiming().UnloadEventStart().is_null() && document_loader->GetTiming().UnloadEventEnd().is_null()) { DocumentLoadTiming& timing = document_loader->GetTiming(); DCHECK(!timing.NavigationStart().is_null()); const TimeTicks unload_event_start = CurrentTimeTicks(); timing.MarkUnloadEventStart(unload_event_start); frame_->DomWindow()->DispatchEvent(unload_event, this); const TimeTicks unload_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL( CustomCountHistogram, unload_histogram, ("DocumentEventTiming.UnloadDuration", 0, 10000000, 50)); unload_histogram.Count( (unload_event_end - unload_event_start).InMicroseconds()); timing.MarkUnloadEventEnd(unload_event_end); } else { frame_->DomWindow()->DispatchEvent(unload_event, frame_->GetDocument()); } } load_event_progress_ = kUnloadEventHandled; } if (!frame_) return; bool keep_event_listeners = frame_->Loader().GetProvisionalDocumentLoader() && frame_->ShouldReuseDefaultView( frame_->Loader().GetProvisionalDocumentLoader()->Url()); if (!keep_event_listeners) RemoveAllEventListenersRecursively(); } Commit Message: Prevent sandboxed documents from reusing the default window Bug: 377995 Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541 Reviewed-on: https://chromium-review.googlesource.com/983558 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#567663} CWE ID: CWE-285 Target: 1 Example 2: Code: unsigned WebGLRenderingContextBase::CurrentMaxGLContexts() { MutexLocker locker(WebGLContextLimitMutex()); DCHECK(webgl_context_limits_initialized_); return IsMainThread() ? max_active_webgl_contexts_ : max_active_webgl_contexts_on_worker_; } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} 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: EncodedJSValue JSC_HOST_CALL JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver(ExecState* exec) { if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); JSObject* object = exec->argument(0).getObject(); if (!object) { setDOMException(exec, TYPE_MISMATCH_ERR); return JSValue::encode(jsUndefined()); } JSWebKitMutationObserverConstructor* jsConstructor = jsCast<JSWebKitMutationObserverConstructor*>(exec->callee()); RefPtr<MutationCallback> callback = JSMutationCallback::create(object, jsConstructor->globalObject()); return JSValue::encode(asObject(toJS(exec, jsConstructor->globalObject(), WebKitMutationObserver::create(callback.release())))); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 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: void fib_del_ifaddr(struct in_ifaddr *ifa, struct in_ifaddr *iprim) { struct in_device *in_dev = ifa->ifa_dev; struct net_device *dev = in_dev->dev; struct in_ifaddr *ifa1; struct in_ifaddr *prim = ifa, *prim1 = NULL; __be32 brd = ifa->ifa_address | ~ifa->ifa_mask; __be32 any = ifa->ifa_address & ifa->ifa_mask; #define LOCAL_OK 1 #define BRD_OK 2 #define BRD0_OK 4 #define BRD1_OK 8 unsigned int ok = 0; int subnet = 0; /* Primary network */ int gone = 1; /* Address is missing */ int same_prefsrc = 0; /* Another primary with same IP */ if (ifa->ifa_flags & IFA_F_SECONDARY) { prim = inet_ifa_byprefix(in_dev, any, ifa->ifa_mask); if (!prim) { pr_warn("%s: bug: prim == NULL\n", __func__); return; } if (iprim && iprim != prim) { pr_warn("%s: bug: iprim != prim\n", __func__); return; } } else if (!ipv4_is_zeronet(any) && (any != ifa->ifa_local || ifa->ifa_prefixlen < 32)) { if (!(ifa->ifa_flags & IFA_F_NOPREFIXROUTE)) fib_magic(RTM_DELROUTE, dev->flags & IFF_LOOPBACK ? RTN_LOCAL : RTN_UNICAST, any, ifa->ifa_prefixlen, prim); subnet = 1; } /* Deletion is more complicated than add. * We should take care of not to delete too much :-) * * Scan address list to be sure that addresses are really gone. */ for (ifa1 = in_dev->ifa_list; ifa1; ifa1 = ifa1->ifa_next) { if (ifa1 == ifa) { /* promotion, keep the IP */ gone = 0; continue; } /* Ignore IFAs from our subnet */ if (iprim && ifa1->ifa_mask == iprim->ifa_mask && inet_ifa_match(ifa1->ifa_address, iprim)) continue; /* Ignore ifa1 if it uses different primary IP (prefsrc) */ if (ifa1->ifa_flags & IFA_F_SECONDARY) { /* Another address from our subnet? */ if (ifa1->ifa_mask == prim->ifa_mask && inet_ifa_match(ifa1->ifa_address, prim)) prim1 = prim; else { /* We reached the secondaries, so * same_prefsrc should be determined. */ if (!same_prefsrc) continue; /* Search new prim1 if ifa1 is not * using the current prim1 */ if (!prim1 || ifa1->ifa_mask != prim1->ifa_mask || !inet_ifa_match(ifa1->ifa_address, prim1)) prim1 = inet_ifa_byprefix(in_dev, ifa1->ifa_address, ifa1->ifa_mask); if (!prim1) continue; if (prim1->ifa_local != prim->ifa_local) continue; } } else { if (prim->ifa_local != ifa1->ifa_local) continue; prim1 = ifa1; if (prim != prim1) same_prefsrc = 1; } if (ifa->ifa_local == ifa1->ifa_local) ok |= LOCAL_OK; if (ifa->ifa_broadcast == ifa1->ifa_broadcast) ok |= BRD_OK; if (brd == ifa1->ifa_broadcast) ok |= BRD1_OK; if (any == ifa1->ifa_broadcast) ok |= BRD0_OK; /* primary has network specific broadcasts */ if (prim1 == ifa1 && ifa1->ifa_prefixlen < 31) { __be32 brd1 = ifa1->ifa_address | ~ifa1->ifa_mask; __be32 any1 = ifa1->ifa_address & ifa1->ifa_mask; if (!ipv4_is_zeronet(any1)) { if (ifa->ifa_broadcast == brd1 || ifa->ifa_broadcast == any1) ok |= BRD_OK; if (brd == brd1 || brd == any1) ok |= BRD1_OK; if (any == brd1 || any == any1) ok |= BRD0_OK; } } } if (!(ok & BRD_OK)) fib_magic(RTM_DELROUTE, RTN_BROADCAST, ifa->ifa_broadcast, 32, prim); if (subnet && ifa->ifa_prefixlen < 31) { if (!(ok & BRD1_OK)) fib_magic(RTM_DELROUTE, RTN_BROADCAST, brd, 32, prim); if (!(ok & BRD0_OK)) fib_magic(RTM_DELROUTE, RTN_BROADCAST, any, 32, prim); } if (!(ok & LOCAL_OK)) { unsigned int addr_type; fib_magic(RTM_DELROUTE, RTN_LOCAL, ifa->ifa_local, 32, prim); /* Check, that this local address finally disappeared. */ addr_type = inet_addr_type_dev_table(dev_net(dev), dev, ifa->ifa_local); if (gone && addr_type != RTN_LOCAL) { /* And the last, but not the least thing. * We must flush stray FIB entries. * * First of all, we scan fib_info list searching * for stray nexthop entries, then ignite fib_flush. */ if (fib_sync_down_addr(dev_net(dev), ifa->ifa_local)) fib_flush(dev_net(dev)); } } #undef LOCAL_OK #undef BRD_OK #undef BRD0_OK #undef BRD1_OK } Commit Message: ipv4: Don't do expensive useless work during inetdev destroy. When an inetdev is destroyed, every address assigned to the interface is removed. And in this scenerio we do two pointless things which can be very expensive if the number of assigned interfaces is large: 1) Address promotion. We are deleting all addresses, so there is no point in doing this. 2) A full nf conntrack table purge for every address. We only need to do this once, as is already caught by the existing masq_dev_notifier so masq_inet_event() can skip this. Reported-by: Solar Designer <[email protected]> Signed-off-by: David S. Miller <[email protected]> Tested-by: Cyrill Gorcunov <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: static int posix_cpu_clock_get(const clockid_t which_clock, struct timespec64 *tp) { const pid_t pid = CPUCLOCK_PID(which_clock); int err = -EINVAL; if (pid == 0) { /* * Special case constant value for our own clocks. * We don't have to do any lookup to find ourselves. */ err = posix_cpu_clock_get_task(current, which_clock, tp); } else { /* * Find the given PID, and validate that the caller * should be able to see it. */ struct task_struct *p; rcu_read_lock(); p = find_task_by_vpid(pid); if (p) err = posix_cpu_clock_get_task(p, which_clock, tp); rcu_read_unlock(); } return err; } Commit Message: posix-timers: Sanitize overrun handling The posix timer overrun handling is broken because the forwarding functions can return a huge number of overruns which does not fit in an int. As a consequence timer_getoverrun(2) and siginfo::si_overrun can turn into random number generators. The k_clock::timer_forward() callbacks return a 64 bit value now. Make k_itimer::ti_overrun[_last] 64bit as well, so the kernel internal accounting is correct. 3Remove the temporary (int) casts. Add a helper function which clamps the overrun value returned to user space via timer_getoverrun(2) or siginfo::si_overrun limited to a positive value between 0 and INT_MAX. INT_MAX is an indicator for user space that the overrun value has been clamped. Reported-by: Team OWL337 <[email protected]> Signed-off-by: Thomas Gleixner <[email protected]> Acked-by: John Stultz <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Michael Kerrisk <[email protected]> Link: https://lkml.kernel.org/r/[email protected] CWE ID: CWE-190 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: explicit SyncInternal(const std::string& name) : name_(name), weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)), enable_sync_tabs_for_other_clients_(false), registrar_(NULL), change_delegate_(NULL), initialized_(false), testing_mode_(NON_TEST), observing_ip_address_changes_(false), traffic_recorder_(kMaxMessagesToRecord, kMaxMessageSizeToRecord), encryptor_(NULL), unrecoverable_error_handler_(NULL), report_unrecoverable_error_function_(NULL), created_on_loop_(MessageLoop::current()), nigori_overwrite_count_(0) { for (int i = syncable::FIRST_REAL_MODEL_TYPE; i < syncable::MODEL_TYPE_COUNT; ++i) { notification_info_map_.insert( std::make_pair(syncable::ModelTypeFromInt(i), NotificationInfo())); } BindJsMessageHandler( "getNotificationState", &SyncManager::SyncInternal::GetNotificationState); BindJsMessageHandler( "getNotificationInfo", &SyncManager::SyncInternal::GetNotificationInfo); BindJsMessageHandler( "getRootNodeDetails", &SyncManager::SyncInternal::GetRootNodeDetails); BindJsMessageHandler( "getNodeSummariesById", &SyncManager::SyncInternal::GetNodeSummariesById); BindJsMessageHandler( "getNodeDetailsById", &SyncManager::SyncInternal::GetNodeDetailsById); BindJsMessageHandler( "getAllNodes", &SyncManager::SyncInternal::GetAllNodes); BindJsMessageHandler( "getChildNodeIds", &SyncManager::SyncInternal::GetChildNodeIds); BindJsMessageHandler( "getClientServerTraffic", &SyncManager::SyncInternal::GetClientServerTraffic); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 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 int jpc_pi_nextrpcl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; uint_fast32_t trx0; uint_fast32_t try0; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2 || pirlvl->prcheightexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2) { return -1; } xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); if (((pi->x == pi->xstart && ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) || !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) || !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } Commit Message: Fixed a bug in the packet iterator code. Added a new regression test case. CWE ID: CWE-125 Target: 1 Example 2: Code: void QQuickWebViewFlickablePrivate::didFinishFirstNonEmptyLayout() { if (!pageIsSuspended) { isTransitioningToNewPage = false; postTransitionState->apply(); } } Commit Message: [Qt][WK2] Allow transparent WebViews https://bugs.webkit.org/show_bug.cgi?id=80608 Reviewed by Tor Arne Vestbø. Added support for transparentBackground in QQuickWebViewExperimental. This uses the existing drawsTransparentBackground property in WebKit2. Also, changed LayerTreeHostQt to set the contentsOpaque flag when the root layer changes, otherwise the change doesn't take effect. A new API test was added. * UIProcess/API/qt/qquickwebview.cpp: (QQuickWebViewPrivate::setTransparentBackground): (QQuickWebViewPrivate::transparentBackground): (QQuickWebViewExperimental::transparentBackground): (QQuickWebViewExperimental::setTransparentBackground): * UIProcess/API/qt/qquickwebview_p.h: * UIProcess/API/qt/qquickwebview_p_p.h: (QQuickWebViewPrivate): * UIProcess/API/qt/tests/qquickwebview/tst_qquickwebview.cpp: (tst_QQuickWebView): (tst_QQuickWebView::transparentWebViews): * WebProcess/WebPage/qt/LayerTreeHostQt.cpp: (WebKit::LayerTreeHostQt::LayerTreeHostQt): (WebKit::LayerTreeHostQt::setRootCompositingLayer): git-svn-id: svn://svn.chromium.org/blink/trunk@110254 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-189 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 ipmi_si_mem_setup(struct si_sm_io *io) { unsigned long addr = io->addr_data; int mapsize, idx; if (!addr) return -ENODEV; io->io_cleanup = mem_cleanup; /* * Figure out the actual readb/readw/readl/etc routine to use based * upon the register size. */ switch (io->regsize) { case 1: io->inputb = intf_mem_inb; io->outputb = intf_mem_outb; break; case 2: io->inputb = intf_mem_inw; io->outputb = intf_mem_outw; break; case 4: io->inputb = intf_mem_inl; io->outputb = intf_mem_outl; break; #ifdef readq case 8: io->inputb = mem_inq; io->outputb = mem_outq; break; #endif default: dev_warn(io->dev, "Invalid register size: %d\n", io->regsize); return -EINVAL; } /* * Some BIOSes reserve disjoint memory regions in their ACPI * tables. This causes problems when trying to request the * entire region. Therefore we must request each register * separately. */ for (idx = 0; idx < io->io_size; idx++) { if (request_mem_region(addr + idx * io->regspacing, io->regsize, DEVICE_NAME) == NULL) { /* Undo allocations */ mem_region_cleanup(io, idx); return -EIO; } } /* * Calculate the total amount of memory to claim. This is an * unusual looking calculation, but it avoids claiming any * more memory than it has to. It will claim everything * between the first address to the end of the last full * register. */ mapsize = ((io->io_size * io->regspacing) - (io->regspacing - io->regsize)); io->addr = ioremap(addr, mapsize); if (io->addr == NULL) { mem_region_cleanup(io, io->io_size); return -EIO; } return 0; } Commit Message: ipmi_si: fix use-after-free of resource->name When we excute the following commands, we got oops rmmod ipmi_si cat /proc/ioports [ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478 [ 1623.482382] Mem abort info: [ 1623.482383] ESR = 0x96000007 [ 1623.482385] Exception class = DABT (current EL), IL = 32 bits [ 1623.482386] SET = 0, FnV = 0 [ 1623.482387] EA = 0, S1PTW = 0 [ 1623.482388] Data abort info: [ 1623.482389] ISV = 0, ISS = 0x00000007 [ 1623.482390] CM = 0, WnR = 0 [ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66 [ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000 [ 1623.482399] Internal error: Oops: 96000007 [#1] SMP [ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si] [ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168 [ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017 [ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO) [ 1623.553684] pc : string+0x28/0x98 [ 1623.557040] lr : vsnprintf+0x368/0x5e8 [ 1623.560837] sp : ffff000013213a80 [ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5 [ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049 [ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5 [ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000 [ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000 [ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff [ 1623.596505] x17: 0000000000000200 x16: 0000000000000000 [ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000 [ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000 [ 1623.612661] x11: 0000000000000000 x10: 0000000000000000 [ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f [ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe [ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478 [ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000 [ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff [ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10) [ 1623.651592] Call trace: [ 1623.654068] string+0x28/0x98 [ 1623.657071] vsnprintf+0x368/0x5e8 [ 1623.660517] seq_vprintf+0x70/0x98 [ 1623.668009] seq_printf+0x7c/0xa0 [ 1623.675530] r_show+0xc8/0xf8 [ 1623.682558] seq_read+0x330/0x440 [ 1623.689877] proc_reg_read+0x78/0xd0 [ 1623.697346] __vfs_read+0x60/0x1a0 [ 1623.704564] vfs_read+0x94/0x150 [ 1623.711339] ksys_read+0x6c/0xd8 [ 1623.717939] __arm64_sys_read+0x24/0x30 [ 1623.725077] el0_svc_common+0x120/0x148 [ 1623.732035] el0_svc_handler+0x30/0x40 [ 1623.738757] el0_svc+0x8/0xc [ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085) [ 1623.753441] ---[ end trace f91b6a4937de9835 ]--- [ 1623.760871] Kernel panic - not syncing: Fatal exception [ 1623.768935] SMP: stopping secondary CPUs [ 1623.775718] Kernel Offset: disabled [ 1623.781998] CPU features: 0x002,21006008 [ 1623.788777] Memory Limit: none [ 1623.798329] Starting crashdump kernel... [ 1623.805202] Bye! If io_setup is called successful in try_smi_init() but try_smi_init() goes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi() will not be called while removing module. It leads to the resource that allocated in io_setup() can not be freed, but the name(DEVICE_NAME) of resource is freed while removing the module. It causes use-after-free when cat /proc/ioports. Fix this by calling io_cleanup() while try_smi_init() goes to out_err. and don't call io_cleanup() until io_setup() returns successful to avoid warning prints. Fixes: 93c303d2045b ("ipmi_si: Clean up shutdown a bit") Cc: [email protected] Reported-by: NuoHan Qiao <[email protected]> Suggested-by: Corey Minyard <[email protected]> Signed-off-by: Yang Yingliang <[email protected]> Signed-off-by: Corey Minyard <[email protected]> CWE ID: CWE-416 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: IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_ext_data(dec_state_t *ps_dec) { stream_t *ps_stream; UWORD32 u4_start_code; IMPEG2D_ERROR_CODES_T e_error; e_error = (IMPEG2D_ERROR_CODES_T) IVD_ERROR_NONE; ps_stream = &ps_dec->s_bit_stream; u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); while( (u4_start_code == EXTENSION_START_CODE || u4_start_code == USER_DATA_START_CODE) && (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE == e_error) { if(u4_start_code == USER_DATA_START_CODE) { impeg2d_dec_user_data(ps_dec); } else { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u4_start_code = impeg2d_bit_stream_nxt(ps_stream,EXT_ID_LEN); switch(u4_start_code) { case SEQ_DISPLAY_EXT_ID: impeg2d_dec_seq_disp_ext(ps_dec); break; case SEQ_SCALABLE_EXT_ID: e_error = IMPEG2D_SCALABILITIY_NOT_SUPPORTED; break; default: /* In case its a reserved extension code */ impeg2d_bit_stream_flush(ps_stream,EXT_ID_LEN); impeg2d_peek_next_start_code(ps_dec); break; } } u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); } return e_error; } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254 Target: 1 Example 2: Code: bool RenderMenuList::itemIsSelected(unsigned listIndex) const { const Vector<HTMLElement*>& listItems = toHTMLSelectElement(node())->listItems(); if (listIndex >= listItems.size()) return false; HTMLElement* element = listItems[listIndex]; return element->hasTagName(optionTag) && toHTMLOptionElement(element)->selected(); } Commit Message: PopupMenuClient::multiple() should be const https://bugs.webkit.org/show_bug.cgi?id=76771 Patch by Benjamin Poulain <[email protected]> on 2012-01-21 Reviewed by Kent Tamura. * platform/PopupMenuClient.h: (WebCore::PopupMenuClient::multiple): * rendering/RenderMenuList.cpp: (WebCore::RenderMenuList::multiple): * rendering/RenderMenuList.h: git-svn-id: svn://svn.chromium.org/blink/trunk@105570 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: yyparse (void *yyscanner, RE_LEX_ENVIRONMENT *lex_env) { /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (&yylval, yyscanner, lex_env); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: #line 105 "re_grammar.y" /* yacc.c:1646 */ { RE_AST* re_ast = yyget_extra(yyscanner); re_ast->root_node = (yyvsp[0].re_node); } #line 1340 "re_grammar.c" /* yacc.c:1646 */ break; case 4: #line 114 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = (yyvsp[0].re_node); } #line 1348 "re_grammar.c" /* yacc.c:1646 */ break; case 5: #line 118 "re_grammar.y" /* yacc.c:1646 */ { mark_as_not_fast_regexp(); (yyval.re_node) = yr_re_node_create(RE_NODE_ALT, (yyvsp[-2].re_node), (yyvsp[0].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-2].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node)); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1363 "re_grammar.c" /* yacc.c:1646 */ break; case 6: #line 129 "re_grammar.y" /* yacc.c:1646 */ { RE_NODE* node; mark_as_not_fast_regexp(); node = yr_re_node_create(RE_NODE_EMPTY, NULL, NULL); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node)); ERROR_IF(node == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node) = yr_re_node_create(RE_NODE_ALT, (yyvsp[-1].re_node), node); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1382 "re_grammar.c" /* yacc.c:1646 */ break; case 7: #line 147 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = (yyvsp[0].re_node); } #line 1390 "re_grammar.c" /* yacc.c:1646 */ break; case 8: #line 151 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, (yyvsp[-1].re_node), (yyvsp[0].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node)); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node)); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1402 "re_grammar.c" /* yacc.c:1646 */ break; case 9: #line 162 "re_grammar.y" /* yacc.c:1646 */ { RE_AST* re_ast; mark_as_not_fast_regexp(); re_ast = yyget_extra(yyscanner); re_ast->flags |= RE_FLAGS_GREEDY; (yyval.re_node) = yr_re_node_create(RE_NODE_STAR, (yyvsp[-1].re_node), NULL); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node)); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1420 "re_grammar.c" /* yacc.c:1646 */ break; case 10: #line 176 "re_grammar.y" /* yacc.c:1646 */ { RE_AST* re_ast; mark_as_not_fast_regexp(); re_ast = yyget_extra(yyscanner); re_ast->flags |= RE_FLAGS_UNGREEDY; (yyval.re_node) = yr_re_node_create(RE_NODE_STAR, (yyvsp[-2].re_node), NULL); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-2].re_node)); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->greedy = FALSE; } #line 1440 "re_grammar.c" /* yacc.c:1646 */ break; case 11: #line 192 "re_grammar.y" /* yacc.c:1646 */ { RE_AST* re_ast; mark_as_not_fast_regexp(); re_ast = yyget_extra(yyscanner); re_ast->flags |= RE_FLAGS_GREEDY; (yyval.re_node) = yr_re_node_create(RE_NODE_PLUS, (yyvsp[-1].re_node), NULL); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node)); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1458 "re_grammar.c" /* yacc.c:1646 */ break; case 12: #line 206 "re_grammar.y" /* yacc.c:1646 */ { RE_AST* re_ast; mark_as_not_fast_regexp(); re_ast = yyget_extra(yyscanner); re_ast->flags |= RE_FLAGS_UNGREEDY; (yyval.re_node) = yr_re_node_create(RE_NODE_PLUS, (yyvsp[-2].re_node), NULL); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-2].re_node)); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->greedy = FALSE; } #line 1478 "re_grammar.c" /* yacc.c:1646 */ break; case 13: #line 222 "re_grammar.y" /* yacc.c:1646 */ { RE_AST* re_ast = yyget_extra(yyscanner); re_ast->flags |= RE_FLAGS_GREEDY; if ((yyvsp[-1].re_node)->type == RE_NODE_ANY) { (yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL); DESTROY_NODE_IF(TRUE, (yyvsp[-1].re_node)); } else { mark_as_not_fast_regexp(); (yyval.re_node) = yr_re_node_create(RE_NODE_RANGE, (yyvsp[-1].re_node), NULL); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node)); } DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node)); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->start = 0; (yyval.re_node)->end = 1; } #line 1505 "re_grammar.c" /* yacc.c:1646 */ break; case 14: #line 245 "re_grammar.y" /* yacc.c:1646 */ { RE_AST* re_ast = yyget_extra(yyscanner); re_ast->flags |= RE_FLAGS_UNGREEDY; if ((yyvsp[-2].re_node)->type == RE_NODE_ANY) { (yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL); DESTROY_NODE_IF(TRUE, (yyvsp[-2].re_node)); } else { mark_as_not_fast_regexp(); (yyval.re_node) = yr_re_node_create(RE_NODE_RANGE, (yyvsp[-2].re_node), NULL); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-2].re_node)); } DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-2].re_node)); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->start = 0; (yyval.re_node)->end = 1; (yyval.re_node)->greedy = FALSE; } #line 1533 "re_grammar.c" /* yacc.c:1646 */ break; case 15: #line 269 "re_grammar.y" /* yacc.c:1646 */ { RE_AST* re_ast = yyget_extra(yyscanner); re_ast->flags |= RE_FLAGS_GREEDY; if ((yyvsp[-1].re_node)->type == RE_NODE_ANY) { (yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL); DESTROY_NODE_IF(TRUE, (yyvsp[-1].re_node)); } else { mark_as_not_fast_regexp(); (yyval.re_node) = yr_re_node_create(RE_NODE_RANGE, (yyvsp[-1].re_node), NULL); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node)); } ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->start = (yyvsp[0].range) & 0xFFFF;; (yyval.re_node)->end = (yyvsp[0].range) >> 16;; } #line 1559 "re_grammar.c" /* yacc.c:1646 */ break; case 16: #line 291 "re_grammar.y" /* yacc.c:1646 */ { RE_AST* re_ast = yyget_extra(yyscanner); re_ast->flags |= RE_FLAGS_UNGREEDY; if ((yyvsp[-2].re_node)->type == RE_NODE_ANY) { (yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL); DESTROY_NODE_IF(TRUE, (yyvsp[-2].re_node)); } else { mark_as_not_fast_regexp(); (yyval.re_node) = yr_re_node_create(RE_NODE_RANGE, (yyvsp[-2].re_node), NULL); DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-2].re_node)); } ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->start = (yyvsp[-1].range) & 0xFFFF;; (yyval.re_node)->end = (yyvsp[-1].range) >> 16;; (yyval.re_node)->greedy = FALSE; } #line 1586 "re_grammar.c" /* yacc.c:1646 */ break; case 17: #line 314 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = (yyvsp[0].re_node); } #line 1594 "re_grammar.c" /* yacc.c:1646 */ break; case 18: #line 318 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_WORD_BOUNDARY, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1604 "re_grammar.c" /* yacc.c:1646 */ break; case 19: #line 324 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_NON_WORD_BOUNDARY, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1614 "re_grammar.c" /* yacc.c:1646 */ break; case 20: #line 330 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_ANCHOR_START, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1624 "re_grammar.c" /* yacc.c:1646 */ break; case 21: #line 336 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_ANCHOR_END, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1634 "re_grammar.c" /* yacc.c:1646 */ break; case 22: #line 345 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = (yyvsp[-1].re_node); } #line 1642 "re_grammar.c" /* yacc.c:1646 */ break; case 23: #line 349 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_ANY, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1652 "re_grammar.c" /* yacc.c:1646 */ break; case 24: #line 355 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_LITERAL, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->value = (yyvsp[0].integer); } #line 1664 "re_grammar.c" /* yacc.c:1646 */ break; case 25: #line 363 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_WORD_CHAR, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1674 "re_grammar.c" /* yacc.c:1646 */ break; case 26: #line 369 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_NON_WORD_CHAR, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1684 "re_grammar.c" /* yacc.c:1646 */ break; case 27: #line 375 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_SPACE, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1694 "re_grammar.c" /* yacc.c:1646 */ break; case 28: #line 381 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_NON_SPACE, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1704 "re_grammar.c" /* yacc.c:1646 */ break; case 29: #line 387 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_DIGIT, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1714 "re_grammar.c" /* yacc.c:1646 */ break; case 30: #line 393 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_NON_DIGIT, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); } #line 1724 "re_grammar.c" /* yacc.c:1646 */ break; case 31: #line 399 "re_grammar.y" /* yacc.c:1646 */ { (yyval.re_node) = yr_re_node_create(RE_NODE_CLASS, NULL, NULL); ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY); (yyval.re_node)->class_vector = (yyvsp[0].class_vector); } #line 1736 "re_grammar.c" /* yacc.c:1646 */ break; #line 1740 "re_grammar.c" /* yacc.c:1646 */ default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (yyscanner, lex_env, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (yyscanner, lex_env, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, yyscanner, lex_env); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp, yyscanner, lex_env); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (yyscanner, lex_env, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, yyscanner, lex_env); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yyscanner, lex_env); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; } Commit Message: Fix issue #674. Move regexp limits to limits.h. CWE ID: CWE-674 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 int udf_encode_fh(struct inode *inode, __u32 *fh, int *lenp, struct inode *parent) { int len = *lenp; struct kernel_lb_addr location = UDF_I(inode)->i_location; struct fid *fid = (struct fid *)fh; int type = FILEID_UDF_WITHOUT_PARENT; if (parent && (len < 5)) { *lenp = 5; return 255; } else if (len < 3) { *lenp = 3; return 255; } *lenp = 3; fid->udf.block = location.logicalBlockNum; fid->udf.partref = location.partitionReferenceNum; fid->udf.generation = inode->i_generation; if (parent) { location = UDF_I(parent)->i_location; fid->udf.parent_block = location.logicalBlockNum; fid->udf.parent_partref = location.partitionReferenceNum; fid->udf.parent_generation = inode->i_generation; *lenp = 5; type = FILEID_UDF_WITH_PARENT; } return type; } Commit Message: udf: avoid info leak on export For type 0x51 the udf.parent_partref member in struct fid gets copied uninitialized to userland. Fix this by initializing it to 0. Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: static ssize_t read_kmem(struct file *file, char __user *buf, size_t count, loff_t *ppos) { unsigned long p = *ppos; ssize_t low_count, read, sz; char *kbuf; /* k-addr because vread() takes vmlist_lock rwlock */ int err = 0; read = 0; if (p < (unsigned long) high_memory) { low_count = count; if (count > (unsigned long)high_memory - p) low_count = (unsigned long)high_memory - p; #ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED /* we don't have page 0 mapped on sparc and m68k.. */ if (p < PAGE_SIZE && low_count > 0) { sz = size_inside_page(p, low_count); if (clear_user(buf, sz)) return -EFAULT; buf += sz; p += sz; read += sz; low_count -= sz; count -= sz; } #endif while (low_count > 0) { sz = size_inside_page(p, low_count); /* * On ia64 if a page has been mapped somewhere as * uncached, then it must also be accessed uncached * by the kernel or data corruption may occur */ kbuf = xlate_dev_kmem_ptr((void *)p); if (!virt_addr_valid(kbuf)) return -ENXIO; if (copy_to_user(buf, kbuf, sz)) return -EFAULT; buf += sz; p += sz; read += sz; low_count -= sz; count -= sz; } } if (count > 0) { kbuf = (char *)__get_free_page(GFP_KERNEL); if (!kbuf) return -ENOMEM; while (count > 0) { sz = size_inside_page(p, count); if (!is_vmalloc_or_module_addr((void *)p)) { err = -ENXIO; break; } sz = vread(kbuf, (char *)p, sz); if (!sz) break; if (copy_to_user(buf, kbuf, sz)) { err = -EFAULT; break; } count -= sz; buf += sz; read += sz; p += sz; } free_page((unsigned long)kbuf); } *ppos = p; return read ? read : err; } Commit Message: mm: Tighten x86 /dev/mem with zeroing reads Under CONFIG_STRICT_DEVMEM, reading System RAM through /dev/mem is disallowed. However, on x86, the first 1MB was always allowed for BIOS and similar things, regardless of it actually being System RAM. It was possible for heap to end up getting allocated in low 1MB RAM, and then read by things like x86info or dd, which would trip hardened usercopy: usercopy: kernel memory exposure attempt detected from ffff880000090000 (dma-kmalloc-256) (4096 bytes) This changes the x86 exception for the low 1MB by reading back zeros for System RAM areas instead of blindly allowing them. More work is needed to extend this to mmap, but currently mmap doesn't go through usercopy, so hardened usercopy won't Oops the kernel. Reported-by: Tommi Rantala <[email protected]> Tested-by: Tommi Rantala <[email protected]> Signed-off-by: Kees Cook <[email protected]> CWE ID: CWE-732 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(SplFileObject, fread) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long length = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) { return; } if (length <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(length + 1); Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; } 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: OMX_ERRORTYPE SoftRaw::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = mChannelCount; pcmParams->nSamplingRate = mSampleRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119 Target: 1 Example 2: Code: page_cgroup_zoneinfo(struct mem_cgroup *memcg, struct page *page) { int nid = page_to_nid(page); int zid = page_zonenum(page); return mem_cgroup_zoneinfo(memcg, nid, zid); } Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [[email protected]: checkpatch fixes] Reported-by: Ulrich Obergfell <[email protected]> Signed-off-by: Andrea Arcangeli <[email protected]> Acked-by: Johannes Weiner <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Dave Jones <[email protected]> Acked-by: Larry Woodman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: Mark Salter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264 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: mysqlnd_switch_to_ssl_if_needed( MYSQLND_CONN_DATA * conn, const MYSQLND_PACKET_GREET * const greet_packet, const MYSQLND_OPTIONS * const options, unsigned long mysql_flags TSRMLS_DC ) { enum_func_status ret = FAIL; const MYSQLND_CHARSET * charset; MYSQLND_PACKET_AUTH * auth_packet; DBG_ENTER("mysqlnd_switch_to_ssl_if_needed"); auth_packet = conn->protocol->m.get_auth_packet(conn->protocol, FALSE TSRMLS_CC); if (!auth_packet) { SET_OOM_ERROR(*conn->error_info); goto end; } auth_packet->client_flags = mysql_flags; auth_packet->max_packet_size = MYSQLND_ASSEMBLED_PACKET_MAX_SIZE; if (options->charset_name && (charset = mysqlnd_find_charset_name(options->charset_name))) { auth_packet->charset_no = charset->nr; } else { #if MYSQLND_UNICODE auth_packet->charset_no = 200;/* utf8 - swedish collation, check mysqlnd_charset.c */ #else auth_packet->charset_no = greet_packet->charset_no; #endif } #ifdef MYSQLND_SSL_SUPPORTED if ((greet_packet->server_capabilities & CLIENT_SSL) && (mysql_flags & CLIENT_SSL)) { zend_bool verify = mysql_flags & CLIENT_SSL_VERIFY_SERVER_CERT? TRUE:FALSE; DBG_INF("Switching to SSL"); if (!PACKET_WRITE(auth_packet, conn)) { CONN_SET_STATE(conn, CONN_QUIT_SENT); SET_CLIENT_ERROR(*conn->error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone); goto end; } conn->net->m.set_client_option(conn->net, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (const char *) &verify TSRMLS_CC); if (FAIL == conn->net->m.enable_ssl(conn->net TSRMLS_CC)) { goto end; } } #endif ret = PASS; end: PACKET_FREE(auth_packet); DBG_RETURN(ret); } Commit Message: CWE ID: CWE-284 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 void copyMultiCh16(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels) { for (unsigned i = 0; i < nSamples; ++i) { for (unsigned c = 0; c < nChannels; ++c) { *dst++ = src[c][i]; } } } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119 Target: 1 Example 2: Code: void DocumentLoader::ProcessDataBuffer() { for (const auto& span : *data_buffer_) ProcessData(span.data(), span.size()); data_buffer_->Clear(); } Commit Message: Inherit CSP when self-navigating to local-scheme URL As the linked bug example shows, we should inherit CSP when we navigate to a local-scheme URL (even if we are in a main browsing context). Bug: 799747 Change-Id: I8413aa8e8049461ebcf0ffbf7b04c41d1340af02 Reviewed-on: https://chromium-review.googlesource.com/c/1234337 Reviewed-by: Mike West <[email protected]> Commit-Queue: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#597889} 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: main (int argc, char **argv) { mode_t old_umask; cleanup_free char *base_path = NULL; int clone_flags; char *old_cwd = NULL; pid_t pid; int event_fd = -1; int child_wait_fd = -1; int setup_finished_pipe[] = {-1, -1}; const char *new_cwd; uid_t ns_uid; gid_t ns_gid; struct stat sbuf; uint64_t val; int res UNUSED; cleanup_free char *seccomp_data = NULL; size_t seccomp_len; struct sock_fprog seccomp_prog; cleanup_free char *args_data = NULL; /* Handle --version early on before we try to acquire/drop * any capabilities so it works in a build environment; * right now flatpak's build runs bubblewrap --version. * https://github.com/projectatomic/bubblewrap/issues/185 */ if (argc == 2 && (strcmp (argv[1], "--version") == 0)) print_version_and_exit (); real_uid = getuid (); real_gid = getgid (); /* Get the (optional) privileges we need */ acquire_privs (); /* Never gain any more privs during exec */ if (prctl (PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) die_with_error ("prctl(PR_SET_NO_NEW_CAPS) failed"); /* The initial code is run with high permissions (i.e. CAP_SYS_ADMIN), so take lots of care. */ read_overflowids (); argv0 = argv[0]; if (isatty (1)) host_tty_dev = ttyname (1); argv++; argc--; if (argc == 0) usage (EXIT_FAILURE, stderr); parse_args (&argc, (const char ***) &argv); /* suck the args into a cleanup_free variable to control their lifecycle */ args_data = opt_args_data; opt_args_data = NULL; if ((requested_caps[0] || requested_caps[1]) && is_privileged) die ("--cap-add in setuid mode can be used only by root"); if (opt_userns_block_fd != -1 && !opt_unshare_user) die ("--userns-block-fd requires --unshare-user"); if (opt_userns_block_fd != -1 && opt_info_fd == -1) die ("--userns-block-fd requires --info-fd"); /* We have to do this if we weren't installed setuid (and we're not * root), so let's just DWIM */ if (!is_privileged && getuid () != 0) opt_unshare_user = TRUE; #ifdef ENABLE_REQUIRE_USERNS /* In this build option, we require userns. */ if (is_privileged && getuid () != 0) opt_unshare_user = TRUE; #endif if (opt_unshare_user_try && stat ("/proc/self/ns/user", &sbuf) == 0) { bool disabled = FALSE; /* RHEL7 has a kernel module parameter that lets you enable user namespaces */ if (stat ("/sys/module/user_namespace/parameters/enable", &sbuf) == 0) { cleanup_free char *enable = NULL; enable = load_file_at (AT_FDCWD, "/sys/module/user_namespace/parameters/enable"); if (enable != NULL && enable[0] == 'N') disabled = TRUE; } /* Check for max_user_namespaces */ if (stat ("/proc/sys/user/max_user_namespaces", &sbuf) == 0) { cleanup_free char *max_user_ns = NULL; max_user_ns = load_file_at (AT_FDCWD, "/proc/sys/user/max_user_namespaces"); if (max_user_ns != NULL && strcmp(max_user_ns, "0\n") == 0) disabled = TRUE; } /* Debian lets you disable *unprivileged* user namespaces. However this is not a problem if we're privileged, and if we're not opt_unshare_user is TRUE already, and there is not much we can do, its just a non-working setup. */ if (!disabled) opt_unshare_user = TRUE; } if (argc == 0) usage (EXIT_FAILURE, stderr); __debug__ (("Creating root mount point\n")); if (opt_sandbox_uid == -1) opt_sandbox_uid = real_uid; if (opt_sandbox_gid == -1) opt_sandbox_gid = real_gid; if (!opt_unshare_user && opt_sandbox_uid != real_uid) die ("Specifying --uid requires --unshare-user"); if (!opt_unshare_user && opt_sandbox_gid != real_gid) die ("Specifying --gid requires --unshare-user"); if (!opt_unshare_uts && opt_sandbox_hostname != NULL) die ("Specifying --hostname requires --unshare-uts"); if (opt_as_pid_1 && !opt_unshare_pid) die ("Specifying --as-pid-1 requires --unshare-pid"); if (opt_as_pid_1 && lock_files != NULL) die ("Specifying --as-pid-1 and --lock-file is not permitted"); /* We need to read stuff from proc during the pivot_root dance, etc. Lets keep a fd to it open */ proc_fd = open ("/proc", O_PATH); if (proc_fd == -1) die_with_error ("Can't open /proc"); /* We need *some* mountpoint where we can mount the root tmpfs. We first try in /run, and if that fails, try in /tmp. */ base_path = xasprintf ("/run/user/%d/.bubblewrap", real_uid); if (ensure_dir (base_path, 0755)) { free (base_path); base_path = xasprintf ("/tmp/.bubblewrap-%d", real_uid); if (ensure_dir (base_path, 0755)) die_with_error ("Creating root mountpoint failed"); } __debug__ (("creating new namespace\n")); if (opt_unshare_pid && !opt_as_pid_1) { event_fd = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK); if (event_fd == -1) die_with_error ("eventfd()"); } /* We block sigchild here so that we can use signalfd in the monitor. */ block_sigchild (); clone_flags = SIGCHLD | CLONE_NEWNS; if (opt_unshare_user) clone_flags |= CLONE_NEWUSER; if (opt_unshare_pid) clone_flags |= CLONE_NEWPID; if (opt_unshare_net) clone_flags |= CLONE_NEWNET; if (opt_unshare_ipc) clone_flags |= CLONE_NEWIPC; if (opt_unshare_uts) clone_flags |= CLONE_NEWUTS; if (opt_unshare_cgroup) { if (stat ("/proc/self/ns/cgroup", &sbuf)) { if (errno == ENOENT) die ("Cannot create new cgroup namespace because the kernel does not support it"); else die_with_error ("stat on /proc/self/ns/cgroup failed"); } clone_flags |= CLONE_NEWCGROUP; } if (opt_unshare_cgroup_try) if (!stat ("/proc/self/ns/cgroup", &sbuf)) clone_flags |= CLONE_NEWCGROUP; child_wait_fd = eventfd (0, EFD_CLOEXEC); if (child_wait_fd == -1) die_with_error ("eventfd()"); /* Track whether pre-exec setup finished if we're reporting process exit */ if (opt_json_status_fd != -1) { int ret; ret = pipe2 (setup_finished_pipe, O_CLOEXEC); if (ret == -1) die_with_error ("pipe2()"); } pid = raw_clone (clone_flags, NULL); if (pid == -1) { if (opt_unshare_user) { if (errno == EINVAL) die ("Creating new namespace failed, likely because the kernel does not support user namespaces. bwrap must be installed setuid on such systems."); else if (errno == EPERM && !is_privileged) die ("No permissions to creating new namespace, likely because the kernel does not allow non-privileged user namespaces. On e.g. debian this can be enabled with 'sysctl kernel.unprivileged_userns_clone=1'."); } die_with_error ("Creating new namespace failed"); } ns_uid = opt_sandbox_uid; ns_gid = opt_sandbox_gid; if (pid != 0) { /* Parent, outside sandbox, privileged (initially) */ if (is_privileged && opt_unshare_user && opt_userns_block_fd == -1) { /* We're running as euid 0, but the uid we want to map is * not 0. This means we're not allowed to write this from * the child user namespace, so we do it from the parent. * * Also, we map uid/gid 0 in the namespace (to overflowuid) * if opt_needs_devpts is true, because otherwise the mount * of devpts fails due to root not being mapped. */ write_uid_gid_map (ns_uid, real_uid, ns_gid, real_gid, pid, TRUE, opt_needs_devpts); } /* Initial launched process, wait for exec:ed command to exit */ /* We don't need any privileges in the launcher, drop them immediately. */ drop_privs (FALSE); /* Optionally bind our lifecycle to that of the parent */ handle_die_with_parent (); if (opt_info_fd != -1) { cleanup_free char *output = xasprintf ("{\n \"child-pid\": %i\n}\n", pid); dump_info (opt_info_fd, output, TRUE); close (opt_info_fd); } if (opt_json_status_fd != -1) { cleanup_free char *output = xasprintf ("{ \"child-pid\": %i }\n", pid); dump_info (opt_json_status_fd, output, TRUE); } if (opt_userns_block_fd != -1) { char b[1]; (void) TEMP_FAILURE_RETRY (read (opt_userns_block_fd, b, 1)); close (opt_userns_block_fd); } /* Let child run now that the uid maps are set up */ val = 1; res = write (child_wait_fd, &val, 8); /* Ignore res, if e.g. the child died and closed child_wait_fd we don't want to error out here */ close (child_wait_fd); return monitor_child (event_fd, pid, setup_finished_pipe[0]); } /* Child, in sandbox, privileged in the parent or in the user namespace (if --unshare-user). * * Note that for user namespaces we run as euid 0 during clone(), so * the child user namespace is owned by euid 0., This means that the * regular user namespace parent (with uid != 0) doesn't have any * capabilities in it, which is nice as we can't exploit those. In * particular the parent user namespace doesn't have CAP_PTRACE * which would otherwise allow the parent to hijack of the child * after this point. * * Unfortunately this also means you can't ptrace the final * sandboxed process from outside the sandbox either. */ if (opt_info_fd != -1) close (opt_info_fd); if (opt_json_status_fd != -1) close (opt_json_status_fd); /* Wait for the parent to init uid/gid maps and drop caps */ res = read (child_wait_fd, &val, 8); close (child_wait_fd); /* At this point we can completely drop root uid, but retain the * required permitted caps. This allow us to do full setup as * the user uid, which makes e.g. fuse access work. */ switch_to_user_with_privs (); if (opt_unshare_net) loopback_setup (); /* Will exit if unsuccessful */ ns_uid = opt_sandbox_uid; ns_gid = opt_sandbox_gid; if (!is_privileged && opt_unshare_user && opt_userns_block_fd == -1) { /* In the unprivileged case we have to write the uid/gid maps in * the child, because we have no caps in the parent */ if (opt_needs_devpts) { /* This is a bit hacky, but we need to first map the real uid/gid to 0, otherwise we can't mount the devpts filesystem because root is not mapped. Later we will create another child user namespace and map back to the real uid */ ns_uid = 0; ns_gid = 0; } write_uid_gid_map (ns_uid, real_uid, ns_gid, real_gid, -1, TRUE, FALSE); } old_umask = umask (0); /* Need to do this before the chroot, but after we're the real uid */ resolve_symlinks_in_ops (); /* Mark everything as slave, so that we still * receive mounts from the real root, but don't * propagate mounts to the real root. */ if (mount (NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) die_with_error ("Failed to make / slave"); /* Create a tmpfs which we will use as / in the namespace */ if (mount ("tmpfs", base_path, "tmpfs", MS_NODEV | MS_NOSUID, NULL) != 0) die_with_error ("Failed to mount tmpfs"); old_cwd = get_current_dir_name (); /* Chdir to the new root tmpfs mount. This will be the CWD during the entire setup. Access old or new root via "oldroot" and "newroot". */ if (chdir (base_path) != 0) die_with_error ("chdir base_path"); /* We create a subdir "$base_path/newroot" for the new root, that * way we can pivot_root to base_path, and put the old root at * "$base_path/oldroot". This avoids problems accessing the oldroot * dir if the user requested to bind mount something over / */ if (mkdir ("newroot", 0755)) die_with_error ("Creating newroot failed"); if (mount ("newroot", "newroot", NULL, MS_MGC_VAL | MS_BIND | MS_REC, NULL) < 0) die_with_error ("setting up newroot bind"); if (mkdir ("oldroot", 0755)) die_with_error ("Creating oldroot failed"); if (pivot_root (base_path, "oldroot")) die_with_error ("pivot_root"); if (chdir ("/") != 0) die_with_error ("chdir / (base path)"); if (is_privileged) { pid_t child; int privsep_sockets[2]; if (socketpair (AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, privsep_sockets) != 0) die_with_error ("Can't create privsep socket"); child = fork (); if (child == -1) die_with_error ("Can't fork unprivileged helper"); if (child == 0) { /* Unprivileged setup process */ drop_privs (FALSE); close (privsep_sockets[0]); setup_newroot (opt_unshare_pid, privsep_sockets[1]); exit (0); } else { int status; uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */ uint32_t op, flags; const char *arg1, *arg2; cleanup_fd int unpriv_socket = -1; unpriv_socket = privsep_sockets[0]; close (privsep_sockets[1]); do { op = read_priv_sec_op (unpriv_socket, buffer, sizeof (buffer), &flags, &arg1, &arg2); privileged_op (-1, op, flags, arg1, arg2); if (write (unpriv_socket, buffer, 1) != 1) die ("Can't write to op_socket"); } while (op != PRIV_SEP_OP_DONE); waitpid (child, &status, 0); /* Continue post setup */ } } else { setup_newroot (opt_unshare_pid, -1); } close_ops_fd (); /* The old root better be rprivate or we will send unmount events to the parent namespace */ if (mount ("oldroot", "oldroot", NULL, MS_REC | MS_PRIVATE, NULL) != 0) die_with_error ("Failed to make old root rprivate"); if (umount2 ("oldroot", MNT_DETACH)) die_with_error ("unmount old root"); /* This is our second pivot. It's like we're a Silicon Valley startup flush * with cash but short on ideas! * * We're aiming to make /newroot the real root, and get rid of /oldroot. To do * that we need a temporary place to store it before we can unmount it. */ { cleanup_fd int oldrootfd = open ("/", O_DIRECTORY | O_RDONLY); if (oldrootfd < 0) die_with_error ("can't open /"); if (chdir ("/newroot") != 0) die_with_error ("chdir /newroot"); /* While the documentation claims that put_old must be underneath * new_root, it is perfectly fine to use the same directory as the * kernel checks only if old_root is accessible from new_root. * * Both runc and LXC are using this "alternative" method for * setting up the root of the container: * * https://github.com/opencontainers/runc/blob/master/libcontainer/rootfs_linux.go#L671 * https://github.com/lxc/lxc/blob/master/src/lxc/conf.c#L1121 */ if (pivot_root (".", ".") != 0) die_with_error ("pivot_root(/newroot)"); if (fchdir (oldrootfd) < 0) die_with_error ("fchdir to oldroot"); if (umount2 (".", MNT_DETACH) < 0) die_with_error ("umount old root"); if (chdir ("/") != 0) die_with_error ("chdir /"); } if (opt_unshare_user && (ns_uid != opt_sandbox_uid || ns_gid != opt_sandbox_gid) && opt_userns_block_fd == -1) { /* Now that devpts is mounted and we've no need for mount permissions we can create a new userspace and map our uid 1:1 */ if (unshare (CLONE_NEWUSER)) die_with_error ("unshare user ns"); write_uid_gid_map (opt_sandbox_uid, ns_uid, opt_sandbox_gid, ns_gid, -1, FALSE, FALSE); } /* All privileged ops are done now, so drop caps we don't need */ drop_privs (!is_privileged); if (opt_block_fd != -1) { char b[1]; (void) TEMP_FAILURE_RETRY (read (opt_block_fd, b, 1)); close (opt_block_fd); } if (opt_seccomp_fd != -1) { seccomp_data = load_file_data (opt_seccomp_fd, &seccomp_len); if (seccomp_data == NULL) die_with_error ("Can't read seccomp data"); if (seccomp_len % 8 != 0) die ("Invalid seccomp data, must be multiple of 8"); seccomp_prog.len = seccomp_len / 8; seccomp_prog.filter = (struct sock_filter *) seccomp_data; close (opt_seccomp_fd); } umask (old_umask); new_cwd = "/"; if (opt_chdir_path) { if (chdir (opt_chdir_path)) die_with_error ("Can't chdir to %s", opt_chdir_path); new_cwd = opt_chdir_path; } else if (chdir (old_cwd) == 0) { /* If the old cwd is mapped in the sandbox, go there */ new_cwd = old_cwd; } else { /* If the old cwd is not mapped, go to home */ const char *home = getenv ("HOME"); if (home != NULL && chdir (home) == 0) new_cwd = home; } xsetenv ("PWD", new_cwd, 1); free (old_cwd); if (opt_new_session && setsid () == (pid_t) -1) die_with_error ("setsid"); if (label_exec (opt_exec_label) == -1) die_with_error ("label_exec %s", argv[0]); __debug__ (("forking for child\n")); if (!opt_as_pid_1 && (opt_unshare_pid || lock_files != NULL || opt_sync_fd != -1)) { /* We have to have a pid 1 in the pid namespace, because * otherwise we'll get a bunch of zombies as nothing reaps * them. Alternatively if we're using sync_fd or lock_files we * need some process to own these. */ pid = fork (); if (pid == -1) die_with_error ("Can't fork for pid 1"); if (pid != 0) { drop_all_caps (FALSE); /* Close fds in pid 1, except stdio and optionally event_fd (for syncing pid 2 lifetime with monitor_child) and opt_sync_fd (for syncing sandbox lifetime with outside process). Any other fds will been passed on to the child though. */ { int dont_close[3]; int j = 0; if (event_fd != -1) dont_close[j++] = event_fd; if (opt_sync_fd != -1) dont_close[j++] = opt_sync_fd; dont_close[j++] = -1; fdwalk (proc_fd, close_extra_fds, dont_close); } return do_init (event_fd, pid, seccomp_data != NULL ? &seccomp_prog : NULL); } } __debug__ (("launch executable %s\n", argv[0])); if (proc_fd != -1) close (proc_fd); /* If we are using --as-pid-1 leak the sync fd into the sandbox. --sync-fd will still work unless the container process doesn't close this file. */ if (!opt_as_pid_1) { if (opt_sync_fd != -1) close (opt_sync_fd); } /* We want sigchild in the child */ unblock_sigchild (); /* Optionally bind our lifecycle */ handle_die_with_parent (); if (!is_privileged) set_ambient_capabilities (); /* Should be the last thing before execve() so that filters don't * need to handle anything above */ if (seccomp_data != NULL && prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &seccomp_prog) != 0) die_with_error ("prctl(PR_SET_SECCOMP)"); if (setup_finished_pipe[1] != -1) { char data = 0; res = write_to_fd (setup_finished_pipe[1], &data, 1); /* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0] we don't want to error out here */ } if (execvp (argv[0], argv) == -1) { if (setup_finished_pipe[1] != -1) { int saved_errno = errno; char data = 0; res = write_to_fd (setup_finished_pipe[1], &data, 1); errno = saved_errno; /* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0] we don't want to error out here */ } die_with_error ("execvp %s", argv[0]); } return 0; } Commit Message: Don't create our own temporary mount point for pivot_root An attacker could pre-create /tmp/.bubblewrap-$UID and make it a non-directory, non-symlink (in which case mounting our tmpfs would fail, causing denial of service), or make it a symlink under their control (potentially allowing bad things if the protected_symlinks sysctl is not enabled). Instead, temporarily mount the tmpfs on a directory that we are sure exists and is not attacker-controlled. /tmp (the directory itself, not a subdirectory) will do. Fixes: #304 Bug-Debian: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=923557 Signed-off-by: Simon McVittie <[email protected]> Closes: #305 Approved by: cgwalters CWE ID: CWE-20 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 modbus_reply(modbus_t *ctx, const uint8_t *req, int req_length, modbus_mapping_t *mb_mapping) { int offset; int slave; int function; uint16_t address; uint8_t rsp[MAX_MESSAGE_LENGTH]; int rsp_length = 0; sft_t sft; if (ctx == NULL) { errno = EINVAL; return -1; } offset = ctx->backend->header_length; slave = req[offset - 1]; function = req[offset]; address = (req[offset + 1] << 8) + req[offset + 2]; sft.slave = slave; sft.function = function; sft.t_id = ctx->backend->prepare_response_tid(req, &req_length); /* Data are flushed on illegal number of values errors. */ switch (function) { case MODBUS_FC_READ_COILS: case MODBUS_FC_READ_DISCRETE_INPUTS: { unsigned int is_input = (function == MODBUS_FC_READ_DISCRETE_INPUTS); int start_bits = is_input ? mb_mapping->start_input_bits : mb_mapping->start_bits; int nb_bits = is_input ? mb_mapping->nb_input_bits : mb_mapping->nb_bits; uint8_t *tab_bits = is_input ? mb_mapping->tab_input_bits : mb_mapping->tab_bits; const char * const name = is_input ? "read_input_bits" : "read_bits"; int nb = (req[offset + 3] << 8) + req[offset + 4]; /* The mapping can be shifted to reduce memory consumption and it doesn't always start at address zero. */ int mapping_address = address - start_bits; if (nb < 1 || MODBUS_MAX_READ_BITS < nb) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, "Illegal nb of values %d in %s (max %d)\n", nb, name, MODBUS_MAX_READ_BITS); } else if (mapping_address < 0 || (mapping_address + nb) > nb_bits) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in %s\n", mapping_address < 0 ? address : address + nb, name); } else { rsp_length = ctx->backend->build_response_basis(&sft, rsp); rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0); rsp_length = response_io_status(tab_bits, mapping_address, nb, rsp, rsp_length); } } break; case MODBUS_FC_READ_HOLDING_REGISTERS: case MODBUS_FC_READ_INPUT_REGISTERS: { unsigned int is_input = (function == MODBUS_FC_READ_INPUT_REGISTERS); int start_registers = is_input ? mb_mapping->start_input_registers : mb_mapping->start_registers; int nb_registers = is_input ? mb_mapping->nb_input_registers : mb_mapping->nb_registers; uint16_t *tab_registers = is_input ? mb_mapping->tab_input_registers : mb_mapping->tab_registers; const char * const name = is_input ? "read_input_registers" : "read_registers"; int nb = (req[offset + 3] << 8) + req[offset + 4]; /* The mapping can be shifted to reduce memory consumption and it doesn't always start at address zero. */ int mapping_address = address - start_registers; if (nb < 1 || MODBUS_MAX_READ_REGISTERS < nb) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, "Illegal nb of values %d in %s (max %d)\n", nb, name, MODBUS_MAX_READ_REGISTERS); } else if (mapping_address < 0 || (mapping_address + nb) > nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in %s\n", mapping_address < 0 ? address : address + nb, name); } else { int i; rsp_length = ctx->backend->build_response_basis(&sft, rsp); rsp[rsp_length++] = nb << 1; for (i = mapping_address; i < mapping_address + nb; i++) { rsp[rsp_length++] = tab_registers[i] >> 8; rsp[rsp_length++] = tab_registers[i] & 0xFF; } } } break; case MODBUS_FC_WRITE_SINGLE_COIL: { int mapping_address = address - mb_mapping->start_bits; if (mapping_address < 0 || mapping_address >= mb_mapping->nb_bits) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in write_bit\n", address); } else { int data = (req[offset + 3] << 8) + req[offset + 4]; if (data == 0xFF00 || data == 0x0) { mb_mapping->tab_bits[mapping_address] = data ? ON : OFF; memcpy(rsp, req, req_length); rsp_length = req_length; } else { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, FALSE, "Illegal data value 0x%0X in write_bit request at address %0X\n", data, address); } } } break; case MODBUS_FC_WRITE_SINGLE_REGISTER: { int mapping_address = address - mb_mapping->start_registers; if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in write_register\n", address); } else { int data = (req[offset + 3] << 8) + req[offset + 4]; mb_mapping->tab_registers[mapping_address] = data; memcpy(rsp, req, req_length); rsp_length = req_length; } } break; case MODBUS_FC_WRITE_MULTIPLE_COILS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; int mapping_address = address - mb_mapping->start_bits; if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb) { /* May be the indication has been truncated on reading because of * invalid address (eg. nb is 0 but the request contains values to * write) so it's necessary to flush. */ rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, "Illegal number of values %d in write_bits (max %d)\n", nb, MODBUS_MAX_WRITE_BITS); } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_bits) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in write_bits\n", mapping_address < 0 ? address : address + nb); } else { /* 6 = byte count */ modbus_set_bits_from_bytes(mb_mapping->tab_bits, mapping_address, nb, &req[offset + 6]); rsp_length = ctx->backend->build_response_basis(&sft, rsp); /* 4 to copy the bit address (2) and the quantity of bits */ memcpy(rsp + rsp_length, req + rsp_length, 4); rsp_length += 4; } } break; case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; int mapping_address = address - mb_mapping->start_registers; if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, "Illegal number of values %d in write_registers (max %d)\n", nb, MODBUS_MAX_WRITE_REGISTERS); } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in write_registers\n", mapping_address < 0 ? address : address + nb); } else { int i, j; for (i = mapping_address, j = 6; i < mapping_address + nb; i++, j += 2) { /* 6 and 7 = first value */ mb_mapping->tab_registers[i] = (req[offset + j] << 8) + req[offset + j + 1]; } rsp_length = ctx->backend->build_response_basis(&sft, rsp); /* 4 to copy the address (2) and the no. of registers */ memcpy(rsp + rsp_length, req + rsp_length, 4); rsp_length += 4; } } break; case MODBUS_FC_REPORT_SLAVE_ID: { int str_len; int byte_count_pos; rsp_length = ctx->backend->build_response_basis(&sft, rsp); /* Skip byte count for now */ byte_count_pos = rsp_length++; rsp[rsp_length++] = _REPORT_SLAVE_ID; /* Run indicator status to ON */ rsp[rsp_length++] = 0xFF; /* LMB + length of LIBMODBUS_VERSION_STRING */ str_len = 3 + strlen(LIBMODBUS_VERSION_STRING); memcpy(rsp + rsp_length, "LMB" LIBMODBUS_VERSION_STRING, str_len); rsp_length += str_len; rsp[byte_count_pos] = rsp_length - byte_count_pos - 1; } break; case MODBUS_FC_READ_EXCEPTION_STATUS: if (ctx->debug) { fprintf(stderr, "FIXME Not implemented\n"); } errno = ENOPROTOOPT; return -1; break; case MODBUS_FC_MASK_WRITE_REGISTER: { int mapping_address = address - mb_mapping->start_registers; if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in write_register\n", address); } else { uint16_t data = mb_mapping->tab_registers[mapping_address]; uint16_t and = (req[offset + 3] << 8) + req[offset + 4]; uint16_t or = (req[offset + 5] << 8) + req[offset + 6]; data = (data & and) | (or & (~and)); mb_mapping->tab_registers[mapping_address] = data; memcpy(rsp, req, req_length); rsp_length = req_length; } } break; case MODBUS_FC_WRITE_AND_READ_REGISTERS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; uint16_t address_write = (req[offset + 5] << 8) + req[offset + 6]; int nb_write = (req[offset + 7] << 8) + req[offset + 8]; int nb_write_bytes = req[offset + 9]; int mapping_address = address - mb_mapping->start_registers; int mapping_address_write = address_write - mb_mapping->start_registers; if (nb_write < 1 || MODBUS_MAX_WR_WRITE_REGISTERS < nb_write || nb < 1 || MODBUS_MAX_WR_READ_REGISTERS < nb || nb_write_bytes != nb_write * 2) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, "Illegal nb of values (W%d, R%d) in write_and_read_registers (max W%d, R%d)\n", nb_write, nb, MODBUS_MAX_WR_WRITE_REGISTERS, MODBUS_MAX_WR_READ_REGISTERS); } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_registers || mapping_address < 0 || (mapping_address_write + nb_write) > mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data read address 0x%0X or write address 0x%0X write_and_read_registers\n", mapping_address < 0 ? address : address + nb, mapping_address_write < 0 ? address_write : address_write + nb_write); } else { int i, j; rsp_length = ctx->backend->build_response_basis(&sft, rsp); rsp[rsp_length++] = nb << 1; /* Write first. 10 and 11 are the offset of the first values to write */ for (i = mapping_address_write, j = 10; i < mapping_address_write + nb_write; i++, j += 2) { mb_mapping->tab_registers[i] = (req[offset + j] << 8) + req[offset + j + 1]; } /* and read the data for the response */ for (i = mapping_address; i < mapping_address + nb; i++) { rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8; rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF; } } } break; default: rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, rsp, TRUE, "Unknown Modbus function code: 0x%0X\n", function); break; } /* Suppress any responses when the request was a broadcast */ return (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU && slave == MODBUS_BROADCAST_ADDRESS) ? 0 : send_msg(ctx, rsp, rsp_length); } Commit Message: Fix VD-1301 and VD-1302 vulnerabilities This patch was contributed by Maor Vermucht and Or Peles from VDOO Connected Trust. CWE ID: CWE-125 Target: 1 Example 2: Code: bool Document::NeedsLayoutTreeUpdateForNode(const Node& node) const { if (!node.CanParticipateInFlatTree()) return false; if (!NeedsLayoutTreeUpdate()) return false; if (!node.isConnected()) return false; if (NeedsFullLayoutTreeUpdate() || node.NeedsStyleRecalc() || node.NeedsStyleInvalidation()) return true; for (const ContainerNode* ancestor = LayoutTreeBuilderTraversal::Parent(node); ancestor; ancestor = LayoutTreeBuilderTraversal::Parent(*ancestor)) { if (ancestor->NeedsStyleRecalc() || ancestor->NeedsStyleInvalidation() || ancestor->NeedsAdjacentStyleRecalc()) return true; } return false; } Commit Message: Inherit CSP when we inherit the security origin This prevents attacks that use main window navigation to get out of the existing csp constraints such as the related bug Bug: 747847 Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8 Reviewed-on: https://chromium-review.googlesource.com/592027 Reviewed-by: Mike West <[email protected]> Commit-Queue: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#492333} CWE ID: CWE-732 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: ssh_session(void) { int type; int interactive = 0; int have_tty = 0; struct winsize ws; char *cp; const char *display; /* Enable compression if requested. */ if (options.compression) { options.compression_level); if (options.compression_level < 1 || options.compression_level > 9) fatal("Compression level must be from 1 (fast) to " "9 (slow, best)."); /* Send the request. */ packet_start(SSH_CMSG_REQUEST_COMPRESSION); packet_put_int(options.compression_level); packet_send(); packet_write_wait(); type = packet_read(); if (type == SSH_SMSG_SUCCESS) packet_start_compression(options.compression_level); else if (type == SSH_SMSG_FAILURE) logit("Warning: Remote host refused compression."); else packet_disconnect("Protocol error waiting for " "compression response."); } /* Allocate a pseudo tty if appropriate. */ if (tty_flag) { debug("Requesting pty."); /* Start the packet. */ packet_start(SSH_CMSG_REQUEST_PTY); /* Store TERM in the packet. There is no limit on the length of the string. */ cp = getenv("TERM"); if (!cp) cp = ""; packet_put_cstring(cp); /* Store window size in the packet. */ if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0) memset(&ws, 0, sizeof(ws)); packet_put_int((u_int)ws.ws_row); packet_put_int((u_int)ws.ws_col); packet_put_int((u_int)ws.ws_xpixel); packet_put_int((u_int)ws.ws_ypixel); /* Store tty modes in the packet. */ tty_make_modes(fileno(stdin), NULL); /* Send the packet, and wait for it to leave. */ packet_send(); packet_write_wait(); /* Read response from the server. */ type = packet_read(); if (type == SSH_SMSG_SUCCESS) { interactive = 1; have_tty = 1; } else if (type == SSH_SMSG_FAILURE) logit("Warning: Remote host failed or refused to " "allocate a pseudo tty."); else packet_disconnect("Protocol error waiting for pty " "request response."); } /* Request X11 forwarding if enabled and DISPLAY is set. */ display = getenv("DISPLAY"); display = getenv("DISPLAY"); if (display == NULL && options.forward_x11) debug("X11 forwarding requested but DISPLAY not set"); if (options.forward_x11 && display != NULL) { char *proto, *data; /* Get reasonable local authentication information. */ client_x11_get_proto(display, options.xauth_location, options.forward_x11_trusted, options.forward_x11_timeout, &proto, &data); /* Request forwarding with authentication spoofing. */ debug("Requesting X11 forwarding with authentication " "spoofing."); /* Request forwarding with authentication spoofing. */ debug("Requesting X11 forwarding with authentication " "spoofing."); x11_request_forwarding_with_spoofing(0, display, proto, data, 0); /* Read response from the server. */ type = packet_read(); if (type == SSH_SMSG_SUCCESS) { interactive = 1; } else if (type == SSH_SMSG_FAILURE) { logit("Warning: Remote host denied X11 forwarding."); } else { packet_disconnect("Protocol error waiting for X11 " "forwarding"); } } /* Tell the packet module whether this is an interactive session. */ packet_set_interactive(interactive, options.ip_qos_interactive, options.ip_qos_bulk); /* Request authentication agent forwarding if appropriate. */ check_agent_present(); if (options.forward_agent) { debug("Requesting authentication agent forwarding."); auth_request_forwarding(); /* Read response from the server. */ type = packet_read(); packet_check_eom(); if (type != SSH_SMSG_SUCCESS) logit("Warning: Remote host denied authentication agent forwarding."); } /* Initiate port forwardings. */ ssh_init_stdio_forwarding(); ssh_init_forwarding(); /* Execute a local command */ if (options.local_command != NULL && options.permit_local_command) ssh_local_cmd(options.local_command); /* * If requested and we are not interested in replies to remote * forwarding requests, then let ssh continue in the background. */ if (fork_after_authentication_flag) { if (options.exit_on_forward_failure && options.num_remote_forwards > 0) { debug("deferring postauth fork until remote forward " "confirmation received"); } else fork_postauth(); } /* * If a command was specified on the command line, execute the * command now. Otherwise request the server to start a shell. */ if (buffer_len(&command) > 0) { int len = buffer_len(&command); if (len > 900) len = 900; debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command)); packet_start(SSH_CMSG_EXEC_CMD); packet_put_string(buffer_ptr(&command), buffer_len(&command)); packet_send(); packet_write_wait(); } else { debug("Requesting shell."); packet_start(SSH_CMSG_EXEC_SHELL); packet_send(); packet_write_wait(); } /* Enter the interactive session. */ return client_loop(have_tty, tty_flag ? options.escape_char : SSH_ESCAPECHAR_NONE, 0); } Commit Message: CWE ID: CWE-254 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: void ChromeContentRendererClient::RenderThreadStarted() { chrome_observer_.reset(new ChromeRenderProcessObserver()); extension_dispatcher_.reset(new ExtensionDispatcher()); histogram_snapshots_.reset(new RendererHistogramSnapshots()); net_predictor_.reset(new RendererNetPredictor()); spellcheck_.reset(new SpellCheck()); visited_link_slave_.reset(new VisitedLinkSlave()); #if defined(ENABLE_SAFE_BROWSING) phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create()); #endif RenderThread* thread = RenderThread::current(); thread->AddFilter(new DevToolsAgentFilter()); thread->AddObserver(chrome_observer_.get()); thread->AddObserver(extension_dispatcher_.get()); thread->AddObserver(histogram_snapshots_.get()); #if defined(ENABLE_SAFE_BROWSING) thread->AddObserver(phishing_classifier_.get()); #endif thread->AddObserver(spellcheck_.get()); thread->AddObserver(visited_link_slave_.get()); thread->RegisterExtension(extensions_v8::ExternalExtension::Get()); thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get()); thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get()); v8::Extension* search_extension = extensions_v8::SearchExtension::Get(); if (search_extension) thread->RegisterExtension(search_extension); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kDomAutomationController)) { thread->RegisterExtension(DomAutomationV8Extension::Get()); } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableIPCFuzzing)) { thread->channel()->set_outgoing_message_filter(LoadExternalIPCFuzzer()); } WebString chrome_ui_scheme(ASCIIToUTF16(chrome::kChromeUIScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_ui_scheme); WebString dev_tools_scheme(ASCIIToUTF16(chrome::kChromeDevToolsScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(dev_tools_scheme); WebString internal_scheme(ASCIIToUTF16(chrome::kChromeInternalScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(internal_scheme); WebString extension_scheme(ASCIIToUTF16(chrome::kExtensionScheme)); WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme); } Commit Message: DevTools: move DevToolsAgent/Client into content. BUG=84078 TEST= Review URL: http://codereview.chromium.org/7461019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: horizontalDifference8(unsigned char *ip, int n, int stride, unsigned short *wp, uint16 *From8) { register int r1, g1, b1, a1, r2, g2, b2, a2, mask; #undef CLAMP #define CLAMP(v) (From8[(v)]) mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1; wp += 3; ip += 3; } } else if (stride == 4) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1; a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1; wp += 4; ip += 4; } } else { REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++) n -= stride; while (n > 0) { REPEAT(stride, wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask); wp++; ip++) n -= stride; } } } } Commit Message: * libtiff/tif_pixarlog.c, libtiff/tif_luv.c: fix heap-based buffer overflow on generation of PixarLog / LUV compressed files, with ColorMap, TransferFunction attached and nasty plays with bitspersample. The fix for LUV has not been tested, but suffers from the same kind of issue of PixarLog. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2604 CWE ID: CWE-125 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 lppTransposer (HANDLE_SBR_LPP_TRANS hLppTrans, /*!< Handle of lpp transposer */ QMF_SCALE_FACTOR *sbrScaleFactor, /*!< Scaling factors */ FIXP_DBL **qmfBufferReal, /*!< Pointer to pointer to real part of subband samples (source) */ FIXP_DBL *degreeAlias, /*!< Vector for results of aliasing estimation */ FIXP_DBL **qmfBufferImag, /*!< Pointer to pointer to imaginary part of subband samples (source) */ const int useLP, const int timeStep, /*!< Time step of envelope */ const int firstSlotOffs, /*!< Start position in time */ const int lastSlotOffs, /*!< Number of overlap-slots into next frame */ const int nInvfBands, /*!< Number of bands for inverse filtering */ INVF_MODE *sbr_invf_mode, /*!< Current inverse filtering modes */ INVF_MODE *sbr_invf_mode_prev /*!< Previous inverse filtering modes */ ) { INT bwIndex[MAX_NUM_PATCHES]; FIXP_DBL bwVector[MAX_NUM_PATCHES]; /*!< pole moving factors */ int i; int loBand, start, stop; TRANSPOSER_SETTINGS *pSettings = hLppTrans->pSettings; PATCH_PARAM *patchParam = pSettings->patchParam; int patch; FIXP_SGL alphar[LPC_ORDER], a0r, a1r; FIXP_SGL alphai[LPC_ORDER], a0i=0, a1i=0; FIXP_SGL bw = FL2FXCONST_SGL(0.0f); int autoCorrLength; FIXP_DBL k1, k1_below=0, k1_below2=0; ACORR_COEFS ac; int startSample; int stopSample; int stopSampleClear; int comLowBandScale; int ovLowBandShift; int lowBandShift; /* int ovHighBandShift;*/ int targetStopBand; alphai[0] = FL2FXCONST_SGL(0.0f); alphai[1] = FL2FXCONST_SGL(0.0f); startSample = firstSlotOffs * timeStep; stopSample = pSettings->nCols + lastSlotOffs * timeStep; inverseFilteringLevelEmphasis(hLppTrans, nInvfBands, sbr_invf_mode, sbr_invf_mode_prev, bwVector); stopSampleClear = stopSample; autoCorrLength = pSettings->nCols + pSettings->overlap; /* Set upper subbands to zero: This is required in case that the patches do not cover the complete highband (because the last patch would be too short). Possible optimization: Clearing bands up to usb would be sufficient here. */ targetStopBand = patchParam[pSettings->noOfPatches-1].targetStartBand + patchParam[pSettings->noOfPatches-1].numBandsInPatch; int memSize = ((64) - targetStopBand) * sizeof(FIXP_DBL); if (!useLP) { for (i = startSample; i < stopSampleClear; i++) { FDKmemclear(&qmfBufferReal[i][targetStopBand], memSize); FDKmemclear(&qmfBufferImag[i][targetStopBand], memSize); } } else for (i = startSample; i < stopSampleClear; i++) { FDKmemclear(&qmfBufferReal[i][targetStopBand], memSize); } /* init bwIndex for each patch */ FDKmemclear(bwIndex, pSettings->noOfPatches*sizeof(INT)); /* Calc common low band scale factor */ comLowBandScale = fixMin(sbrScaleFactor->ov_lb_scale,sbrScaleFactor->lb_scale); ovLowBandShift = sbrScaleFactor->ov_lb_scale - comLowBandScale; lowBandShift = sbrScaleFactor->lb_scale - comLowBandScale; /* ovHighBandShift = firstSlotOffs == 0 ? ovLowBandShift:0;*/ /* outer loop over bands to do analysis only once for each band */ if (!useLP) { start = pSettings->lbStartPatching; stop = pSettings->lbStopPatching; } else { start = fixMax(1, pSettings->lbStartPatching - 2); stop = patchParam[0].targetStartBand; } for ( loBand = start; loBand < stop; loBand++ ) { FIXP_DBL lowBandReal[(((1024)/(32))+(6))+LPC_ORDER]; FIXP_DBL *plowBandReal = lowBandReal; FIXP_DBL **pqmfBufferReal = qmfBufferReal; FIXP_DBL lowBandImag[(((1024)/(32))+(6))+LPC_ORDER]; FIXP_DBL *plowBandImag = lowBandImag; FIXP_DBL **pqmfBufferImag = qmfBufferImag; int resetLPCCoeffs=0; int dynamicScale = DFRACT_BITS-1-LPC_SCALE_FACTOR; int acDetScale = 0; /* scaling of autocorrelation determinant */ for(i=0;i<LPC_ORDER;i++){ *plowBandReal++ = hLppTrans->lpcFilterStatesReal[i][loBand]; if (!useLP) *plowBandImag++ = hLppTrans->lpcFilterStatesImag[i][loBand]; } /* Take old slope length qmf slot source values out of (overlap)qmf buffer */ if (!useLP) { for(i=0;i<pSettings->nCols+pSettings->overlap;i++){ *plowBandReal++ = (*pqmfBufferReal++)[loBand]; *plowBandImag++ = (*pqmfBufferImag++)[loBand]; } } else { /* pSettings->overlap is always even */ FDK_ASSERT((pSettings->overlap & 1) == 0); for(i=0;i<((pSettings->overlap+pSettings->nCols)>>1);i++) { *plowBandReal++ = (*pqmfBufferReal++)[loBand]; *plowBandReal++ = (*pqmfBufferReal++)[loBand]; } if (pSettings->nCols & 1) { *plowBandReal++ = (*pqmfBufferReal++)[loBand]; } } /* Determine dynamic scaling value. */ dynamicScale = fixMin(dynamicScale, getScalefactor(lowBandReal, LPC_ORDER+pSettings->overlap) + ovLowBandShift); dynamicScale = fixMin(dynamicScale, getScalefactor(&lowBandReal[LPC_ORDER+pSettings->overlap], pSettings->nCols) + lowBandShift); if (!useLP) { dynamicScale = fixMin(dynamicScale, getScalefactor(lowBandImag, LPC_ORDER+pSettings->overlap) + ovLowBandShift); dynamicScale = fixMin(dynamicScale, getScalefactor(&lowBandImag[LPC_ORDER+pSettings->overlap], pSettings->nCols) + lowBandShift); } dynamicScale = fixMax(0, dynamicScale-1); /* one additional bit headroom to prevent -1.0 */ /* Scale temporal QMF buffer. */ scaleValues(&lowBandReal[0], LPC_ORDER+pSettings->overlap, dynamicScale-ovLowBandShift); scaleValues(&lowBandReal[LPC_ORDER+pSettings->overlap], pSettings->nCols, dynamicScale-lowBandShift); if (!useLP) { scaleValues(&lowBandImag[0], LPC_ORDER+pSettings->overlap, dynamicScale-ovLowBandShift); scaleValues(&lowBandImag[LPC_ORDER+pSettings->overlap], pSettings->nCols, dynamicScale-lowBandShift); } if (!useLP) { acDetScale += autoCorr2nd_cplx(&ac, lowBandReal+LPC_ORDER, lowBandImag+LPC_ORDER, autoCorrLength); } else { acDetScale += autoCorr2nd_real(&ac, lowBandReal+LPC_ORDER, autoCorrLength); } /* Examine dynamic of determinant in autocorrelation. */ acDetScale += 2*(comLowBandScale + dynamicScale); acDetScale *= 2; /* two times reflection coefficent scaling */ acDetScale += ac.det_scale; /* ac scaling of determinant */ /* In case of determinant < 10^-38, resetLPCCoeffs=1 has to be enforced. */ if (acDetScale>126 ) { resetLPCCoeffs = 1; } alphar[1] = FL2FXCONST_SGL(0.0f); if (!useLP) alphai[1] = FL2FXCONST_SGL(0.0f); if (ac.det != FL2FXCONST_DBL(0.0f)) { FIXP_DBL tmp,absTmp,absDet; absDet = fixp_abs(ac.det); if (!useLP) { tmp = ( fMultDiv2(ac.r01r,ac.r12r) >> (LPC_SCALE_FACTOR-1) ) - ( (fMultDiv2(ac.r01i,ac.r12i) + fMultDiv2(ac.r02r,ac.r11r)) >> (LPC_SCALE_FACTOR-1) ); } else { tmp = ( fMultDiv2(ac.r01r,ac.r12r) >> (LPC_SCALE_FACTOR-1) ) - ( fMultDiv2(ac.r02r,ac.r11r) >> (LPC_SCALE_FACTOR-1) ); } absTmp = fixp_abs(tmp); /* Quick check: is first filter coeff >= 1(4) */ { INT scale; FIXP_DBL result = fDivNorm(absTmp, absDet, &scale); scale = scale+ac.det_scale; if ( (scale > 0) && (result >= (FIXP_DBL)MAXVAL_DBL>>scale) ) { resetLPCCoeffs = 1; } else { alphar[1] = FX_DBL2FX_SGL(scaleValue(result,scale)); if((tmp<FL2FX_DBL(0.0f)) ^ (ac.det<FL2FX_DBL(0.0f))) { alphar[1] = -alphar[1]; } } } if (!useLP) { tmp = ( fMultDiv2(ac.r01i,ac.r12r) >> (LPC_SCALE_FACTOR-1) ) + ( (fMultDiv2(ac.r01r,ac.r12i) - (FIXP_DBL)fMultDiv2(ac.r02i,ac.r11r)) >> (LPC_SCALE_FACTOR-1) ) ; absTmp = fixp_abs(tmp); /* Quick check: is second filter coeff >= 1(4) */ { INT scale; FIXP_DBL result = fDivNorm(absTmp, absDet, &scale); scale = scale+ac.det_scale; if ( (scale > 0) && (result >= /*FL2FXCONST_DBL(1.f)*/ (FIXP_DBL)MAXVAL_DBL>>scale) ) { resetLPCCoeffs = 1; } else { alphai[1] = FX_DBL2FX_SGL(scaleValue(result,scale)); if((tmp<FL2FX_DBL(0.0f)) ^ (ac.det<FL2FX_DBL(0.0f))) { alphai[1] = -alphai[1]; } } } } } alphar[0] = FL2FXCONST_SGL(0.0f); if (!useLP) alphai[0] = FL2FXCONST_SGL(0.0f); if ( ac.r11r != FL2FXCONST_DBL(0.0f) ) { /* ac.r11r is always >=0 */ FIXP_DBL tmp,absTmp; if (!useLP) { tmp = (ac.r01r>>(LPC_SCALE_FACTOR+1)) + (fMultDiv2(alphar[1],ac.r12r) + fMultDiv2(alphai[1],ac.r12i)); } else { if(ac.r01r>=FL2FXCONST_DBL(0.0f)) tmp = (ac.r01r>>(LPC_SCALE_FACTOR+1)) + fMultDiv2(alphar[1],ac.r12r); else tmp = -((-ac.r01r)>>(LPC_SCALE_FACTOR+1)) + fMultDiv2(alphar[1],ac.r12r); } absTmp = fixp_abs(tmp); /* Quick check: is first filter coeff >= 1(4) */ if (absTmp >= (ac.r11r>>1)) { resetLPCCoeffs=1; } else { INT scale; FIXP_DBL result = fDivNorm(absTmp, fixp_abs(ac.r11r), &scale); alphar[0] = FX_DBL2FX_SGL(scaleValue(result,scale+1)); if((tmp>FL2FX_DBL(0.0f)) ^ (ac.r11r<FL2FX_DBL(0.0f))) alphar[0] = -alphar[0]; } if (!useLP) { tmp = (ac.r01i>>(LPC_SCALE_FACTOR+1)) + (fMultDiv2(alphai[1],ac.r12r) - fMultDiv2(alphar[1],ac.r12i)); absTmp = fixp_abs(tmp); /* Quick check: is second filter coeff >= 1(4) */ if (absTmp >= (ac.r11r>>1)) { resetLPCCoeffs=1; } else { INT scale; FIXP_DBL result = fDivNorm(absTmp, fixp_abs(ac.r11r), &scale); alphai[0] = FX_DBL2FX_SGL(scaleValue(result,scale+1)); if((tmp>FL2FX_DBL(0.0f)) ^ (ac.r11r<FL2FX_DBL(0.0f))) alphai[0] = -alphai[0]; } } } if (!useLP) { /* Now check the quadratic criteria */ if( (fMultDiv2(alphar[0],alphar[0]) + fMultDiv2(alphai[0],alphai[0])) >= FL2FXCONST_DBL(0.5f) ) resetLPCCoeffs=1; if( (fMultDiv2(alphar[1],alphar[1]) + fMultDiv2(alphai[1],alphai[1])) >= FL2FXCONST_DBL(0.5f) ) resetLPCCoeffs=1; } if(resetLPCCoeffs){ alphar[0] = FL2FXCONST_SGL(0.0f); alphar[1] = FL2FXCONST_SGL(0.0f); if (!useLP) { alphai[0] = FL2FXCONST_SGL(0.0f); alphai[1] = FL2FXCONST_SGL(0.0f); } } if (useLP) { /* Aliasing detection */ if(ac.r11r==FL2FXCONST_DBL(0.0f)) { k1 = FL2FXCONST_DBL(0.0f); } else { if ( fixp_abs(ac.r01r) >= fixp_abs(ac.r11r) ) { if ( fMultDiv2(ac.r01r,ac.r11r) < FL2FX_DBL(0.0f)) { k1 = (FIXP_DBL)MAXVAL_DBL /*FL2FXCONST_SGL(1.0f)*/; }else { /* Since this value is squared later, it must not ever become -1.0f. */ k1 = (FIXP_DBL)(MINVAL_DBL+1) /*FL2FXCONST_SGL(-1.0f)*/; } } else { INT scale; FIXP_DBL result = fDivNorm(fixp_abs(ac.r01r), fixp_abs(ac.r11r), &scale); k1 = scaleValue(result,scale); if(!((ac.r01r<FL2FX_DBL(0.0f)) ^ (ac.r11r<FL2FX_DBL(0.0f)))) { k1 = -k1; } } } if(loBand > 1){ /* Check if the gain should be locked */ FIXP_DBL deg = /*FL2FXCONST_DBL(1.0f)*/ (FIXP_DBL)MAXVAL_DBL - fPow2(k1_below); degreeAlias[loBand] = FL2FXCONST_DBL(0.0f); if (((loBand & 1) == 0) && (k1 < FL2FXCONST_DBL(0.0f))){ if (k1_below < FL2FXCONST_DBL(0.0f)) { /* 2-Ch Aliasing Detection */ degreeAlias[loBand] = (FIXP_DBL)MAXVAL_DBL /*FL2FXCONST_DBL(1.0f)*/; if ( k1_below2 > FL2FXCONST_DBL(0.0f) ) { /* 3-Ch Aliasing Detection */ degreeAlias[loBand-1] = deg; } } else if ( k1_below2 > FL2FXCONST_DBL(0.0f) ) { /* 3-Ch Aliasing Detection */ degreeAlias[loBand] = deg; } } if (((loBand & 1) == 1) && (k1 > FL2FXCONST_DBL(0.0f))){ if (k1_below > FL2FXCONST_DBL(0.0f)) { /* 2-CH Aliasing Detection */ degreeAlias[loBand] = (FIXP_DBL)MAXVAL_DBL /*FL2FXCONST_DBL(1.0f)*/; if ( k1_below2 < FL2FXCONST_DBL(0.0f) ) { /* 3-CH Aliasing Detection */ degreeAlias[loBand-1] = deg; } } else if ( k1_below2 < FL2FXCONST_DBL(0.0f) ) { /* 3-CH Aliasing Detection */ degreeAlias[loBand] = deg; } } } /* remember k1 values of the 2 QMF channels below the current channel */ k1_below2 = k1_below; k1_below = k1; } patch = 0; while ( patch < pSettings->noOfPatches ) { /* inner loop over every patch */ int hiBand = loBand + patchParam[patch].targetBandOffs; if ( loBand < patchParam[patch].sourceStartBand || loBand >= patchParam[patch].sourceStopBand ) { /* Lowband not in current patch - proceed */ patch++; continue; } FDK_ASSERT( hiBand < (64) ); /* bwIndex[patch] is already initialized with value from previous band inside this patch */ while (hiBand >= pSettings->bwBorders[bwIndex[patch]]) bwIndex[patch]++; /* Filter Step 2: add the left slope with the current filter to the buffer pure source values are already in there */ bw = FX_DBL2FX_SGL(bwVector[bwIndex[patch]]); a0r = FX_DBL2FX_SGL(fMult(bw,alphar[0])); /* Apply current bandwidth expansion factor */ if (!useLP) a0i = FX_DBL2FX_SGL(fMult(bw,alphai[0])); bw = FX_DBL2FX_SGL(fPow2(bw)); a1r = FX_DBL2FX_SGL(fMult(bw,alphar[1])); if (!useLP) a1i = FX_DBL2FX_SGL(fMult(bw,alphai[1])); /* Filter Step 3: insert the middle part which won't be windowed */ if ( bw <= FL2FXCONST_SGL(0.0f) ) { if (!useLP) { int descale = fixMin(DFRACT_BITS-1, (LPC_SCALE_FACTOR+dynamicScale)); for(i = startSample; i < stopSample; i++ ) { qmfBufferReal[i][hiBand] = lowBandReal[LPC_ORDER+i]>>descale; qmfBufferImag[i][hiBand] = lowBandImag[LPC_ORDER+i]>>descale; } } else { int descale = fixMin(DFRACT_BITS-1, (LPC_SCALE_FACTOR+dynamicScale)); for(i = startSample; i < stopSample; i++ ) { qmfBufferReal[i][hiBand] = lowBandReal[LPC_ORDER+i]>>descale; } } } else { /* bw <= 0 */ if (!useLP) { int descale = fixMin(DFRACT_BITS-1, (LPC_SCALE_FACTOR+dynamicScale)); #ifdef FUNCTION_LPPTRANSPOSER_func1 lppTransposer_func1(lowBandReal+LPC_ORDER+startSample,lowBandImag+LPC_ORDER+startSample, qmfBufferReal+startSample,qmfBufferImag+startSample, stopSample-startSample, (int) hiBand, dynamicScale,descale, a0r, a0i, a1r, a1i); #else for(i = startSample; i < stopSample; i++ ) { FIXP_DBL accu1, accu2; accu1 = (fMultDiv2(a0r,lowBandReal[LPC_ORDER+i-1]) - fMultDiv2(a0i,lowBandImag[LPC_ORDER+i-1]) + fMultDiv2(a1r,lowBandReal[LPC_ORDER+i-2]) - fMultDiv2(a1i,lowBandImag[LPC_ORDER+i-2]))>>dynamicScale; accu2 = (fMultDiv2(a0i,lowBandReal[LPC_ORDER+i-1]) + fMultDiv2(a0r,lowBandImag[LPC_ORDER+i-1]) + fMultDiv2(a1i,lowBandReal[LPC_ORDER+i-2]) + fMultDiv2(a1r,lowBandImag[LPC_ORDER+i-2]))>>dynamicScale; qmfBufferReal[i][hiBand] = (lowBandReal[LPC_ORDER+i]>>descale) + (accu1<<1); qmfBufferImag[i][hiBand] = (lowBandImag[LPC_ORDER+i]>>descale) + (accu2<<1); } #endif } else { int descale = fixMin(DFRACT_BITS-1, (LPC_SCALE_FACTOR+dynamicScale)); FDK_ASSERT(dynamicScale >= 0); for(i = startSample; i < stopSample; i++ ) { FIXP_DBL accu1; accu1 = (fMultDiv2(a0r,lowBandReal[LPC_ORDER+i-1]) + fMultDiv2(a1r,lowBandReal[LPC_ORDER+i-2]))>>dynamicScale; qmfBufferReal[i][hiBand] = (lowBandReal[LPC_ORDER+i]>>descale) + (accu1<<1); } } } /* bw <= 0 */ patch++; } /* inner loop over patches */ /* * store the unmodified filter coefficients if there is * an overlapping envelope *****************************************************************/ } /* outer loop over bands (loBand) */ if (useLP) { for ( loBand = pSettings->lbStartPatching; loBand < pSettings->lbStopPatching; loBand++ ) { patch = 0; while ( patch < pSettings->noOfPatches ) { UCHAR hiBand = loBand + patchParam[patch].targetBandOffs; if ( loBand < patchParam[patch].sourceStartBand || loBand >= patchParam[patch].sourceStopBand || hiBand >= (64) /* Highband out of range (biterror) */ ) { /* Lowband not in current patch or highband out of range (might be caused by biterrors)- proceed */ patch++; continue; } if(hiBand != patchParam[patch].targetStartBand) degreeAlias[hiBand] = degreeAlias[loBand]; patch++; } }/* end for loop */ } for (i = 0; i < nInvfBands; i++ ) { hLppTrans->bwVectorOld[i] = bwVector[i]; } /* set high band scale factor */ sbrScaleFactor->hb_scale = comLowBandScale-(LPC_SCALE_FACTOR); } Commit Message: Fix out of bound memory access in lppTransposer In TRANSPOSER_SETTINGS, initialize the whole bwBorders array to a reasonable value to guarantee correct termination in while loop in lppTransposer function. This fixes the reported bug. For completeness: - clear the whole bwIndex array instead of noOfPatches entries only. - abort criterion in while loop to prevent potential infinite loop, and limit bwIndex[patch] to a valid range. Test: see bug for malicious content, decoded with "stagefright -s -a" Bug: 65280786 Change-Id: I16ed2e1c0f1601926239a652ca20a91284151843 (cherry picked from commit 6d3dd40e204bf550abcfa589bd9615df8778e118) 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: void InitOnIOThread(const std::string& mime_type) { PluginServiceImpl* plugin_service = PluginServiceImpl::GetInstance(); std::vector<WebPluginInfo> plugins; plugin_service->GetPluginInfoArray( GURL(), mime_type, false, &plugins, NULL); base::FilePath plugin_path; if (!plugins.empty()) // May be empty for some tests. plugin_path = plugins[0].path; DCHECK_CURRENTLY_ON(BrowserThread::IO); remove_start_time_ = base::Time::Now(); is_removing_ = true; AddRef(); PepperPluginInfo* pepper_info = plugin_service->GetRegisteredPpapiPluginInfo(plugin_path); if (pepper_info) { plugin_name_ = pepper_info->name; plugin_service->OpenChannelToPpapiBroker(0, plugin_path, this); } else { plugin_service->OpenChannelToNpapiPlugin( 0, 0, GURL(), GURL(), mime_type, this); } } Commit Message: Do not attempt to open a channel to a plugin in Plugin Data Remover if there are no plugins available. BUG=485886 Review URL: https://codereview.chromium.org/1144353003 Cr-Commit-Position: refs/heads/master@{#331168} CWE ID: Target: 1 Example 2: Code: perf_event_nmi_handler(struct notifier_block *self, unsigned long cmd, void *__args) { struct die_args *args = __args; unsigned int this_nmi; int handled; if (!atomic_read(&active_events)) return NOTIFY_DONE; switch (cmd) { case DIE_NMI: break; case DIE_NMIUNKNOWN: this_nmi = percpu_read(irq_stat.__nmi_count); if (this_nmi != __this_cpu_read(pmu_nmi.marked)) /* let the kernel handle the unknown nmi */ return NOTIFY_DONE; /* * This one is a PMU back-to-back nmi. Two events * trigger 'simultaneously' raising two back-to-back * NMIs. If the first NMI handles both, the latter * will be empty and daze the CPU. So, we drop it to * avoid false-positive 'unknown nmi' messages. */ return NOTIFY_STOP; default: return NOTIFY_DONE; } handled = x86_pmu.handle_irq(args->regs); if (!handled) return NOTIFY_DONE; this_nmi = percpu_read(irq_stat.__nmi_count); if ((handled > 1) || /* the next nmi could be a back-to-back nmi */ ((__this_cpu_read(pmu_nmi.marked) == this_nmi) && (__this_cpu_read(pmu_nmi.handled) > 1))) { /* * We could have two subsequent back-to-back nmis: The * first handles more than one counter, the 2nd * handles only one counter and the 3rd handles no * counter. * * This is the 2nd nmi because the previous was * handling more than one counter. We will mark the * next (3rd) and then drop it if unhandled. */ __this_cpu_write(pmu_nmi.marked, this_nmi + 1); __this_cpu_write(pmu_nmi.handled, handled); } return NOTIFY_STOP; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 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: ModuleExport void UnregisterFAXImage(void) { (void) UnregisterMagickInfo("FAX"); (void) UnregisterMagickInfo("G3"); } Commit Message: 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: virtual void SetUp() { const tuple<int, int, SubpelVarianceFunctionType>& params = this->GetParam(); log2width_ = get<0>(params); width_ = 1 << log2width_; log2height_ = get<1>(params); height_ = 1 << log2height_; subpel_variance_ = get<2>(params); rnd(ACMRandom::DeterministicSeed()); block_size_ = width_ * height_; src_ = reinterpret_cast<uint8_t *>(vpx_memalign(16, block_size_)); sec_ = reinterpret_cast<uint8_t *>(vpx_memalign(16, block_size_)); ref_ = new uint8_t[block_size_ + width_ + height_ + 1]; ASSERT_TRUE(src_ != NULL); ASSERT_TRUE(sec_ != NULL); ASSERT_TRUE(ref_ != NULL); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: static int mov_switch_root(AVFormatContext *s, int64_t target) { MOVContext *mov = s->priv_data; int i, j; int already_read = 0; if (avio_seek(s->pb, target, SEEK_SET) != target) { av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target); return AVERROR_INVALIDDATA; } mov->next_root_atom = 0; for (i = 0; i < mov->fragment_index_count; i++) { MOVFragmentIndex *index = mov->fragment_index_data[i]; int found = 0; for (j = 0; j < index->item_count; j++) { MOVFragmentIndexItem *item = &index->items[j]; if (found) { mov->next_root_atom = item->moof_offset; break; // Advance to next index in outer loop } else if (item->moof_offset == target) { index->current_item = FFMIN(j, index->current_item); if (item->headers_read) already_read = 1; item->headers_read = 1; found = 1; } } if (!found) index->current_item = 0; } if (already_read) return 0; mov->found_mdat = 0; if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 || avio_feof(s->pb)) return AVERROR_EOF; av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb)); return 1; } Commit Message: avformat/mov: Fix DoS in read_tfra() Fixes: Missing EOF check in loop No testcase Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-834 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 mpage_da_map_blocks(struct mpage_da_data *mpd) { int err, blks, get_blocks_flags; struct buffer_head new; sector_t next = mpd->b_blocknr; unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits; loff_t disksize = EXT4_I(mpd->inode)->i_disksize; handle_t *handle = NULL; /* * We consider only non-mapped and non-allocated blocks */ if ((mpd->b_state & (1 << BH_Mapped)) && !(mpd->b_state & (1 << BH_Delay)) && !(mpd->b_state & (1 << BH_Unwritten))) return 0; /* * If we didn't accumulate anything to write simply return */ if (!mpd->b_size) return 0; handle = ext4_journal_current_handle(); BUG_ON(!handle); /* * Call ext4_get_blocks() to allocate any delayed allocation * blocks, or to convert an uninitialized extent to be * initialized (in the case where we have written into * one or more preallocated blocks). * * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to * indicate that we are on the delayed allocation path. This * affects functions in many different parts of the allocation * call path. This flag exists primarily because we don't * want to change *many* call functions, so ext4_get_blocks() * will set the magic i_delalloc_reserved_flag once the * inode's allocation semaphore is taken. * * If the blocks in questions were delalloc blocks, set * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting * variables are updated after the blocks have been allocated. */ new.b_state = 0; get_blocks_flags = EXT4_GET_BLOCKS_CREATE; if (mpd->b_state & (1 << BH_Delay)) get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE; blks = ext4_get_blocks(handle, mpd->inode, next, max_blocks, &new, get_blocks_flags); if (blks < 0) { err = blks; /* * If get block returns with error we simply * return. Later writepage will redirty the page and * writepages will find the dirty page again */ if (err == -EAGAIN) return 0; if (err == -ENOSPC && ext4_count_free_blocks(mpd->inode->i_sb)) { mpd->retval = err; return 0; } /* * get block failure will cause us to loop in * writepages, because a_ops->writepage won't be able * to make progress. The page will be redirtied by * writepage and writepages will again try to write * the same. */ ext4_msg(mpd->inode->i_sb, KERN_CRIT, "delayed block allocation failed for inode %lu at " "logical offset %llu with max blocks %zd with " "error %d\n", mpd->inode->i_ino, (unsigned long long) next, mpd->b_size >> mpd->inode->i_blkbits, err); printk(KERN_CRIT "This should not happen!! " "Data will be lost\n"); if (err == -ENOSPC) { ext4_print_free_blocks(mpd->inode); } /* invalidate all the pages */ ext4_da_block_invalidatepages(mpd, next, mpd->b_size >> mpd->inode->i_blkbits); return err; } BUG_ON(blks == 0); new.b_size = (blks << mpd->inode->i_blkbits); if (buffer_new(&new)) __unmap_underlying_blocks(mpd->inode, &new); /* * If blocks are delayed marked, we need to * put actual blocknr and drop delayed bit */ if ((mpd->b_state & (1 << BH_Delay)) || (mpd->b_state & (1 << BH_Unwritten))) mpage_put_bnr_to_bhs(mpd, next, &new); if (ext4_should_order_data(mpd->inode)) { err = ext4_jbd2_file_inode(handle, mpd->inode); if (err) return err; } /* * Update on-disk size along with block allocation. */ disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits; if (disksize > i_size_read(mpd->inode)) disksize = i_size_read(mpd->inode); if (disksize > EXT4_I(mpd->inode)->i_disksize) { ext4_update_i_disksize(mpd->inode, disksize); return ext4_mark_inode_dirty(handle, mpd->inode); } return 0; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID: 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 MessageLoop::DoWork() { if (!nestable_tasks_allowed_) { return false; } for (;;) { ReloadWorkQueue(); if (work_queue_.empty()) break; do { PendingTask pending_task = std::move(work_queue_.front()); work_queue_.pop(); if (pending_task.task.IsCancelled()) { #if defined(OS_WIN) DecrementHighResTaskCountIfNeeded(pending_task); #endif } else if (!pending_task.delayed_run_time.is_null()) { int sequence_num = pending_task.sequence_num; TimeTicks delayed_run_time = pending_task.delayed_run_time; AddToDelayedWorkQueue(std::move(pending_task)); if (delayed_work_queue_.top().sequence_num == sequence_num) pump_->ScheduleDelayedWork(delayed_run_time); } else { if (DeferOrRunPendingTask(std::move(pending_task))) return true; } } while (!work_queue_.empty()); } return false; } Commit Message: Introduce RunLoop::Type::NESTABLE_TASKS_ALLOWED to replace MessageLoop::ScopedNestableTaskAllower. (as well as MessageLoop::SetNestableTasksAllowed()) Surveying usage: the scoped object is always instantiated right before RunLoop().Run(). The intent is really to allow nestable tasks in that RunLoop so it's better to explicitly label that RunLoop as such and it allows us to break the last dependency that forced some RunLoop users to use MessageLoop APIs. There's also the odd case of allowing nestable tasks for loops that are reentrant from a native task (without going through RunLoop), these are the minority but will have to be handled (after cleaning up the majority of cases that are RunLoop induced). As highlighted by robliao@ in https://chromium-review.googlesource.com/c/600517 (which was merged in this CL). [email protected] Bug: 750779 Change-Id: I43d122c93ec903cff3a6fe7b77ec461ea0656448 Reviewed-on: https://chromium-review.googlesource.com/594713 Commit-Queue: Gabriel Charette <[email protected]> Reviewed-by: Robert Liao <[email protected]> Reviewed-by: danakj <[email protected]> Cr-Commit-Position: refs/heads/master@{#492263} CWE ID: Target: 1 Example 2: Code: render_state_draw( RenderState state, const unsigned char* text, int idx, int x, int y, int width, int height ) { ColumnState column = &state->columns[idx]; const unsigned char* p = text; long load_flags = FT_LOAD_DEFAULT; FT_Face face = state->face; int left = x; int right = x + width; int bottom = y + height; int line_height; FT_UInt prev_glyph = 0; FT_Pos prev_rsb_delta = 0; FT_Pos x_origin = x << 6; HintMode rmode = column->hint_mode; if ( !face ) return; _render_state_rescale( state ); if ( column->use_lcd_filter ) FT_Library_SetLcdFilter( face->glyph->library, column->lcd_filter ); if ( column->use_custom_lcd_filter ) FT_Library_SetLcdFilterWeights( face->glyph->library, column->filter_weights ); y += state->size->metrics.ascender / 64; line_height = state->size->metrics.height / 64; if ( rmode == HINT_MODE_AUTOHINT ) load_flags = FT_LOAD_FORCE_AUTOHINT; if ( rmode == HINT_MODE_AUTOHINT_LIGHT ) load_flags = FT_LOAD_TARGET_LIGHT; if ( rmode == HINT_MODE_UNHINTED ) load_flags |= FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP; if ( !column->use_global_advance_width ) load_flags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH; for ( ; *p; p++ ) { FT_UInt gindex; FT_Error error; FT_GlyphSlot slot = face->glyph; FT_Bitmap* map = &slot->bitmap; int xmax; /* handle newlines */ if ( *p == 0x0A ) { if ( p[1] == 0x0D ) p++; x_origin = left << 6; y += line_height; prev_rsb_delta = 0; if ( y >= bottom ) break; continue; } else if ( *p == 0x0D ) { if ( p[1] == 0x0A ) p++; x_origin = left << 6; y += line_height; prev_rsb_delta = 0; if ( y >= bottom ) break; continue; } gindex = FT_Get_Char_Index( state->face, p[0] ); error = FT_Load_Glyph( face, gindex, load_flags ); if ( error ) continue; if ( column->use_kerning && gindex != 0 && prev_glyph != 0 ) { FT_Vector vec; FT_Int kerning_mode = FT_KERNING_DEFAULT; if ( rmode == HINT_MODE_UNHINTED ) kerning_mode = FT_KERNING_UNFITTED; FT_Get_Kerning( face, prev_glyph, gindex, kerning_mode, &vec ); x_origin += vec.x; } if ( column->use_deltas ) { if ( prev_rsb_delta - face->glyph->lsb_delta >= 32 ) x_origin -= 64; else if ( prev_rsb_delta - face->glyph->lsb_delta < -32 ) x_origin += 64; } prev_rsb_delta = face->glyph->rsb_delta; /* implement sub-pixel positining for un-hinted mode */ if ( rmode == HINT_MODE_UNHINTED && slot->format == FT_GLYPH_FORMAT_OUTLINE ) { FT_Pos shift = x_origin & 63; FT_Outline_Translate( &slot->outline, shift, 0 ); } if ( slot->format == FT_GLYPH_FORMAT_OUTLINE ) { FT_BBox cbox; FT_Outline_Get_CBox( &slot->outline, &cbox ); xmax = ( x_origin + cbox.xMax + 63 ) >> 6; FT_Render_Glyph( slot, column->use_lcd_filter ? FT_RENDER_MODE_LCD : FT_RENDER_MODE_NORMAL ); } else xmax = ( x_origin >> 6 ) + slot->bitmap_left + slot->bitmap.width; if ( xmax >= right ) { x = left; y += line_height; if ( y >= bottom ) break; x_origin = x << 6; prev_rsb_delta = 0; } { DisplayMode mode = DISPLAY_MODE_MONO; if ( slot->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY ) mode = DISPLAY_MODE_GRAY; else if ( slot->bitmap.pixel_mode == FT_PIXEL_MODE_LCD ) mode = DISPLAY_MODE_LCD; state->display.disp_draw( state->display.disp, mode, ( x_origin >> 6 ) + slot->bitmap_left, y - slot->bitmap_top, map->width, map->rows, map->pitch, map->buffer ); } if ( rmode == HINT_MODE_UNHINTED ) x_origin += slot->linearHoriAdvance >> 10; else x_origin += slot->advance.x; prev_glyph = gindex; } /* display footer on this column */ { void* disp = state->display.disp; const char *msg; char temp[64]; msg = render_mode_names[column->hint_mode]; state->display.disp_text( disp, left, bottom + 5, msg ); if ( !column->use_lcd_filter ) msg = "gray rendering"; else if ( column->use_custom_lcd_filter ) { int fwi = column->fw_index; unsigned char *fw = column->filter_weights; msg = ""; sprintf( temp, "%s0x%02X%s0x%02X%s0x%02X%s0x%02X%s0x%02X%s", fwi == 0 ? "[" : " ", fw[0], fwi == 0 ? "]" : ( fwi == 1 ? "[" : " " ), fw[1], fwi == 1 ? "]" : ( fwi == 2 ? "[" : " " ), fw[2], fwi == 2 ? "]" : ( fwi == 3 ? "[" : " " ), fw[3], fwi == 3 ? "]" : ( fwi == 4 ? "[" : " " ), fw[4], fwi == 4 ? "]" : " " ); state->display.disp_text( disp, left, bottom + 15, temp ); } else switch ( column->lcd_filter ) { case FT_LCD_FILTER_NONE: msg = "LCD without filtering"; break; case FT_LCD_FILTER_DEFAULT: msg = "default LCD filter"; break; case FT_LCD_FILTER_LIGHT: msg = "light LCD filter"; break; default: msg = "legacy LCD filter"; } state->display.disp_text( disp, left, bottom + 15, msg ); sprintf(temp, "%s %s %s", column->use_kerning ? "+kern" : "-kern", column->use_deltas ? "+delta" : "-delta", column->use_global_advance_width ? "+advance" : "-advance" ); state->display.disp_text( disp, left, bottom + 25, temp ); if ( state->col == idx ) state->display.disp_text( disp, left, bottom + 35, "**************" ); } } 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 int FAST_FUNC config_file_action(const char *filename, struct stat *statbuf UNUSED_PARAM, void *userdata UNUSED_PARAM, int depth UNUSED_PARAM) { char *tokens[3]; parser_t *p; struct module_entry *m; int rc = TRUE; if (bb_basename(filename)[0] == '.') goto error; p = config_open2(filename, fopen_for_read); if (p == NULL) { rc = FALSE; goto error; } while (config_read(p, tokens, 3, 2, "# \t", PARSE_NORMAL)) { if (strcmp(tokens[0], "alias") == 0) { /* alias <wildcard> <modulename> */ llist_t *l; char wildcard[MODULE_NAME_LEN]; char *rmod; if (tokens[2] == NULL) continue; filename2modname(tokens[1], wildcard); for (l = G.probes; l; l = l->link) { m = (struct module_entry *) l->data; if (fnmatch(wildcard, m->modname, 0) != 0) continue; rmod = filename2modname(tokens[2], NULL); llist_add_to(&m->realnames, rmod); if (m->flags & MODULE_FLAG_NEED_DEPS) { m->flags &= ~MODULE_FLAG_NEED_DEPS; G.num_unresolved_deps--; } m = get_or_add_modentry(rmod); if (!(m->flags & MODULE_FLAG_NEED_DEPS)) { m->flags |= MODULE_FLAG_NEED_DEPS; G.num_unresolved_deps++; } } } else if (strcmp(tokens[0], "options") == 0) { /* options <modulename> <option...> */ if (tokens[2] == NULL) continue; m = get_or_add_modentry(tokens[1]); m->options = gather_options_str(m->options, tokens[2]); } else if (strcmp(tokens[0], "include") == 0) { /* include <filename> */ read_config(tokens[1]); } else if (ENABLE_FEATURE_MODPROBE_BLACKLIST && strcmp(tokens[0], "blacklist") == 0 ) { /* blacklist <modulename> */ get_or_add_modentry(tokens[1])->flags |= MODULE_FLAG_BLACKLISTED; } } config_close(p); error: return rc; } Commit Message: CWE ID: CWE-20 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 jsR_calllwfunction(js_State *J, int n, js_Function *F, js_Environment *scope) { js_Value v; int i; jsR_savescope(J, scope); if (n > F->numparams) { js_pop(J, F->numparams - n); n = F->numparams; } for (i = n; i < F->varlen; ++i) js_pushundefined(J); jsR_run(J, F); v = *stackidx(J, -1); TOP = --BOT; /* clear stack */ js_pushvalue(J, v); jsR_restorescope(J); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: static size_t consume_s8 (ut8 *buf, ut8 *max, st8 *out, ut32 *offset) { size_t n; ut32 tmp; if (!(n = consume_u32 (buf, max, &tmp, offset)) || n > 1) { return 0; } *out = (st8)(tmp & 0x7f); return 1; } Commit Message: Fix crash in fuzzed wasm r2_hoobr_consume_init_expr CWE ID: CWE-125 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 dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) { int al, i, j, ret; unsigned int n; SSL3_RECORD *rr; void (*cb) (const SSL *ssl, int type2, int val) = NULL; if (s->s3->rbuf.buf == NULL) /* Not initialized yet */ if (!ssl3_setup_buffers(s)) return (-1); /* XXX: check what the second '&& type' is about */ if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE) && type) || (peek && (type != SSL3_RT_APPLICATION_DATA))) { SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } /* * check whether there's a handshake message (client hello?) waiting */ if ((ret = have_handshake_fragment(s, type, buf, len, peek))) return ret; /* * Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */ #ifndef OPENSSL_NO_SCTP /* * Continue handshake if it had to be interrupted to read app data with * SCTP. */ if ((!s->in_handshake && SSL_in_init(s)) || (BIO_dgram_is_sctp(SSL_get_rbio(s)) && (s->state == DTLS1_SCTP_ST_SR_READ_SOCK || s->state == DTLS1_SCTP_ST_CR_READ_SOCK) && s->s3->in_read_app_data != 2)) #else if (!s->in_handshake && SSL_in_init(s)) #endif { /* type == SSL3_RT_APPLICATION_DATA */ i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } } start: s->rwstate = SSL_NOTHING; /*- * s->s3->rrec.type - is the type of record * s->s3->rrec.data, - data * s->s3->rrec.off, - offset into 'data' for next read * s->s3->rrec.length, - number of bytes. */ rr = &(s->s3->rrec); /* * We are not handshaking and have no data yet, so process data buffered * during the last handshake in advance, if any. */ if (s->state == SSL_ST_OK && rr->length == 0) { pitem *item; item = pqueue_pop(s->d1->buffered_app_data.q); if (item) { #ifndef OPENSSL_NO_SCTP /* Restore bio_dgram_sctp_rcvinfo struct */ if (BIO_dgram_is_sctp(SSL_get_rbio(s))) { DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *)item->data; BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo); } #endif dtls1_copy_record(s, item); OPENSSL_free(item->data); pitem_free(item); } } /* Check for timeout */ if (dtls1_handle_timeout(s) > 0) goto start; /* get new packet if necessary */ if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) { ret = dtls1_get_record(s); if (ret <= 0) { ret = dtls1_read_failed(s, ret); /* anything other than a timeout is an error */ if (ret <= 0) return (ret); else goto start; } } if (s->d1->listen && rr->type != SSL3_RT_HANDSHAKE) { rr->length = 0; goto start; } /* * Reset the count of consecutive warning alerts if we've got a non-empty * record that isn't an alert. */ if (rr->type != SSL3_RT_ALERT && rr->length != 0) s->cert->alert_count = 0; /* we now have a packet which can be read and processed */ if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec, * reset by ssl3_get_finished */ && (rr->type != SSL3_RT_HANDSHAKE)) { /* * We now have application data between CCS and Finished. Most likely * the packets were reordered on their way, so buffer the application * data for later processing rather than dropping the connection. */ if (dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num) < 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } rr->length = 0; goto start; } /* * If the other end has shut down, throw anything we read away (even in * 'peek' mode) */ if (s->shutdown & SSL_RECEIVED_SHUTDOWN) { rr->length = 0; s->rwstate = SSL_NOTHING; return (0); } if (type == rr->type) { /* SSL3_RT_APPLICATION_DATA or * SSL3_RT_HANDSHAKE */ /* * make sure that we are not getting application data when we are * doing a handshake for the first time */ if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) && (s->enc_read_ctx == NULL)) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE); goto f_err; } if (len <= 0) return (len); if ((unsigned int)len > rr->length) n = rr->length; else n = (unsigned int)len; memcpy(buf, &(rr->data[rr->off]), n); if (!peek) { rr->length -= n; rr->off += n; if (rr->length == 0) { s->rstate = SSL_ST_READ_HEADER; rr->off = 0; } } #ifndef OPENSSL_NO_SCTP /* * We were about to renegotiate but had to read belated application * data first, so retry. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && rr->type == SSL3_RT_APPLICATION_DATA && (s->state == DTLS1_SCTP_ST_SR_READ_SOCK || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)) { s->rwstate = SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); } /* * We might had to delay a close_notify alert because of reordered * app data. If there was an alert and there is no message to read * anymore, finally set shutdown. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && s->d1->shutdown_received && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->shutdown |= SSL_RECEIVED_SHUTDOWN; return (0); } #endif return (n); } /* * If we get here, then type != rr->type; if we have a handshake message, * then it was unexpected (Hello Request or Client Hello). */ /* * In case of record types for which we have 'fragment' storage, fill * that so that we can process the data at a fixed place. */ { unsigned int k, dest_maxlen = 0; unsigned char *dest = NULL; unsigned int *dest_len = NULL; if (rr->type == SSL3_RT_HANDSHAKE) { dest_maxlen = sizeof(s->d1->handshake_fragment); dest = s->d1->handshake_fragment; dest_len = &s->d1->handshake_fragment_len; } else if (rr->type == SSL3_RT_ALERT) { dest_maxlen = sizeof(s->d1->alert_fragment); dest = s->d1->alert_fragment; dest_len = &s->d1->alert_fragment_len; } #ifndef OPENSSL_NO_HEARTBEATS else if (rr->type == TLS1_RT_HEARTBEAT) { dtls1_process_heartbeat(s); /* Exit and notify application to read again */ rr->length = 0; s->rwstate = SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return (-1); } #endif /* else it's a CCS message, or application data or wrong */ else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) { /* * Application data while renegotiating is allowed. Try again * reading. */ if (rr->type == SSL3_RT_APPLICATION_DATA) { BIO *bio; s->s3->in_read_app_data = 2; bio = SSL_get_rbio(s); s->rwstate = SSL_READING; BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return (-1); } /* Not certain if this is the right error handling */ al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); goto f_err; } if (dest_maxlen > 0) { /* * XDTLS: In a pathalogical case, the Client Hello may be * fragmented--don't always expect dest_maxlen bytes */ if (rr->length < dest_maxlen) { #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE /* * for normal alerts rr->length is 2, while * dest_maxlen is 7 if we were to handle this * non-existing alert... */ FIX ME #endif s->rstate = SSL_ST_READ_HEADER; rr->length = 0; goto start; } /* now move 'n' bytes: */ for (k = 0; k < dest_maxlen; k++) { dest[k] = rr->data[rr->off++]; rr->length--; } *dest_len = dest_maxlen; } } /*- * s->d1->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE; * s->d1->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */ /* If we are a client, check for an incoming 'Hello Request': */ if ((!s->server) && (s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && (s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) && (s->session != NULL) && (s->session->cipher != NULL)) { s->d1->handshake_fragment_len = 0; if ((s->d1->handshake_fragment[1] != 0) || (s->d1->handshake_fragment[2] != 0) || (s->d1->handshake_fragment[3] != 0)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_HELLO_REQUEST); goto f_err; } /* * no need to check sequence number on HELLO REQUEST messages */ if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->d1->handshake_fragment, 4, s, s->msg_callback_arg); if (SSL_is_init_finished(s) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) && !s->s3->renegotiate) { s->d1->handshake_read_seq++; s->new_session = 1; ssl3_renegotiate(s); if (ssl3_renegotiate_check(s)) { i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (s->s3->rbuf.left == 0) { /* no read-ahead left? */ BIO *bio; /* * In the case where we try to read application data, * but we trigger an SSL handshake, we return -1 with * the retry option set. Otherwise renegotiation may * cause nasty problems in the blocking world */ s->rwstate = SSL_READING; bio = SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return (-1); } } } } /* * we either finished a handshake or ignored the request, now try * again to obtain the (application) data we were asked for */ goto start; } /* * If we are a server and get a client hello when renegotiation isn't * allowed send back a no renegotiation alert and carry on. */ if (s->server && SSL_is_init_finished(s) && !s->s3->send_connection_binding && s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH && s->d1->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO && s->s3->previous_client_finished_len != 0 && (s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) == 0) { s->d1->handshake_fragment_len = 0; rr->length = 0; ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION); goto start; } if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) { int alert_level = s->d1->alert_fragment[0]; int alert_descr = s->d1->alert_fragment[1]; s->d1->alert_fragment_len = 0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_ALERT, s->d1->alert_fragment, 2, s, s->msg_callback_arg); if (s->info_callback != NULL) cb = s->info_callback; else if (s->ctx->info_callback != NULL) cb = s->ctx->info_callback; if (cb != NULL) { j = (alert_level << 8) | alert_descr; cb(s, SSL_CB_READ_ALERT, j); } if (alert_level == SSL3_AL_WARNING) { s->s3->warn_alert = alert_descr; s->cert->alert_count++; if (s->cert->alert_count == MAX_WARN_ALERT_COUNT) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS); goto f_err; } if (alert_descr == SSL_AD_CLOSE_NOTIFY) { #ifndef OPENSSL_NO_SCTP /* * With SCTP and streams the socket may deliver app data * after a close_notify alert. We have to check this first so * that nothing gets discarded. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->d1->shutdown_received = 1; s->rwstate = SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return -1; } #endif s->shutdown |= SSL_RECEIVED_SHUTDOWN; return (0); } #if 0 /* XXX: this is a possible improvement in the future */ /* now check if it's a missing record */ if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) { unsigned short seq; unsigned int frag_off; unsigned char *p = &(s->d1->alert_fragment[2]); n2s(p, seq); n2l3(p, frag_off); dtls1_retransmit_message(s, dtls1_get_queue_priority (frag->msg_header.seq, 0), frag_off, &found); if (!found && SSL_in_init(s)) { /* * fprintf( stderr,"in init = %d\n", SSL_in_init(s)); */ /* * requested a message not yet sent, send an alert * ourselves */ ssl3_send_alert(s, SSL3_AL_WARNING, DTLS1_AD_MISSING_HANDSHAKE_MESSAGE); } } #endif } else if (alert_level == SSL3_AL_FATAL) { char tmp[16]; s->rwstate = SSL_NOTHING; s->s3->fatal_alert = alert_descr; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr); BIO_snprintf(tmp, sizeof(tmp), "%d", alert_descr); ERR_add_error_data(2, "SSL alert number ", tmp); s->shutdown |= SSL_RECEIVED_SHUTDOWN; SSL_CTX_remove_session(s->session_ctx, s->session); return (0); } else { al = SSL_AD_ILLEGAL_PARAMETER; goto f_err; } goto start; } if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a * shutdown */ s->rwstate = SSL_NOTHING; rr->length = 0; return (0); } if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) { struct ccs_header_st ccs_hdr; unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH; dtls1_get_ccs_header(rr->data, &ccs_hdr); if (s->version == DTLS1_BAD_VER) ccs_hdr_len = 3; /* * 'Change Cipher Spec' is just a single byte, so we know exactly * what the record payload has to look like */ /* XDTLS: check that epoch is consistent */ if ((rr->length != ccs_hdr_len) || (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC); goto f_err; } rr->length = 0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg); /* * We can't process a CCS now, because previous handshake messages * are still missing, so just drop it. */ if (!s->d1->change_cipher_spec_ok) { goto start; } s->d1->change_cipher_spec_ok = 0; s->s3->change_cipher_spec = 1; if (!ssl3_do_change_cipher_spec(s)) goto err; /* do this whenever CCS is processed */ dtls1_reset_seq_numbers(s, SSL3_CC_READ); if (s->version == DTLS1_BAD_VER) s->d1->handshake_read_seq++; #ifndef OPENSSL_NO_SCTP /* * Remember that a CCS has been received, so that an old key of * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no * SCTP is used */ BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL); #endif goto start; } /* * Unexpected handshake message (Client Hello, or protocol violation) */ if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && !s->in_handshake) { struct hm_header_st msg_hdr; /* this may just be a stale retransmit */ dtls1_get_message_header(rr->data, &msg_hdr); if (rr->epoch != s->d1->r_epoch) { rr->length = 0; goto start; } /* * If we are server, we may have a repeated FINISHED of the client * here, then retransmit our CCS and FINISHED. */ if (msg_hdr.type == SSL3_MT_FINISHED) { if (dtls1_check_timeout_num(s) < 0) return -1; dtls1_retransmit_buffered_messages(s); rr->length = 0; goto start; } if (((s->state & SSL_ST_MASK) == SSL_ST_OK) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) { #if 0 /* worked only because C operator preferences * are not as expected (and because this is * not really needed for clients except for * detecting protocol violations): */ s->state = SSL_ST_BEFORE | (s->server) ? SSL_ST_ACCEPT : SSL_ST_CONNECT; #else s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT; #endif s->renegotiate = 1; s->new_session = 1; } i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (s->s3->rbuf.left == 0) { /* no read-ahead left? */ BIO *bio; /* * In the case where we try to read application data, but we * trigger an SSL handshake, we return -1 with the retry * option set. Otherwise renegotiation may cause nasty * problems in the blocking world */ s->rwstate = SSL_READING; bio = SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return (-1); } } goto start; } switch (rr->type) { default: #ifndef OPENSSL_NO_TLS /* TLS just ignores unknown message types */ if (s->version == TLS1_VERSION) { rr->length = 0; goto start; } #endif al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); goto f_err; case SSL3_RT_CHANGE_CIPHER_SPEC: case SSL3_RT_ALERT: case SSL3_RT_HANDSHAKE: /* * we already handled all of these, with the possible exception of * SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not * happen when type != rr->type */ al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); goto f_err; case SSL3_RT_APPLICATION_DATA: /* * At this point, we were expecting handshake data, but have * application data. If the library was running inside ssl3_read() * (i.e. in_read_app_data is set) and it makes sense to read * application data at this point (session renegotiation not yet * started), we will indulge it. */ if (s->s3->in_read_app_data && (s->s3->total_renegotiations != 0) && (((s->state & SSL_ST_CONNECT) && (s->state >= SSL3_ST_CW_CLNT_HELLO_A) && (s->state <= SSL3_ST_CR_SRVR_HELLO_A) ) || ((s->state & SSL_ST_ACCEPT) && (s->state <= SSL3_ST_SW_HELLO_REQ_A) && (s->state >= SSL3_ST_SR_CLNT_HELLO_A) ) )) { s->s3->in_read_app_data = 2; return (-1); } else { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); goto f_err; } } /* not reached */ f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: return (-1); } Commit Message: 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: stf_status ikev2parent_inI2outR2(struct msg_digest *md) { struct state *st = md->st; /* struct connection *c = st->st_connection; */ /* * the initiator sent us an encrypted payload. We need to calculate * our g^xy, and skeyseed values, and then decrypt the payload. */ DBG(DBG_CONTROLMORE, DBG_log( "ikev2 parent inI2outR2: calculating g^{xy} in order to decrypt I2")); /* verify that there is in fact an encrypted payload */ if (!md->chain[ISAKMP_NEXT_v2E]) { libreswan_log("R2 state should receive an encrypted payload"); reset_globals(); return STF_FATAL; } /* now. we need to go calculate the g^xy */ { struct dh_continuation *dh = alloc_thing( struct dh_continuation, "ikev2_inI2outR2 KE"); stf_status e; dh->md = md; set_suspended(st, dh->md); pcrc_init(&dh->dh_pcrc); dh->dh_pcrc.pcrc_func = ikev2_parent_inI2outR2_continue; e = start_dh_v2(&dh->dh_pcrc, st, st->st_import, RESPONDER, st->st_oakley.groupnum); if (e != STF_SUSPEND && e != STF_INLINE) { loglog(RC_CRYPTOFAILED, "system too busy"); delete_state(st); } reset_globals(); return e; } } Commit Message: SECURITY: Properly handle IKEv2 I1 notification packet without KE payload CWE ID: CWE-20 Target: 1 Example 2: Code: void WriteData(SAVESTREAM* fp, cmsIT8* it8) { int i, j; TABLE* t = GetTable(it8); if (!t->Data) return; WriteStr (fp, "BEGIN_DATA\n"); t->nPatches = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS")); for (i = 0; i < t-> nPatches; i++) { WriteStr(fp, " "); for (j = 0; j < t->nSamples; j++) { char *ptr = t->Data[i*t->nSamples+j]; if (ptr == NULL) WriteStr(fp, "\"\""); else { if (strchr(ptr, ' ') != NULL) { WriteStr(fp, "\""); WriteStr(fp, ptr); WriteStr(fp, "\""); } else WriteStr(fp, ptr); } WriteStr(fp, ((j == (t->nSamples-1)) ? "\n" : "\t")); } } WriteStr (fp, "END_DATA\n"); } Commit Message: Upgrade Visual studio 2017 15.8 - Upgrade to 15.8 - Add check on CGATS memory allocation (thanks to Quang Nguyen for pointing out this) CWE ID: CWE-190 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: gss_wrap_size_limit(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 *max_input_size) { gss_union_ctx_id_t ctx; gss_mechanism mech; OM_uint32 major_status; if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); if (max_input_size == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (!mech) return (GSS_S_BAD_MECH); if (mech->gss_wrap_size_limit) major_status = mech->gss_wrap_size_limit(minor_status, ctx->internal_ctx_id, conf_req_flag, qop_req, req_output_size, max_input_size); else if (mech->gss_wrap_iov_length) major_status = gssint_wrap_size_limit_iov_shim(mech, minor_status, ctx->internal_ctx_id, conf_req_flag, qop_req, req_output_size, max_input_size); else major_status = GSS_S_UNAVAILABLE; if (major_status != GSS_S_COMPLETE) map_error(minor_status, mech); return major_status; } Commit Message: Preserve GSS context on init/accept failure After gss_init_sec_context() or gss_accept_sec_context() has created a context, don't delete the mechglue context on failures from subsequent calls, even if the mechanism deletes the mech-specific context (which is allowed by RFC 2744 but not preferred). Check for union contexts with no mechanism context in each GSS function which accepts a gss_ctx_id_t. CVE-2017-11462: RFC 2744 permits a GSS-API implementation to delete an existing security context on a second or subsequent call to gss_init_sec_context() or gss_accept_sec_context() if the call results in an error. This API behavior has been found to be dangerous, leading to the possibility of memory errors in some callers. For safety, GSS-API implementations should instead preserve existing security contexts on error until the caller deletes them. All versions of MIT krb5 prior to this change may delete acceptor contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through 1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on error. ticket: 8598 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup CWE ID: CWE-415 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_PTR CALLBACK NewVersionCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { char cmdline[] = APPLICATION_NAME " -w 150"; static char* filepath = NULL; static int download_status = 0; LONG i; HWND hNotes; STARTUPINFOA si; PROCESS_INFORMATION pi; HFONT hyperlink_font = NULL; EXT_DECL(dl_ext, NULL, __VA_GROUP__("*.exe"), __VA_GROUP__(lmprintf(MSG_037))); switch (message) { case WM_INITDIALOG: apply_localization(IDD_NEW_VERSION, hDlg); download_status = 0; SetTitleBarIcon(hDlg); CenterDialog(hDlg); update_original_proc = (WNDPROC)SetWindowLongPtr(hDlg, GWLP_WNDPROC, (LONG_PTR)update_subclass_callback); hNotes = GetDlgItem(hDlg, IDC_RELEASE_NOTES); SendMessage(hNotes, EM_AUTOURLDETECT, 1, 0); SendMessageA(hNotes, EM_SETTEXTEX, (WPARAM)&friggin_microsoft_unicode_amateurs, (LPARAM)update.release_notes); SendMessage(hNotes, EM_SETSEL, -1, -1); SendMessage(hNotes, EM_SETEVENTMASK, 0, ENM_LINK); SetWindowTextU(GetDlgItem(hDlg, IDC_YOUR_VERSION), lmprintf(MSG_018, rufus_version[0], rufus_version[1], rufus_version[2])); SetWindowTextU(GetDlgItem(hDlg, IDC_LATEST_VERSION), lmprintf(MSG_019, update.version[0], update.version[1], update.version[2])); SetWindowTextU(GetDlgItem(hDlg, IDC_DOWNLOAD_URL), update.download_url); SendMessage(GetDlgItem(hDlg, IDC_PROGRESS), PBM_SETRANGE, 0, (MAX_PROGRESS<<16) & 0xFFFF0000); if (update.download_url == NULL) EnableWindow(GetDlgItem(hDlg, IDC_DOWNLOAD), FALSE); break; case WM_CTLCOLORSTATIC: if ((HWND)lParam != GetDlgItem(hDlg, IDC_WEBSITE)) return FALSE; SetBkMode((HDC)wParam, TRANSPARENT); CreateStaticFont((HDC)wParam, &hyperlink_font); SelectObject((HDC)wParam, hyperlink_font); SetTextColor((HDC)wParam, RGB(0,0,125)); // DARK_BLUE return (INT_PTR)CreateSolidBrush(GetSysColor(COLOR_BTNFACE)); case WM_COMMAND: switch (LOWORD(wParam)) { case IDCLOSE: case IDCANCEL: if (download_status != 1) { reset_localization(IDD_NEW_VERSION); safe_free(filepath); EndDialog(hDlg, LOWORD(wParam)); } return (INT_PTR)TRUE; case IDC_WEBSITE: ShellExecuteA(hDlg, "open", RUFUS_URL, NULL, NULL, SW_SHOWNORMAL); break; case IDC_DOWNLOAD: // Also doubles as abort and launch function switch(download_status) { case 1: // Abort FormatStatus = ERROR_SEVERITY_ERROR|FAC(FACILITY_STORAGE)|ERROR_CANCELLED; download_status = 0; break; case 2: // Launch newer version and close this one Sleep(1000); // Add a delay on account of antivirus scanners if (ValidateSignature(hDlg, filepath) != NO_ERROR) break; memset(&si, 0, sizeof(si)); memset(&pi, 0, sizeof(pi)); si.cb = sizeof(si); if (!CreateProcessU(filepath, cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { PrintInfo(0, MSG_214); uprintf("Failed to launch new application: %s\n", WindowsErrorString()); } else { PrintInfo(0, MSG_213); PostMessage(hDlg, WM_COMMAND, (WPARAM)IDCLOSE, 0); PostMessage(hMainDialog, WM_CLOSE, 0, 0); } break; default: // Download if (update.download_url == NULL) { uprintf("Could not get download URL\n"); break; } for (i=(int)strlen(update.download_url); (i>0)&&(update.download_url[i]!='/'); i--); dl_ext.filename = &update.download_url[i+1]; filepath = FileDialog(TRUE, app_dir, &dl_ext, OFN_NOCHANGEDIR); if (filepath == NULL) { uprintf("Could not get save path\n"); break; } SendMessage(hDlg, WM_NEXTDLGCTL, (WPARAM)GetDlgItem(hDlg, IDC_DOWNLOAD), TRUE); DownloadFileThreaded(update.download_url, filepath, hDlg); break; } return (INT_PTR)TRUE; } break; case UM_PROGRESS_INIT: EnableWindow(GetDlgItem(hDlg, IDCANCEL), FALSE); SetWindowTextU(GetDlgItem(hDlg, IDC_DOWNLOAD), lmprintf(MSG_038)); FormatStatus = 0; download_status = 1; return (INT_PTR)TRUE; case UM_PROGRESS_EXIT: EnableWindow(GetDlgItem(hDlg, IDCANCEL), TRUE); if (wParam) { SetWindowTextU(GetDlgItem(hDlg, IDC_DOWNLOAD), lmprintf(MSG_039)); download_status = 2; } else { SetWindowTextU(GetDlgItem(hDlg, IDC_DOWNLOAD), lmprintf(MSG_040)); download_status = 0; } return (INT_PTR)TRUE; } return (INT_PTR)FALSE; } Commit Message: [pki] fix https://www.kb.cert.org/vuls/id/403768 * This commit effectively fixes https://www.kb.cert.org/vuls/id/403768 (CVE-2017-13083) as it is described per its revision 11, which is the latest revision at the time of this commit, by disabling Windows prompts, enacted during signature validation, that allow the user to bypass the intended signature verification checks. * It needs to be pointed out that the vulnerability ("allow(ing) the use of a self-signed certificate"), which relies on the end-user actively ignoring a Windows prompt that tells them that the update failed the signature validation whilst also advising against running it, is being fully addressed, even as the update protocol remains HTTP. * It also need to be pointed out that the extended delay (48 hours) between the time the vulnerability was reported and the moment it is fixed in our codebase has to do with the fact that the reporter chose to deviate from standard security practices by not disclosing the details of the vulnerability with us, be it publicly or privately, before creating the cert.org report. The only advance notification we received was a generic note about the use of HTTP vs HTTPS, which, as have established, is not immediately relevant to addressing the reported vulnerability. * Closes #1009 * Note: The other vulnerability scenario described towards the end of #1009, which doesn't have to do with the "lack of CA checking", will be addressed separately. CWE ID: CWE-494 Target: 1 Example 2: Code: static int lzw_process_code(struct iwgifrcontext *rctx, struct lzwdeccontext *d, unsigned int code) { if(code==d->eoi_code) { d->eoi_flag=1; return 1; } if(code==d->clear_code) { lzw_clear(d); return 1; } d->ncodes_since_clear++; if(d->ncodes_since_clear==1) { lzw_emit_code(rctx,d,code); d->oldcode = code; return 1; } if(code < d->ct_used) { lzw_emit_code(rctx,d,code); lzw_add_to_dict(d,d->oldcode,d->ct[code].firstchar); } else { if(d->oldcode>=d->ct_used) { iw_set_error(rctx->ctx,"GIF decoding error"); return 0; } if(lzw_add_to_dict(d,d->oldcode,d->ct[d->oldcode].firstchar)) { lzw_emit_code(rctx,d,d->last_code_added); } } d->oldcode = code; return 1; } Commit Message: Fixed a GIF decoding bug (divide by zero) Fixes issue #15 CWE ID: CWE-369 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 CastDuplexView::ActivateCastView() { select_view_->SetVisible(false); cast_view_->SetVisible(true); InvalidateLayout(); } Commit Message: Allow the cast tray to function as expected when the installed extension is missing API methods. BUG=489445 Review URL: https://codereview.chromium.org/1145833003 Cr-Commit-Position: refs/heads/master@{#330663} 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: gs_call_interp(i_ctx_t **pi_ctx_p, ref * pref, int user_errors, int *pexit_code, ref * perror_object) { ref *epref = pref; ref doref; ref *perrordict; ref error_name; int code, ccode; ref saref; i_ctx_t *i_ctx_p = *pi_ctx_p; int *gc_signal = &imemory_system->gs_lib_ctx->gcsignal; *pexit_code = 0; *gc_signal = 0; ialloc_reset_requested(idmemory); again: /* Avoid a dangling error object that might get traced by a future GC. */ make_null(perror_object); o_stack.requested = e_stack.requested = d_stack.requested = 0; while (*gc_signal) { /* Some routine below triggered a GC. */ gs_gc_root_t epref_root; *gc_signal = 0; /* Make sure that doref will get relocated properly if */ /* a garbage collection happens with epref == &doref. */ gs_register_ref_root(imemory_system, &epref_root, (void **)&epref, "gs_call_interp(epref)"); code = interp_reclaim(pi_ctx_p, -1); i_ctx_p = *pi_ctx_p; gs_unregister_root(imemory_system, &epref_root, "gs_call_interp(epref)"); if (code < 0) return code; } code = interp(pi_ctx_p, epref, perror_object); i_ctx_p = *pi_ctx_p; if (!r_has_type(&i_ctx_p->error_object, t__invalid)) { *perror_object = i_ctx_p->error_object; make_t(&i_ctx_p->error_object, t__invalid); } /* Prevent a dangling reference to the GC signal in ticks_left */ /* in the frame of interp, but be prepared to do a GC if */ /* an allocation in this routine asks for it. */ *gc_signal = 0; set_gc_signal(i_ctx_p, 1); if (esp < esbot) /* popped guard entry */ esp = esbot; switch (code) { case gs_error_Fatal: *pexit_code = 255; return code; case gs_error_Quit: *perror_object = osp[-1]; *pexit_code = code = osp->value.intval; osp -= 2; return (code == 0 ? gs_error_Quit : code < 0 && code > -100 ? code : gs_error_Fatal); case gs_error_InterpreterExit: return 0; case gs_error_ExecStackUnderflow: /****** WRONG -- must keep mark blocks intact ******/ ref_stack_pop_block(&e_stack); doref = *perror_object; epref = &doref; goto again; case gs_error_VMreclaim: /* Do the GC and continue. */ /* We ignore the return value here, if it fails here * we'll call it again having jumped to the "again" label. * Where, assuming it fails again, we'll handle the error. */ (void)interp_reclaim(pi_ctx_p, (osp->value.intval == 2 ? avm_global : avm_local)); i_ctx_p = *pi_ctx_p; make_oper(&doref, 0, zpop); epref = &doref; goto again; case gs_error_NeedInput: case gs_error_interrupt: return code; } /* Adjust osp in case of operand stack underflow */ if (osp < osbot - 1) osp = osbot - 1; /* We have to handle stack over/underflow specially, because */ /* we might be able to recover by adding or removing a block. */ switch (code) { case gs_error_dictstackoverflow: /* We don't have to handle this specially: */ /* The only places that could generate it */ /* use check_dstack, which does a ref_stack_extend, */ /* so if` we get this error, it's a real one. */ if (osp >= ostop) { if ((ccode = ref_stack_extend(&o_stack, 1)) < 0) return ccode; } /* Skip system dictionaries for CET 20-02-02 */ ccode = copy_stack(i_ctx_p, &d_stack, min_dstack_size, &saref); if (ccode < 0) return ccode; ref_stack_pop_to(&d_stack, min_dstack_size); dict_set_top(); *++osp = saref; break; case gs_error_dictstackunderflow: if (ref_stack_pop_block(&d_stack) >= 0) { dict_set_top(); doref = *perror_object; epref = &doref; goto again; } break; case gs_error_execstackoverflow: /* We don't have to handle this specially: */ /* The only places that could generate it */ /* use check_estack, which does a ref_stack_extend, */ /* so if we get this error, it's a real one. */ if (osp >= ostop) { if ((ccode = ref_stack_extend(&o_stack, 1)) < 0) return ccode; } ccode = copy_stack(i_ctx_p, &e_stack, 0, &saref); if (ccode < 0) return ccode; { uint count = ref_stack_count(&e_stack); uint limit = ref_stack_max_count(&e_stack) - ES_HEADROOM; if (count > limit) { /* * If there is an e-stack mark within MIN_BLOCK_ESTACK of * the new top, cut the stack back to remove the mark. */ int skip = count - limit; int i; for (i = skip; i < skip + MIN_BLOCK_ESTACK; ++i) { const ref *ep = ref_stack_index(&e_stack, i); if (r_has_type_attrs(ep, t_null, a_executable)) { skip = i + 1; break; } } pop_estack(i_ctx_p, skip); } } *++osp = saref; break; case gs_error_stackoverflow: if (ref_stack_extend(&o_stack, o_stack.requested) >= 0) { /* We can't just re-execute the object, because */ /* it might be a procedure being pushed as a */ /* literal. We check for this case specially. */ doref = *perror_object; if (r_is_proc(&doref)) { *++osp = doref; make_null_proc(&doref); } epref = &doref; goto again; } ccode = copy_stack(i_ctx_p, &o_stack, 0, &saref); if (ccode < 0) return ccode; ref_stack_clear(&o_stack); *++osp = saref; break; case gs_error_stackunderflow: if (ref_stack_pop_block(&o_stack) >= 0) { doref = *perror_object; epref = &doref; goto again; } break; } if (user_errors < 0) return code; if (gs_errorname(i_ctx_p, code, &error_name) < 0) return code; /* out-of-range error code! */ /* * For greater Adobe compatibility, only the standard PostScript errors * are defined in errordict; the rest are in gserrordict. */ if (dict_find_string(systemdict, "errordict", &perrordict) <= 0 || (dict_find(perrordict, &error_name, &epref) <= 0 && (dict_find_string(systemdict, "gserrordict", &perrordict) <= 0 || dict_find(perrordict, &error_name, &epref) <= 0)) ) return code; /* error name not in errordict??? */ doref = *epref; epref = &doref; /* Push the error object on the operand stack if appropriate. */ if (!GS_ERROR_IS_INTERRUPT(code)) { /* Replace the error object if within an oparray or .errorexec. */ *++osp = *perror_object; errorexec_find(i_ctx_p, osp); } goto again; } Commit Message: CWE ID: CWE-388 Target: 1 Example 2: Code: unsigned long msecs_to_jiffies(const unsigned int m) { /* * Negative value, means infinite timeout: */ if ((int)m < 0) return MAX_JIFFY_OFFSET; #if HZ <= MSEC_PER_SEC && !(MSEC_PER_SEC % HZ) /* * HZ is equal to or smaller than 1000, and 1000 is a nice * round multiple of HZ, divide with the factor between them, * but round upwards: */ return (m + (MSEC_PER_SEC / HZ) - 1) / (MSEC_PER_SEC / HZ); #elif HZ > MSEC_PER_SEC && !(HZ % MSEC_PER_SEC) /* * HZ is larger than 1000, and HZ is a nice round multiple of * 1000 - simply multiply with the factor between them. * * But first make sure the multiplication result cannot * overflow: */ if (m > jiffies_to_msecs(MAX_JIFFY_OFFSET)) return MAX_JIFFY_OFFSET; return m * (HZ / MSEC_PER_SEC); #else /* * Generic case - multiply, round and divide. But first * check that if we are doing a net multiplication, that * we wouldn't overflow: */ if (HZ > MSEC_PER_SEC && m > jiffies_to_msecs(MAX_JIFFY_OFFSET)) return MAX_JIFFY_OFFSET; return ((u64)MSEC_TO_HZ_MUL32 * m + MSEC_TO_HZ_ADJ32) >> MSEC_TO_HZ_SHR32; #endif } Commit Message: remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189 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: InspectorScheduleStyleInvalidationTrackingEvent::ClassChange( Element& element, const InvalidationSet& invalidation_set, const AtomicString& class_name) { std::unique_ptr<TracedValue> value = FillCommonPart(element, invalidation_set, kClass); value->SetString("changedClass", class_name); return value; } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} 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: bool SharedMemoryHandleProvider::InitFromMojoHandle( mojo::ScopedSharedBufferHandle buffer_handle) { #if DCHECK_IS_ON() DCHECK_EQ(map_ref_count_, 0); #endif DCHECK(!shared_memory_); base::SharedMemoryHandle memory_handle; const MojoResult result = mojo::UnwrapSharedMemoryHandle(std::move(buffer_handle), &memory_handle, &mapped_size_, &read_only_flag_); if (result != MOJO_RESULT_OK) return false; shared_memory_.emplace(memory_handle, read_only_flag_); 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 Target: 1 Example 2: Code: bool HttpProxyClientSocket::IsConnectedAndIdle() const { return next_state_ == STATE_DONE && transport_->socket()->IsConnectedAndIdle(); } Commit Message: Sanitize headers in Proxy Authentication Required responses BUG=431504 Review URL: https://codereview.chromium.org/769043003 Cr-Commit-Position: refs/heads/master@{#310014} CWE ID: CWE-19 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 validate_camera_metadata_structure(const camera_metadata_t *metadata, const size_t *expected_size) { if (metadata == NULL) { ALOGE("%s: metadata is null!", __FUNCTION__); return ERROR; } { static const struct { const char *name; size_t alignment; } alignments[] = { { .name = "camera_metadata", .alignment = METADATA_ALIGNMENT }, { .name = "camera_metadata_buffer_entry", .alignment = ENTRY_ALIGNMENT }, { .name = "camera_metadata_data", .alignment = DATA_ALIGNMENT }, }; for (size_t i = 0; i < sizeof(alignments)/sizeof(alignments[0]); ++i) { uintptr_t aligned_ptr = ALIGN_TO(metadata, alignments[i].alignment); if ((uintptr_t)metadata != aligned_ptr) { ALOGE("%s: Metadata pointer is not aligned (actual %p, " "expected %p) to type %s", __FUNCTION__, metadata, (void*)aligned_ptr, alignments[i].name); return ERROR; } } } /** * Check that the metadata contents are correct */ if (expected_size != NULL && metadata->size > *expected_size) { ALOGE("%s: Metadata size (%" PRIu32 ") should be <= expected size (%zu)", __FUNCTION__, metadata->size, *expected_size); return ERROR; } if (metadata->entry_count > metadata->entry_capacity) { ALOGE("%s: Entry count (%" PRIu32 ") should be <= entry capacity " "(%" PRIu32 ")", __FUNCTION__, metadata->entry_count, metadata->entry_capacity); return ERROR; } const metadata_uptrdiff_t entries_end = metadata->entries_start + metadata->entry_capacity; if (entries_end < metadata->entries_start || // overflow check entries_end > metadata->data_start) { ALOGE("%s: Entry start + capacity (%" PRIu32 ") should be <= data start " "(%" PRIu32 ")", __FUNCTION__, (metadata->entries_start + metadata->entry_capacity), metadata->data_start); return ERROR; } const metadata_uptrdiff_t data_end = metadata->data_start + metadata->data_capacity; if (data_end < metadata->data_start || // overflow check data_end > metadata->size) { ALOGE("%s: Data start + capacity (%" PRIu32 ") should be <= total size " "(%" PRIu32 ")", __FUNCTION__, (metadata->data_start + metadata->data_capacity), metadata->size); return ERROR; } const metadata_size_t entry_count = metadata->entry_count; camera_metadata_buffer_entry_t *entries = get_entries(metadata); for (size_t i = 0; i < entry_count; ++i) { if ((uintptr_t)&entries[i] != ALIGN_TO(&entries[i], ENTRY_ALIGNMENT)) { ALOGE("%s: Entry index %zu had bad alignment (address %p)," " expected alignment %zu", __FUNCTION__, i, &entries[i], ENTRY_ALIGNMENT); return ERROR; } camera_metadata_buffer_entry_t entry = entries[i]; if (entry.type >= NUM_TYPES) { ALOGE("%s: Entry index %zu had a bad type %d", __FUNCTION__, i, entry.type); return ERROR; } uint32_t tag_section = entry.tag >> 16; int tag_type = get_camera_metadata_tag_type(entry.tag); if (tag_type != (int)entry.type && tag_section < VENDOR_SECTION) { ALOGE("%s: Entry index %zu had tag type %d, but the type was %d", __FUNCTION__, i, tag_type, entry.type); return ERROR; } size_t data_size = calculate_camera_metadata_entry_data_size(entry.type, entry.count); if (data_size != 0) { camera_metadata_data_t *data = (camera_metadata_data_t*) (get_data(metadata) + entry.data.offset); if ((uintptr_t)data != ALIGN_TO(data, DATA_ALIGNMENT)) { ALOGE("%s: Entry index %zu had bad data alignment (address %p)," " expected align %zu, (tag name %s, data size %zu)", __FUNCTION__, i, data, DATA_ALIGNMENT, get_camera_metadata_tag_name(entry.tag) ?: "unknown", data_size); return ERROR; } size_t data_entry_end = entry.data.offset + data_size; if (data_entry_end < entry.data.offset || // overflow check data_entry_end > metadata->data_capacity) { ALOGE("%s: Entry index %zu data ends (%zu) beyond the capacity " "%" PRIu32, __FUNCTION__, i, data_entry_end, metadata->data_capacity); return ERROR; } } else if (entry.count == 0) { if (entry.data.offset != 0) { ALOGE("%s: Entry index %zu had 0 items, but offset was non-0 " "(%" PRIu32 "), tag name: %s", __FUNCTION__, i, entry.data.offset, get_camera_metadata_tag_name(entry.tag) ?: "unknown"); return ERROR; } } // else data stored inline, so we look at value which can be anything. } return OK; } Commit Message: Camera: Prevent data size overflow Add a function to check overflow when calculating metadata data size. Bug: 30741779 Change-Id: I6405fe608567a4f4113674050f826f305ecae030 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: rsvp_obj_print(netdissect_options *ndo, const u_char *pptr, u_int plen, const u_char *tptr, const char *ident, u_int tlen, const struct rsvp_common_header *rsvp_com_header) { const struct rsvp_object_header *rsvp_obj_header; const u_char *obj_tptr; union { const struct rsvp_obj_integrity_t *rsvp_obj_integrity; const struct rsvp_obj_frr_t *rsvp_obj_frr; } obj_ptr; u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen; int hexdump,processed,padbytes,error_code,error_value,i,sigcheck; union { float f; uint32_t i; } bw; uint8_t namelen; u_int action, subchannel; while(tlen>=sizeof(struct rsvp_object_header)) { /* did we capture enough for fully decoding the object header ? */ ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header)); rsvp_obj_header = (const struct rsvp_object_header *)tptr; rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length); rsvp_obj_ctype=rsvp_obj_header->ctype; if(rsvp_obj_len % 4) { ND_PRINT((ndo, "%sERROR: object header size %u not a multiple of 4", ident, rsvp_obj_len)); return -1; } if(rsvp_obj_len < sizeof(struct rsvp_object_header)) { ND_PRINT((ndo, "%sERROR: object header too short %u < %lu", ident, rsvp_obj_len, (unsigned long)sizeof(const struct rsvp_object_header))); return -1; } ND_PRINT((ndo, "%s%s Object (%u) Flags: [%s", ident, tok2str(rsvp_obj_values, "Unknown", rsvp_obj_header->class_num), rsvp_obj_header->class_num, ((rsvp_obj_header->class_num) & 0x80) ? "ignore" : "reject")); if (rsvp_obj_header->class_num > 128) ND_PRINT((ndo, " %s", ((rsvp_obj_header->class_num) & 0x40) ? "and forward" : "silently")); ND_PRINT((ndo, " if unknown], Class-Type: %s (%u), length: %u", tok2str(rsvp_ctype_values, "Unknown", ((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype), rsvp_obj_ctype, rsvp_obj_len)); if(tlen < rsvp_obj_len) { ND_PRINT((ndo, "%sERROR: object goes past end of objects TLV", ident)); return -1; } obj_tptr=tptr+sizeof(struct rsvp_object_header); obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header); /* did we capture enough for fully decoding the object ? */ if (!ND_TTEST2(*tptr, rsvp_obj_len)) return -1; hexdump=FALSE; switch(rsvp_obj_header->class_num) { case RSVP_OBJ_SESSION: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return -1; ND_PRINT((ndo, "%s IPv4 DestAddress: %s, Protocol ID: 0x%02x", ident, ipaddr_string(ndo, obj_tptr), *(obj_tptr + sizeof(struct in_addr)))); ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u", ident, *(obj_tptr+5), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return -1; ND_PRINT((ndo, "%s IPv6 DestAddress: %s, Protocol ID: 0x%02x", ident, ip6addr_string(ndo, obj_tptr), *(obj_tptr + sizeof(struct in6_addr)))); ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u", ident, *(obj_tptr+sizeof(struct in6_addr)+1), EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_TUNNEL_IPV6: if (obj_tlen < 36) return -1; ND_PRINT((ndo, "%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+18), ip6addr_string(ndo, obj_tptr + 20))); obj_tlen-=36; obj_tptr+=36; break; case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */ if (obj_tlen < 26) return -1; ND_PRINT((ndo, "%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_16BITS(obj_tptr+6), ip6addr_string(ndo, obj_tptr + 8))); obj_tlen-=26; obj_tptr+=26; break; case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */ if (obj_tlen < 12) return -1; ND_PRINT((ndo, "%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ipaddr_string(ndo, obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; case RSVP_CTYPE_TUNNEL_IPV4: case RSVP_CTYPE_UNI_IPV4: if (obj_tlen < 12) return -1; ND_PRINT((ndo, "%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ipaddr_string(ndo, obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; default: hexdump=TRUE; } break; case RSVP_OBJ_CONFIRM: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < sizeof(struct in_addr)) return -1; ND_PRINT((ndo, "%s IPv4 Receiver Address: %s", ident, ipaddr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in_addr); obj_tptr+=sizeof(struct in_addr); break; case RSVP_CTYPE_IPV6: if (obj_tlen < sizeof(struct in6_addr)) return -1; ND_PRINT((ndo, "%s IPv6 Receiver Address: %s", ident, ip6addr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in6_addr); obj_tptr+=sizeof(struct in6_addr); break; default: hexdump=TRUE; } break; case RSVP_OBJ_NOTIFY_REQ: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < sizeof(struct in_addr)) return -1; ND_PRINT((ndo, "%s IPv4 Notify Node Address: %s", ident, ipaddr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in_addr); obj_tptr+=sizeof(struct in_addr); break; case RSVP_CTYPE_IPV6: if (obj_tlen < sizeof(struct in6_addr)) return-1; ND_PRINT((ndo, "%s IPv6 Notify Node Address: %s", ident, ip6addr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in6_addr); obj_tptr+=sizeof(struct in6_addr); break; default: hexdump=TRUE; } break; case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */ case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */ case RSVP_OBJ_RECOVERY_LABEL: /* fall through */ case RSVP_OBJ_LABEL: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: while(obj_tlen >= 4 ) { ND_PRINT((ndo, "%s Label: %u", ident, EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; } break; case RSVP_CTYPE_2: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Generalized Label: %u", ident, EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; case RSVP_CTYPE_3: if (obj_tlen < 12) return-1; ND_PRINT((ndo, "%s Waveband ID: %u%s Start Label: %u, Stop Label: %u", ident, EXTRACT_32BITS(obj_tptr), ident, EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; default: hexdump=TRUE; } break; case RSVP_OBJ_STYLE: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Reservation Style: %s, Flags: [0x%02x]", ident, tok2str(rsvp_resstyle_values, "Unknown", EXTRACT_24BITS(obj_tptr+1)), *(obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_SENDER_TEMPLATE: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 18))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */ if (obj_tlen < 40) return-1; ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+18), ident, ip6addr_string(ndo, obj_tptr+20), EXTRACT_16BITS(obj_tptr + 38))); obj_tlen-=40; obj_tptr+=40; break; case RSVP_CTYPE_TUNNEL_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */ if (obj_tlen < 16) return-1; ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ident, ipaddr_string(ndo, obj_tptr+8), EXTRACT_16BITS(obj_tptr + 12))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; case RSVP_OBJ_LABEL_REQ: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: while(obj_tlen >= 4 ) { ND_PRINT((ndo, "%s L3 Protocol ID: %s", ident, tok2str(ethertype_values, "Unknown Protocol (0x%04x)", EXTRACT_16BITS(obj_tptr + 2)))); obj_tlen-=4; obj_tptr+=4; } break; case RSVP_CTYPE_2: if (obj_tlen < 12) return-1; ND_PRINT((ndo, "%s L3 Protocol ID: %s", ident, tok2str(ethertype_values, "Unknown Protocol (0x%04x)", EXTRACT_16BITS(obj_tptr + 2)))); ND_PRINT((ndo, ",%s merge capability",((*(obj_tptr + 4)) & 0x80) ? "no" : "" )); ND_PRINT((ndo, "%s Minimum VPI/VCI: %u/%u", ident, (EXTRACT_16BITS(obj_tptr+4))&0xfff, (EXTRACT_16BITS(obj_tptr + 6)) & 0xfff)); ND_PRINT((ndo, "%s Maximum VPI/VCI: %u/%u", ident, (EXTRACT_16BITS(obj_tptr+8))&0xfff, (EXTRACT_16BITS(obj_tptr + 10)) & 0xfff)); obj_tlen-=12; obj_tptr+=12; break; case RSVP_CTYPE_3: if (obj_tlen < 12) return-1; ND_PRINT((ndo, "%s L3 Protocol ID: %s", ident, tok2str(ethertype_values, "Unknown Protocol (0x%04x)", EXTRACT_16BITS(obj_tptr + 2)))); ND_PRINT((ndo, "%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI", ident, (EXTRACT_32BITS(obj_tptr+4))&0x7fffff, (EXTRACT_32BITS(obj_tptr+8))&0x7fffff, (((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? "10" : "", (((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? "23" : "")); obj_tlen-=12; obj_tptr+=12; break; case RSVP_CTYPE_4: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s LSP Encoding Type: %s (%u)", ident, tok2str(gmpls_encoding_values, "Unknown", *obj_tptr), *obj_tptr)); ND_PRINT((ndo, "%s Switching Type: %s (%u), Payload ID: %s (0x%04x)", ident, tok2str(gmpls_switch_cap_values, "Unknown", *(obj_tptr+1)), *(obj_tptr+1), tok2str(gmpls_payload_values, "Unknown", EXTRACT_16BITS(obj_tptr+2)), EXTRACT_16BITS(obj_tptr + 2))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_RRO: case RSVP_OBJ_ERO: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: while(obj_tlen >= 4 ) { u_char length; ND_TCHECK2(*obj_tptr, 4); length = *(obj_tptr + 1); ND_PRINT((ndo, "%s Subobject Type: %s, length %u", ident, tok2str(rsvp_obj_xro_values, "Unknown %u", RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)), length)); if (length == 0) { /* prevent infinite loops */ ND_PRINT((ndo, "%s ERROR: zero length ERO subtype", ident)); break; } switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) { u_char prefix_length; case RSVP_OBJ_XRO_IPV4: if (length != 8) { ND_PRINT((ndo, " ERROR: length != 8")); goto invalid; } ND_TCHECK2(*obj_tptr, 8); prefix_length = *(obj_tptr+6); if (prefix_length != 32) { ND_PRINT((ndo, " ERROR: Prefix length %u != 32", prefix_length)); goto invalid; } ND_PRINT((ndo, ", %s, %s/%u, Flags: [%s]", RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? "Loose" : "Strict", ipaddr_string(ndo, obj_tptr+2), *(obj_tptr+6), bittok2str(rsvp_obj_rro_flag_values, "none", *(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */ break; case RSVP_OBJ_XRO_LABEL: if (length != 8) { ND_PRINT((ndo, " ERROR: length != 8")); goto invalid; } ND_TCHECK2(*obj_tptr, 8); ND_PRINT((ndo, ", Flags: [%s] (%#x), Class-Type: %s (%u), %u", bittok2str(rsvp_obj_rro_label_flag_values, "none", *(obj_tptr+2)), *(obj_tptr+2), tok2str(rsvp_ctype_values, "Unknown", *(obj_tptr+3) + 256*RSVP_OBJ_RRO), *(obj_tptr+3), EXTRACT_32BITS(obj_tptr + 4))); } obj_tlen-=*(obj_tptr+1); obj_tptr+=*(obj_tptr+1); } break; default: hexdump=TRUE; } break; case RSVP_OBJ_HELLO: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: case RSVP_CTYPE_2: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Instance: 0x%08x, Destination Instance: 0x%08x", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; break; default: hexdump=TRUE; } break; case RSVP_OBJ_RESTART_CAPABILITY: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Restart Time: %ums, Recovery Time: %ums", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; break; default: hexdump=TRUE; } break; case RSVP_OBJ_SESSION_ATTRIBUTE: switch(rsvp_obj_ctype) { case RSVP_CTYPE_TUNNEL_IPV4: if (obj_tlen < 4) return-1; namelen = *(obj_tptr+3); if (obj_tlen < 4+namelen) return-1; ND_PRINT((ndo, "%s Session Name: ", ident)); for (i = 0; i < namelen; i++) safeputchar(ndo, *(obj_tptr + 4 + i)); ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)", ident, (int)*obj_tptr, (int)*(obj_tptr+1), bittok2str(rsvp_session_attribute_flag_values, "none", *(obj_tptr+2)), *(obj_tptr + 2))); obj_tlen-=4+*(obj_tptr+3); obj_tptr+=4+*(obj_tptr+3); break; default: hexdump=TRUE; } break; case RSVP_OBJ_GENERALIZED_UNI: switch(rsvp_obj_ctype) { int subobj_type,af,subobj_len,total_subobj_len; case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; /* read variable length subobjects */ total_subobj_len = obj_tlen; while(total_subobj_len > 0) { subobj_len = EXTRACT_16BITS(obj_tptr); subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8; af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF; ND_PRINT((ndo, "%s Subobject Type: %s (%u), AF: %s (%u), length: %u", ident, tok2str(rsvp_obj_generalized_uni_values, "Unknown", subobj_type), subobj_type, tok2str(af_values, "Unknown", af), af, subobj_len)); if(subobj_len == 0) goto invalid; switch(subobj_type) { case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS: case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS: switch(af) { case AFNUM_INET: if (subobj_len < 8) return -1; ND_PRINT((ndo, "%s UNI IPv4 TNA address: %s", ident, ipaddr_string(ndo, obj_tptr + 4))); break; case AFNUM_INET6: if (subobj_len < 20) return -1; ND_PRINT((ndo, "%s UNI IPv6 TNA address: %s", ident, ip6addr_string(ndo, obj_tptr + 4))); break; case AFNUM_NSAP: if (subobj_len) { /* unless we have a TLV parser lets just hexdump */ hexdump=TRUE; } break; } break; case RSVP_GEN_UNI_SUBOBJ_DIVERSITY: if (subobj_len) { /* unless we have a TLV parser lets just hexdump */ hexdump=TRUE; } break; case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL: if (subobj_len < 16) { return -1; } ND_PRINT((ndo, "%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u", ident, ((EXTRACT_32BITS(obj_tptr+4))>>31), ((EXTRACT_32BITS(obj_tptr+4))&0xFF), EXTRACT_32BITS(obj_tptr+8), EXTRACT_32BITS(obj_tptr + 12))); break; case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL: if (subobj_len < 8) { return -1; } ND_PRINT((ndo, "%s Service level: %u", ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24)); break; default: hexdump=TRUE; break; } total_subobj_len-=subobj_len; obj_tptr+=subobj_len; obj_tlen+=subobj_len; } if (total_subobj_len) { /* unless we have a TLV parser lets just hexdump */ hexdump=TRUE; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_RSVP_HOP: switch(rsvp_obj_ctype) { case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; if (obj_tlen) hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */ break; case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr + 16))); obj_tlen-=20; obj_tptr+=20; hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */ break; default: hexdump=TRUE; } break; case RSVP_OBJ_TIME_VALUES: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Refresh Period: %ums", ident, EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; /* those three objects do share the same semantics */ case RSVP_OBJ_SENDER_TSPEC: case RSVP_OBJ_ADSPEC: case RSVP_OBJ_FLOWSPEC: switch(rsvp_obj_ctype) { case RSVP_CTYPE_2: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Msg-Version: %u, length: %u", ident, (*obj_tptr & 0xf0) >> 4, EXTRACT_16BITS(obj_tptr + 2) << 2)); obj_tptr+=4; /* get to the start of the service header */ obj_tlen-=4; while (obj_tlen >= 4) { intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2; ND_PRINT((ndo, "%s Service Type: %s (%u), break bit %s set, Service length: %u", ident, tok2str(rsvp_intserv_service_type_values,"unknown",*(obj_tptr)), *(obj_tptr), (*(obj_tptr+1)&0x80) ? "" : "not", intserv_serv_tlen)); obj_tptr+=4; /* get to the start of the parameter list */ obj_tlen-=4; while (intserv_serv_tlen>=4) { processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen); if (processed == 0) break; obj_tlen-=processed; intserv_serv_tlen-=processed; obj_tptr+=processed; } } break; default: hexdump=TRUE; } break; case RSVP_OBJ_FILTERSPEC: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 18))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_3: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, Flow Label: %u", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_24BITS(obj_tptr + 17))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_TUNNEL_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 18))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */ if (obj_tlen < 40) return-1; ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+18), ident, ip6addr_string(ndo, obj_tptr+20), EXTRACT_16BITS(obj_tptr + 38))); obj_tlen-=40; obj_tptr+=40; break; case RSVP_CTYPE_TUNNEL_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */ if (obj_tlen < 16) return-1; ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ident, ipaddr_string(ndo, obj_tptr+8), EXTRACT_16BITS(obj_tptr + 12))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; case RSVP_OBJ_FASTREROUTE: /* the differences between c-type 1 and 7 are minor */ obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr; bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth); switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: /* new style */ if (obj_tlen < sizeof(struct rsvp_obj_frr_t)) return-1; ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps", ident, (int)obj_ptr.rsvp_obj_frr->setup_prio, (int)obj_ptr.rsvp_obj_frr->hold_prio, (int)obj_ptr.rsvp_obj_frr->hop_limit, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x", ident, EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any), EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any), EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all))); obj_tlen-=sizeof(struct rsvp_obj_frr_t); obj_tptr+=sizeof(struct rsvp_obj_frr_t); break; case RSVP_CTYPE_TUNNEL_IPV4: /* old style */ if (obj_tlen < 16) return-1; ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps", ident, (int)obj_ptr.rsvp_obj_frr->setup_prio, (int)obj_ptr.rsvp_obj_frr->hold_prio, (int)obj_ptr.rsvp_obj_frr->hop_limit, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Include Colors: 0x%08x, Exclude Colors: 0x%08x", ident, EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any), EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; case RSVP_OBJ_DETOUR: switch(rsvp_obj_ctype) { case RSVP_CTYPE_TUNNEL_IPV4: while(obj_tlen >= 8) { ND_PRINT((ndo, "%s PLR-ID: %s, Avoid-Node-ID: %s", ident, ipaddr_string(ndo, obj_tptr), ipaddr_string(ndo, obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_CLASSTYPE: case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */ switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: ND_PRINT((ndo, "%s CT: %u", ident, EXTRACT_32BITS(obj_tptr) & 0x7)); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_ERROR_SPEC: switch(rsvp_obj_ctype) { case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; error_code=*(obj_tptr+5); error_value=EXTRACT_16BITS(obj_tptr+6); ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)", ident, ipaddr_string(ndo, obj_tptr), *(obj_tptr+4), ident, tok2str(rsvp_obj_error_code_values,"unknown",error_code), error_code)); switch (error_code) { case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING: ND_PRINT((ndo, ", Error Value: %s (%u)", tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value), error_value)); break; case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */ case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD: ND_PRINT((ndo, ", Error Value: %s (%u)", tok2str(rsvp_obj_error_code_diffserv_te_values,"unknown",error_value), error_value)); break; default: ND_PRINT((ndo, ", Unknown Error Value (%u)", error_value)); break; } obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; error_code=*(obj_tptr+17); error_value=EXTRACT_16BITS(obj_tptr+18); ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)", ident, ip6addr_string(ndo, obj_tptr), *(obj_tptr+16), ident, tok2str(rsvp_obj_error_code_values,"unknown",error_code), error_code)); switch (error_code) { case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING: ND_PRINT((ndo, ", Error Value: %s (%u)", tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value), error_value)); break; default: break; } obj_tlen-=20; obj_tptr+=20; break; default: hexdump=TRUE; } break; case RSVP_OBJ_PROPERTIES: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; padbytes = EXTRACT_16BITS(obj_tptr+2); ND_PRINT((ndo, "%s TLV count: %u, padding bytes: %u", ident, EXTRACT_16BITS(obj_tptr), padbytes)); obj_tlen-=4; obj_tptr+=4; /* loop through as long there is anything longer than the TLV header (2) */ while(obj_tlen >= 2 + padbytes) { ND_PRINT((ndo, "%s %s TLV (0x%02x), length: %u", /* length includes header */ ident, tok2str(rsvp_obj_prop_tlv_values,"unknown",*obj_tptr), *obj_tptr, *(obj_tptr + 1))); if (obj_tlen < *(obj_tptr+1)) return-1; if (*(obj_tptr+1) < 2) return -1; print_unknown_data(ndo, obj_tptr + 2, "\n\t\t", *(obj_tptr + 1) - 2); obj_tlen-=*(obj_tptr+1); obj_tptr+=*(obj_tptr+1); } break; default: hexdump=TRUE; } break; case RSVP_OBJ_MESSAGE_ID: /* fall through */ case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */ case RSVP_OBJ_MESSAGE_ID_LIST: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: case RSVP_CTYPE_2: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Flags [0x%02x], epoch: %u", ident, *obj_tptr, EXTRACT_24BITS(obj_tptr + 1))); obj_tlen-=4; obj_tptr+=4; /* loop through as long there are no messages left */ while(obj_tlen >= 4) { ND_PRINT((ndo, "%s Message-ID 0x%08x (%u)", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_INTEGRITY: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < sizeof(struct rsvp_obj_integrity_t)) return-1; obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr; ND_PRINT((ndo, "%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]", ident, EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4), bittok2str(rsvp_obj_integrity_flag_values, "none", obj_ptr.rsvp_obj_integrity->flags))); ND_PRINT((ndo, "%s MD5-sum 0x%08x%08x%08x%08x ", ident, EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12))); sigcheck = signature_verify(ndo, pptr, plen, obj_ptr.rsvp_obj_integrity->digest, rsvp_clear_checksum, rsvp_com_header); ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck))); obj_tlen+=sizeof(struct rsvp_obj_integrity_t); obj_tptr+=sizeof(struct rsvp_obj_integrity_t); break; default: hexdump=TRUE; } break; case RSVP_OBJ_ADMIN_STATUS: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Flags [%s]", ident, bittok2str(rsvp_obj_admin_status_flag_values, "none", EXTRACT_32BITS(obj_tptr)))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_LABEL_SET: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; action = (EXTRACT_16BITS(obj_tptr)>>8); ND_PRINT((ndo, "%s Action: %s (%u), Label type: %u", ident, tok2str(rsvp_obj_label_set_action_values, "Unknown", action), action, ((EXTRACT_32BITS(obj_tptr) & 0x7F)))); switch (action) { case LABEL_SET_INCLUSIVE_RANGE: case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */ /* only a couple of subchannels are expected */ if (obj_tlen < 12) return -1; ND_PRINT((ndo, "%s Start range: %u, End range: %u", ident, EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; default: obj_tlen-=4; obj_tptr+=4; subchannel = 1; while(obj_tlen >= 4 ) { ND_PRINT((ndo, "%s Subchannel #%u: %u", ident, subchannel, EXTRACT_32BITS(obj_tptr))); obj_tptr+=4; obj_tlen-=4; subchannel++; } break; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_S2L: switch (rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Sub-LSP destination address: %s", ident, ipaddr_string(ndo, obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 16) return-1; ND_PRINT((ndo, "%s Sub-LSP destination address: %s", ident, ip6addr_string(ndo, obj_tptr))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; /* * FIXME those are the defined objects that lack a decoder * you are welcome to contribute code ;-) */ case RSVP_OBJ_SCOPE: case RSVP_OBJ_POLICY_DATA: case RSVP_OBJ_ACCEPT_LABEL_SET: case RSVP_OBJ_PROTECTION: default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); /* FIXME indentation */ break; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || hexdump == TRUE) print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), "\n\t ", /* FIXME indentation */ rsvp_obj_len - sizeof(struct rsvp_object_header)); tptr+=rsvp_obj_len; tlen-=rsvp_obj_len; } return 0; invalid: ND_PRINT((ndo, "%s", istr)); return -1; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return -1; } Commit Message: CVE-2017-13048/RSVP: fix decoding of Fast Reroute objects In rsvp_obj_print() the case block for Class-Num 205 (FAST_REROUTE) from RFC 4090 Section 4.1 could over-read accessing the buffer contents before making the bounds check. Rearrange those steps the correct way around. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: void OfflinePageModelTaskified::DeleteCachedPagesByURLPredicate( const UrlPredicate& predicate, const DeletePageCallback& callback) { auto task = DeletePageTask::CreateTaskMatchingUrlPredicateForCachedPages( store_.get(), base::BindOnce(&OfflinePageModelTaskified::OnDeleteDone, weak_ptr_factory_.GetWeakPtr(), callback), policy_controller_.get(), predicate); task_queue_.AddTask(std::move(task)); } Commit Message: Add the method to check if offline archive is in internal dir Bug: 758690 Change-Id: I8bb4283fc40a87fa7a87df2c7e513e2e16903290 Reviewed-on: https://chromium-review.googlesource.com/828049 Reviewed-by: Filip Gorski <[email protected]> Commit-Queue: Jian Li <[email protected]> Cr-Commit-Position: refs/heads/master@{#524232} CWE ID: CWE-787 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 cbc_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_cbc_decrypt_128bit(&serpent_dec_cbc, desc, dst, src, nbytes); } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[email protected]> 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 void get_socket_name(SingleInstData* data, char* buf, int len) { const char* dpy = g_getenv("DISPLAY"); char* host = NULL; int dpynum; if(dpy) { const char* p = strrchr(dpy, ':'); host = g_strndup(dpy, (p - dpy)); dpynum = atoi(p + 1); } else dpynum = 0; g_snprintf(buf, len, "%s/.%s-socket-%s-%d-%s", g_get_tmp_dir(), data->prog_name, host ? host : "", dpynum, g_get_user_name()); } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: void SyncManager::SyncInternal::RefreshEncryption() { DCHECK(initialized_); WriteTransaction trans(FROM_HERE, GetUserShare()); WriteNode node(&trans); if (!node.InitByTagLookup(kNigoriTag)) { NOTREACHED() << "Unable to set encrypted datatypes because Nigori node not " << "found."; return; } Cryptographer* cryptographer = trans.GetCryptographer(); if (!cryptographer->is_ready()) { DVLOG(1) << "Attempting to encrypt datatypes when cryptographer not " << "initialized, prompting for passphrase."; sync_pb::EncryptedData pending_keys; if (cryptographer->has_pending_keys()) pending_keys = cryptographer->GetPendingKeys(); FOR_EACH_OBSERVER(SyncManager::Observer, observers_, OnPassphraseRequired(sync_api::REASON_DECRYPTION, pending_keys)); return; } sync_pb::NigoriSpecifics nigori; nigori.CopyFrom(node.GetNigoriSpecifics()); cryptographer->UpdateNigoriFromEncryptedTypes(&nigori); node.SetNigoriSpecifics(nigori); allstatus_.SetEncryptedTypes(cryptographer->GetEncryptedTypes()); ReEncryptEverything(&trans); } Commit Message: sync: remove Chrome OS specific logic to deal with flimflam shutdown / sync race. No longer necessary as the ProfileSyncService now aborts sync network traffic on shutdown. BUG=chromium-os:20841 Review URL: http://codereview.chromium.org/9358007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@120912 0039d316-1c4b-4281-b951-d872f2087c98 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: long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp) { struct file *eventfp, *filep = NULL; struct eventfd_ctx *ctx = NULL; u64 p; long r; int i, fd; /* If you are not the owner, you can become one */ if (ioctl == VHOST_SET_OWNER) { r = vhost_dev_set_owner(d); goto done; } /* You must be the owner to do anything else */ r = vhost_dev_check_owner(d); if (r) goto done; switch (ioctl) { case VHOST_SET_MEM_TABLE: r = vhost_set_memory(d, argp); break; case VHOST_SET_LOG_BASE: if (copy_from_user(&p, argp, sizeof p)) { r = -EFAULT; break; } if ((u64)(unsigned long)p != p) { r = -EFAULT; break; } for (i = 0; i < d->nvqs; ++i) { struct vhost_virtqueue *vq; void __user *base = (void __user *)(unsigned long)p; vq = d->vqs[i]; mutex_lock(&vq->mutex); /* If ring is inactive, will check when it's enabled. */ if (vq->private_data && !vq_log_access_ok(vq, base)) r = -EFAULT; else vq->log_base = base; mutex_unlock(&vq->mutex); } break; case VHOST_SET_LOG_FD: r = get_user(fd, (int __user *)argp); if (r < 0) break; eventfp = fd == -1 ? NULL : eventfd_fget(fd); if (IS_ERR(eventfp)) { r = PTR_ERR(eventfp); break; } if (eventfp != d->log_file) { filep = d->log_file; ctx = d->log_ctx; d->log_ctx = eventfp ? eventfd_ctx_fileget(eventfp) : NULL; } else filep = eventfp; for (i = 0; i < d->nvqs; ++i) { mutex_lock(&d->vqs[i]->mutex); d->vqs[i]->log_ctx = d->log_ctx; mutex_unlock(&d->vqs[i]->mutex); } if (ctx) eventfd_ctx_put(ctx); if (filep) fput(filep); break; default: r = -ENOIOCTLCMD; break; } done: return r; } Commit Message: vhost: actually track log eventfd file While reviewing vhost log code, I found out that log_file is never set. Note: I haven't tested the change (QEMU doesn't use LOG_FD yet). Cc: [email protected] Signed-off-by: Marc-André Lureau <[email protected]> Signed-off-by: Michael S. Tsirkin <[email protected]> CWE ID: CWE-399 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 *ReadJPEGImage(const ImageInfo *image_info, ExceptionInfo *exception) { char value[MaxTextExtent]; const char *option; ErrorManager error_manager; Image *image; IndexPacket index; JSAMPLE *volatile jpeg_pixels; JSAMPROW scanline[1]; MagickBooleanType debug, status; MagickSizeType number_pixels; MemoryInfo *memory_info; register ssize_t i; struct jpeg_decompress_struct jpeg_info; struct jpeg_error_mgr jpeg_error; register JSAMPLE *p; size_t units; ssize_t y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); debug=IsEventLogging(); (void) debug; image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize JPEG parameters. */ (void) ResetMagickMemory(&error_manager,0,sizeof(error_manager)); (void) ResetMagickMemory(&jpeg_info,0,sizeof(jpeg_info)); (void) ResetMagickMemory(&jpeg_error,0,sizeof(jpeg_error)); jpeg_info.err=jpeg_std_error(&jpeg_error); jpeg_info.err->emit_message=(void (*)(j_common_ptr,int)) JPEGWarningHandler; jpeg_info.err->error_exit=(void (*)(j_common_ptr)) JPEGErrorHandler; memory_info=(MemoryInfo *) NULL; error_manager.image=image; if (setjmp(error_manager.error_recovery) != 0) { jpeg_destroy_decompress(&jpeg_info); if (error_manager.profile != (StringInfo *) NULL) error_manager.profile=DestroyStringInfo(error_manager.profile); (void) CloseBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != 0) return(GetFirstImageInList(image)); InheritException(exception,&image->exception); return(DestroyImage(image)); } jpeg_info.client_data=(void *) &error_manager; jpeg_create_decompress(&jpeg_info); JPEGSourceManager(&jpeg_info,image); jpeg_set_marker_processor(&jpeg_info,JPEG_COM,ReadComment); option=GetImageOption(image_info,"profile:skip"); if (IsOptionMember("ICC",option) == MagickFalse) jpeg_set_marker_processor(&jpeg_info,ICC_MARKER,ReadICCProfile); if (IsOptionMember("IPTC",option) == MagickFalse) jpeg_set_marker_processor(&jpeg_info,IPTC_MARKER,ReadIPTCProfile); for (i=1; i < 16; i++) if ((i != 2) && (i != 13) && (i != 14)) if (IsOptionMember("APP",option) == MagickFalse) jpeg_set_marker_processor(&jpeg_info,(int) (JPEG_APP0+i),ReadProfile); i=(ssize_t) jpeg_read_header(&jpeg_info,TRUE); if ((image_info->colorspace == YCbCrColorspace) || (image_info->colorspace == Rec601YCbCrColorspace) || (image_info->colorspace == Rec709YCbCrColorspace)) jpeg_info.out_color_space=JCS_YCbCr; /* Set image resolution. */ units=0; if ((jpeg_info.saw_JFIF_marker != 0) && (jpeg_info.X_density != 1) && (jpeg_info.Y_density != 1)) { image->x_resolution=(double) jpeg_info.X_density; image->y_resolution=(double) jpeg_info.Y_density; units=(size_t) jpeg_info.density_unit; } if (units == 1) image->units=PixelsPerInchResolution; if (units == 2) image->units=PixelsPerCentimeterResolution; number_pixels=(MagickSizeType) image->columns*image->rows; option=GetImageOption(image_info,"jpeg:size"); if ((option != (const char *) NULL) && (jpeg_info.out_color_space != JCS_YCbCr)) { double scale_factor; GeometryInfo geometry_info; MagickStatusType flags; /* Scale the image. */ flags=ParseGeometry(option,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; jpeg_calc_output_dimensions(&jpeg_info); image->magick_columns=jpeg_info.output_width; image->magick_rows=jpeg_info.output_height; scale_factor=1.0; if (geometry_info.rho != 0.0) scale_factor=jpeg_info.output_width/geometry_info.rho; if ((geometry_info.sigma != 0.0) && (scale_factor > (jpeg_info.output_height/geometry_info.sigma))) scale_factor=jpeg_info.output_height/geometry_info.sigma; jpeg_info.scale_num=1U; jpeg_info.scale_denom=(unsigned int) scale_factor; jpeg_calc_output_dimensions(&jpeg_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Scale factor: %.20g",(double) scale_factor); } #if (JPEG_LIB_VERSION >= 61) && defined(D_PROGRESSIVE_SUPPORTED) #if defined(D_LOSSLESS_SUPPORTED) image->interlace=jpeg_info.process == JPROC_PROGRESSIVE ? JPEGInterlace : NoInterlace; image->compression=jpeg_info.process == JPROC_LOSSLESS ? LosslessJPEGCompression : JPEGCompression; if (jpeg_info.data_precision > 8) (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "12-bit JPEG not supported. Reducing pixel data to 8 bits","`%s'", image->filename); if (jpeg_info.data_precision == 16) jpeg_info.data_precision=12; #else image->interlace=jpeg_info.progressive_mode != 0 ? JPEGInterlace : NoInterlace; image->compression=JPEGCompression; #endif #else image->compression=JPEGCompression; image->interlace=JPEGInterlace; #endif option=GetImageOption(image_info,"jpeg:colors"); if (option != (const char *) NULL) { /* Let the JPEG library quantize for us. */ jpeg_info.quantize_colors=TRUE; jpeg_info.desired_number_of_colors=(int) StringToUnsignedLong(option); } option=GetImageOption(image_info,"jpeg:block-smoothing"); if (option != (const char *) NULL) jpeg_info.do_block_smoothing=IsStringTrue(option) != MagickFalse ? TRUE : FALSE; jpeg_info.dct_method=JDCT_FLOAT; option=GetImageOption(image_info,"jpeg:dct-method"); if (option != (const char *) NULL) switch (*option) { case 'D': case 'd': { if (LocaleCompare(option,"default") == 0) jpeg_info.dct_method=JDCT_DEFAULT; break; } case 'F': case 'f': { if (LocaleCompare(option,"fastest") == 0) jpeg_info.dct_method=JDCT_FASTEST; if (LocaleCompare(option,"float") == 0) jpeg_info.dct_method=JDCT_FLOAT; break; } case 'I': case 'i': { if (LocaleCompare(option,"ifast") == 0) jpeg_info.dct_method=JDCT_IFAST; if (LocaleCompare(option,"islow") == 0) jpeg_info.dct_method=JDCT_ISLOW; break; } } option=GetImageOption(image_info,"jpeg:fancy-upsampling"); if (option != (const char *) NULL) jpeg_info.do_fancy_upsampling=IsStringTrue(option) != MagickFalse ? TRUE : FALSE; (void) jpeg_start_decompress(&jpeg_info); image->columns=jpeg_info.output_width; image->rows=jpeg_info.output_height; image->depth=(size_t) jpeg_info.data_precision; switch (jpeg_info.out_color_space) { case JCS_RGB: default: { (void) SetImageColorspace(image,sRGBColorspace); break; } case JCS_GRAYSCALE: { (void) SetImageColorspace(image,GRAYColorspace); break; } case JCS_YCbCr: { (void) SetImageColorspace(image,YCbCrColorspace); break; } case JCS_CMYK: { (void) SetImageColorspace(image,CMYKColorspace); break; } } if (IsITUFaxImage(image) != MagickFalse) { (void) SetImageColorspace(image,LabColorspace); jpeg_info.out_color_space=JCS_YCbCr; } option=GetImageOption(image_info,"jpeg:colors"); if (option != (const char *) NULL) if (AcquireImageColormap(image,StringToUnsignedLong(option)) == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((jpeg_info.output_components == 1) && (jpeg_info.quantize_colors == 0)) { size_t colors; colors=(size_t) GetQuantumRange(image->depth)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } } if (image->debug != MagickFalse) { if (image->interlace != NoInterlace) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Interlace: progressive"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Interlace: nonprogressive"); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Data precision: %d", (int) jpeg_info.data_precision); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %dx%d", (int) jpeg_info.output_width,(int) jpeg_info.output_height); } JPEGSetImageQuality(&jpeg_info,image); JPEGSetImageSamplingFactor(&jpeg_info,image); (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double) jpeg_info.out_color_space); (void) SetImageProperty(image,"jpeg:colorspace",value); if (image_info->ping != MagickFalse) { jpeg_destroy_decompress(&jpeg_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { jpeg_destroy_decompress(&jpeg_info); InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((jpeg_info.output_components != 1) && (jpeg_info.output_components != 3) && (jpeg_info.output_components != 4)) { jpeg_destroy_decompress(&jpeg_info); ThrowReaderException(CorruptImageError,"ImageTypeNotSupported"); } memory_info=AcquireVirtualMemory((size_t) image->columns, jpeg_info.output_components*sizeof(*jpeg_pixels)); if (memory_info == (MemoryInfo *) NULL) { jpeg_destroy_decompress(&jpeg_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } jpeg_pixels=(JSAMPLE *) GetVirtualMemoryBlob(memory_info); /* Convert JPEG pixels to pixel packets. */ if (setjmp(error_manager.error_recovery) != 0) { if (memory_info != (MemoryInfo *) NULL) memory_info=RelinquishVirtualMemory(memory_info); jpeg_destroy_decompress(&jpeg_info); (void) CloseBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != 0) return(GetFirstImageInList(image)); return(DestroyImage(image)); } if (jpeg_info.quantize_colors != 0) { image->colors=(size_t) jpeg_info.actual_number_of_colors; if (jpeg_info.out_color_space == JCS_GRAYSCALE) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]); image->colormap[i].green=image->colormap[i].red; image->colormap[i].blue=image->colormap[i].red; image->colormap[i].opacity=OpaqueOpacity; } else for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]); image->colormap[i].green=ScaleCharToQuantum(jpeg_info.colormap[1][i]); image->colormap[i].blue=ScaleCharToQuantum(jpeg_info.colormap[2][i]); image->colormap[i].opacity=OpaqueOpacity; } } scanline[0]=(JSAMPROW) jpeg_pixels; for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (jpeg_read_scanlines(&jpeg_info,scanline,1) != 1) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"SkipToSyncByte","`%s'",image->filename); continue; } p=jpeg_pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); if (jpeg_info.data_precision > 8) { unsigned short scale; scale=65535/(unsigned short) GetQuantumRange((size_t) jpeg_info.data_precision); if (jpeg_info.output_components == 1) for (x=0; x < (ssize_t) image->columns; x++) { size_t pixel; pixel=(size_t) (scale*GETJSAMPLE(*p)); index=ConstrainColormapIndex(image,pixel); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } else if (image->colorspace != CMYKColorspace) for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleShortToQuantum((unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelOpacity(q,OpaqueOpacity); q++; } else for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,QuantumRange-ScaleShortToQuantum( (unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelMagenta(q,QuantumRange-ScaleShortToQuantum( (unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelYellow(q,QuantumRange-ScaleShortToQuantum( (unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelBlack(indexes+x,QuantumRange-ScaleShortToQuantum( (unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelOpacity(q,OpaqueOpacity); q++; } } else if (jpeg_info.output_components == 1) for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,(size_t) GETJSAMPLE(*p)); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } else if (image->colorspace != CMYKColorspace) for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelOpacity(q,OpaqueOpacity); q++; } else for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,QuantumRange-ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelMagenta(q,QuantumRange-ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelYellow(q,QuantumRange-ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelBlack(indexes+x,QuantumRange-ScaleCharToQuantum( (unsigned char) GETJSAMPLE(*p++))); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) { jpeg_abort_decompress(&jpeg_info); break; } } if (status != MagickFalse) { error_manager.finished=MagickTrue; if (setjmp(error_manager.error_recovery) == 0) (void) jpeg_finish_decompress(&jpeg_info); } /* Free jpeg resources. */ jpeg_destroy_decompress(&jpeg_info); memory_info=RelinquishVirtualMemory(memory_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: ... CWE ID: CWE-20 Target: 1 Example 2: Code: void GLES2DecoderImpl::PerformanceWarning( const char* filename, int line, const std::string& msg) { logger_.LogMessage(filename, line, std::string("PERFORMANCE WARNING: ") + msg); } Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled. This is when we expose DrawBuffers extension. BUG=376951 TEST=the attached test case, webgl conformance [email protected],[email protected] Review URL: https://codereview.chromium.org/315283002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 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: BGD_DECLARE(int) gdTransformAffineBoundingBox(gdRectPtr src, const double affine[6], gdRectPtr bbox) { gdPointF extent[4], min, max, point; int i; extent[0].x=0.0; extent[0].y=0.0; extent[1].x=(double) src->width; extent[1].y=0.0; extent[2].x=(double) src->width; extent[2].y=(double) src->height; extent[3].x=0.0; extent[3].y=(double) src->height; for (i=0; i < 4; i++) { point=extent[i]; if (gdAffineApplyToPointF(&extent[i], &point, affine) != GD_TRUE) { return GD_FALSE; } } min=extent[0]; max=extent[0]; for (i=1; i < 4; i++) { if (min.x > extent[i].x) min.x=extent[i].x; if (min.y > extent[i].y) min.y=extent[i].y; if (max.x < extent[i].x) max.x=extent[i].x; if (max.y < extent[i].y) max.y=extent[i].y; } bbox->x = (int) min.x; bbox->y = (int) min.y; bbox->width = (int) floor(max.x - min.x) - 1; bbox->height = (int) floor(max.y - min.y); return GD_TRUE; } Commit Message: gdImageScaleTwoPass memory leak fix Fixing memory leak in gdImageScaleTwoPass, as reported by @cmb69 and confirmed by @vapier. This bug actually bit me in production and I'm very thankful that it was reported with an easy fix. Fixes #173. 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 voutf(struct GlobalConfig *config, const char *prefix, const char *fmt, va_list ap) { size_t width = (79 - strlen(prefix)); if(!config->mute) { size_t len; char *ptr; char *print_buffer; print_buffer = curlx_mvaprintf(fmt, ap); if(!print_buffer) return; len = strlen(print_buffer); ptr = print_buffer; while(len > 0) { fputs(prefix, config->errors); if(len > width) { size_t cut = width-1; while(!ISSPACE(ptr[cut]) && cut) { cut--; } if(0 == cut) /* not a single cutting position was found, just cut it at the max text width then! */ cut = width-1; (void)fwrite(ptr, cut + 1, 1, config->errors); fputs("\n", config->errors); ptr += cut + 1; /* skip the space too */ len -= cut; } else { fputs(ptr, config->errors); len = 0; } } curl_free(print_buffer); } } Commit Message: voutf: fix bad arethmetic when outputting warnings to stderr CVE-2018-16842 Reported-by: Brian Carpenter Bug: https://curl.haxx.se/docs/CVE-2018-16842.html CWE ID: CWE-125 Target: 1 Example 2: Code: void btif_dm_update_ble_remote_properties( BD_ADDR bd_addr, BD_NAME bd_name, tBT_DEVICE_TYPE dev_type) { btif_update_remote_properties(bd_addr,bd_name,NULL,dev_type); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284 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 pid_ns_release_proc(struct pid_namespace *ns) { mntput(ns->proc_mnt); } Commit Message: procfs: fix a vfsmount longterm reference leak kern_mount() doesn't pair with plain mntput()... Signed-off-by: Al Viro <[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: void StopInputMethodDaemon() { if (!initialized_successfully_) return; should_launch_ime_ = false; if (ibus_daemon_process_handle_ != base::kNullProcessHandle) { const base::ProcessId pid = base::GetProcId(ibus_daemon_process_handle_); if (!chromeos::StopInputMethodProcess(input_method_status_connection_)) { LOG(ERROR) << "StopInputMethodProcess IPC failed. Sending SIGTERM to " << "PID " << pid; base::KillProcess(ibus_daemon_process_handle_, -1, false /* wait */); } VLOG(1) << "ibus-daemon (PID=" << pid << ") is terminated"; ibus_daemon_process_handle_ = base::kNullProcessHandle; } } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: void _WM_AdjustNoteVolumes(struct _mdi *mdi, uint8_t ch, struct _note *nte) { float premix_dBm; float premix_lin; uint8_t pan_ofs; float premix_dBm_left; float premix_dBm_right; float premix_left; float premix_right; float volume_adj; uint32_t vol_ofs; /* Pointless CPU heating checks to shoosh up a compiler */ if (ch > 0x0f) ch = 0x0f; if (nte->ignore_chan_events) return; pan_ofs = mdi->channel[ch].balance + mdi->channel[ch].pan - 64; vol_ofs = (nte->velocity * ((mdi->channel[ch].expression * mdi->channel[ch].volume) / 127)) / 127; /* This value is to reduce the chance of clipping. Higher value means lower overall volume, Lower value means higher overall volume. NOTE: The lower the value the higher the chance of clipping. FIXME: Still needs tuning. Clipping heard at a value of 3.75 */ #define VOL_DIVISOR 4.0 volume_adj = ((float)_WM_MasterVolume / 1024.0) / VOL_DIVISOR; MIDI_EVENT_DEBUG(__FUNCTION__,ch, 0); if (pan_ofs > 127) pan_ofs = 127; premix_dBm_left = dBm_pan_volume[(127-pan_ofs)]; premix_dBm_right = dBm_pan_volume[pan_ofs]; if (mdi->extra_info.mixer_options & WM_MO_LOG_VOLUME) { premix_dBm = dBm_volume[vol_ofs]; premix_dBm_left += premix_dBm; premix_dBm_right += premix_dBm; premix_left = (powf(10.0,(premix_dBm_left / 20.0))) * volume_adj; premix_right = (powf(10.0,(premix_dBm_right / 20.0))) * volume_adj; } else { premix_lin = (float)(_WM_lin_volume[vol_ofs]) / 1024.0; premix_left = premix_lin * powf(10.0, (premix_dBm_left / 20)) * volume_adj; premix_right = premix_lin * powf(10.0, (premix_dBm_right / 20)) * volume_adj; } nte->left_mix_volume = (int32_t)(premix_left * 1024.0); nte->right_mix_volume = (int32_t)(premix_right * 1024.0); } 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 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 log_option(const char *pfx, const uint8_t *opt) { if (dhcp_verbose >= 2) { char buf[256 * 2 + 2]; *bin2hex(buf, (void*) (opt + OPT_DATA), opt[OPT_LEN]) = '\0'; bb_error_msg("%s: 0x%02x %s", pfx, opt[OPT_CODE], buf); } } Commit Message: CWE ID: CWE-125 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 int virtio_net_load(QEMUFile *f, void *opaque, int version_id) { VirtIONet *n = opaque; VirtIODevice *vdev = VIRTIO_DEVICE(n); int ret, i, link_down; if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION) return -EINVAL; ret = virtio_load(vdev, f); if (ret) { return ret; } qemu_get_buffer(f, n->mac, ETH_ALEN); n->vqs[0].tx_waiting = qemu_get_be32(f); virtio_net_set_mrg_rx_bufs(n, qemu_get_be32(f)); if (version_id >= 3) n->status = qemu_get_be16(f); if (version_id >= 4) { if (version_id < 8) { n->promisc = qemu_get_be32(f); n->allmulti = qemu_get_be32(f); } else { n->promisc = qemu_get_byte(f); n->allmulti = qemu_get_byte(f); } } if (version_id >= 5) { n->mac_table.in_use = qemu_get_be32(f); /* MAC_TABLE_ENTRIES may be different from the saved image */ if (n->mac_table.in_use <= MAC_TABLE_ENTRIES) { qemu_get_buffer(f, n->mac_table.macs, n->mac_table.in_use * ETH_ALEN); } else if (n->mac_table.in_use) { uint8_t *buf = g_malloc0(n->mac_table.in_use); qemu_get_buffer(f, buf, n->mac_table.in_use * ETH_ALEN); g_free(buf); n->mac_table.multi_overflow = n->mac_table.uni_overflow = 1; n->mac_table.in_use = 0; } } if (version_id >= 6) qemu_get_buffer(f, (uint8_t *)n->vlans, MAX_VLAN >> 3); if (version_id >= 7) { if (qemu_get_be32(f) && !peer_has_vnet_hdr(n)) { error_report("virtio-net: saved image requires vnet_hdr=on"); return -1; } } if (version_id >= 9) { n->mac_table.multi_overflow = qemu_get_byte(f); n->mac_table.uni_overflow = qemu_get_byte(f); } if (version_id >= 10) { n->alluni = qemu_get_byte(f); n->nomulti = qemu_get_byte(f); n->nouni = qemu_get_byte(f); n->nobcast = qemu_get_byte(f); } if (version_id >= 11) { if (qemu_get_byte(f) && !peer_has_ufo(n)) { error_report("virtio-net: saved image requires TUN_F_UFO support"); return -1; } } if (n->max_queues > 1) { if (n->max_queues != qemu_get_be16(f)) { error_report("virtio-net: different max_queues "); return -1; } n->curr_queues = qemu_get_be16(f); for (i = 1; i < n->curr_queues; i++) { n->vqs[i].tx_waiting = qemu_get_be32(f); } n->curr_guest_offloads = virtio_net_supported_guest_offloads(n); } if (peer_has_vnet_hdr(n)) { virtio_net_apply_guest_offloads(n); } virtio_net_set_queues(n); /* Find the first multicast entry in the saved MAC filter */ for (i = 0; i < n->mac_table.in_use; i++) { if (n->mac_table.macs[i * ETH_ALEN] & 1) { break; } } n->mac_table.first_multi = i; /* nc.link_down can't be migrated, so infer link_down according * to link status bit in n->status */ link_down = (n->status & VIRTIO_NET_S_LINK_UP) == 0; for (i = 0; i < n->max_queues; i++) { qemu_get_subqueue(n->nic, i)->link_down = link_down; } return 0; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: ppmd_read(void* p) { /* Get the handle to current decompression context. */ struct archive_read *a = ((IByteIn*)p)->a; struct zip *zip = (struct zip*) a->format->data; ssize_t bytes_avail = 0; /* Fetch next byte. */ const uint8_t* data = __archive_read_ahead(a, 1, &bytes_avail); if(bytes_avail < 1) { zip->ppmd8_stream_failed = 1; return 0; } __archive_read_consume(a, 1); /* Increment the counter. */ ++zip->zipx_ppmd_read_compressed; /* Return the next compressed byte. */ return data[0]; } Commit Message: Fix typo in preprocessor macro in archive_read_format_zip_cleanup() Frees lzma_stream on cleanup() Fixes #1165 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: cf2_getLanguageGroup( CFF_Decoder* decoder ) { FT_ASSERT( decoder && decoder->current_subfont ); return decoder->current_subfont->private_dict.language_group; } Commit Message: CWE ID: CWE-20 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: xfs_acl_from_disk(struct xfs_acl *aclp) { struct posix_acl_entry *acl_e; struct posix_acl *acl; struct xfs_acl_entry *ace; int count, i; count = be32_to_cpu(aclp->acl_cnt); acl = posix_acl_alloc(count, GFP_KERNEL); if (!acl) return ERR_PTR(-ENOMEM); for (i = 0; i < count; i++) { acl_e = &acl->a_entries[i]; ace = &aclp->acl_entry[i]; /* * The tag is 32 bits on disk and 16 bits in core. * * Because every access to it goes through the core * format first this is not a problem. */ acl_e->e_tag = be32_to_cpu(ace->ae_tag); acl_e->e_perm = be16_to_cpu(ace->ae_perm); switch (acl_e->e_tag) { case ACL_USER: case ACL_GROUP: acl_e->e_id = be32_to_cpu(ace->ae_id); break; case ACL_USER_OBJ: case ACL_GROUP_OBJ: case ACL_MASK: case ACL_OTHER: acl_e->e_id = ACL_UNDEFINED_ID; break; default: goto fail; } } return acl; fail: posix_acl_release(acl); return ERR_PTR(-EINVAL); } Commit Message: xfs: validate acl count This prevents in-memory corruption and possible panics if the on-disk ACL is badly corrupted. Signed-off-by: Christoph Hellwig <[email protected]> Signed-off-by: Ben Myers <[email protected]> CWE ID: CWE-189 Target: 1 Example 2: Code: static int shadow_copy2_chdir(vfs_handle_struct *handle, const char *fname) { time_t timestamp; char *stripped; int ret, saved_errno; char *conv; if (!shadow_copy2_strip_snapshot(talloc_tos(), handle, fname, &timestamp, &stripped)) { return -1; } if (timestamp == 0) { return SMB_VFS_NEXT_CHDIR(handle, fname); } conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp); TALLOC_FREE(stripped); if (conv == NULL) { return -1; } ret = SMB_VFS_NEXT_CHDIR(handle, conv); saved_errno = errno; TALLOC_FREE(conv); errno = saved_errno; return ret; } Commit Message: 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 void netbk_tx_err(struct xenvif *vif, struct xen_netif_tx_request *txp, RING_IDX end) { RING_IDX cons = vif->tx.req_cons; do { make_tx_response(vif, txp, XEN_NETIF_RSP_ERROR); if (cons >= end) break; txp = RING_GET_REQUEST(&vif->tx, cons++); } while (1); vif->tx.req_cons = cons; xen_netbk_check_rx_xenvif(vif); xenvif_put(vif); } Commit Message: xen/netback: don't leak pages on failure in xen_netbk_tx_check_gop. Signed-off-by: Matthew Daley <[email protected]> Reviewed-by: Konrad Rzeszutek Wilk <[email protected]> Acked-by: Ian Campbell <[email protected]> Acked-by: Jan Beulich <[email protected]> Signed-off-by: David S. Miller <[email protected]> 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: sf_open_virtual (SF_VIRTUAL_IO *sfvirtual, int mode, SF_INFO *sfinfo, void *user_data) { SF_PRIVATE *psf ; /* Make sure we have a valid set ot virtual pointers. */ if (sfvirtual->get_filelen == NULL || sfvirtual->seek == NULL || sfvirtual->tell == NULL) { sf_errno = SFE_BAD_VIRTUAL_IO ; snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_get_filelen / vio_seek / vio_tell in SF_VIRTUAL_IO struct.\n") ; return NULL ; } ; if ((mode == SFM_READ || mode == SFM_RDWR) && sfvirtual->read == NULL) { sf_errno = SFE_BAD_VIRTUAL_IO ; snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_read in SF_VIRTUAL_IO struct.\n") ; return NULL ; } ; if ((mode == SFM_WRITE || mode == SFM_RDWR) && sfvirtual->write == NULL) { sf_errno = SFE_BAD_VIRTUAL_IO ; snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_write in SF_VIRTUAL_IO struct.\n") ; return NULL ; } ; if ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL) { sf_errno = SFE_MALLOC_FAILED ; return NULL ; } ; psf_init_files (psf) ; psf->virtual_io = SF_TRUE ; psf->vio = *sfvirtual ; psf->vio_user_data = user_data ; psf->file.mode = mode ; return psf_open_file (psf, sfinfo) ; } /* sf_open_virtual */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119 Target: 1 Example 2: Code: static void __exit hid_exit(void) { hid_debug_exit(); hidraw_exit(); bus_unregister(&hid_bus_type); } Commit Message: HID: core: prevent out-of-bound readings Plugging a Logitech DJ receiver with KASAN activated raises a bunch of out-of-bound readings. The fields are allocated up to MAX_USAGE, meaning that potentially, we do not have enough fields to fit the incoming values. Add checks and silence KASAN. Signed-off-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-125 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: const AtomicString& HTMLKeygenElement::formControlType() const { DEFINE_STATIC_LOCAL(const AtomicString, keygen, ("keygen", AtomicString::ConstructFromLiteral)); return keygen; } Commit Message: Add HTMLFormControlElement::supportsAutofocus to fix a FIXME comment. This virtual function should return true if the form control can hanlde 'autofocucs' attribute if it is specified. Note: HTMLInputElement::supportsAutofocus reuses InputType::isInteractiveContent because interactiveness is required for autofocus capability. BUG=none TEST=none; no behavior changes. Review URL: https://codereview.chromium.org/143343003 git-svn-id: svn://svn.chromium.org/blink/trunk@165432 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: bool NavigatorImpl::NavigateToEntry( FrameTreeNode* frame_tree_node, const FrameNavigationEntry& frame_entry, const NavigationEntryImpl& entry, ReloadType reload_type, bool is_same_document_history_load, bool is_history_navigation_in_new_child, bool is_pending_entry, const scoped_refptr<ResourceRequestBodyImpl>& post_body) { TRACE_EVENT0("browser,navigation", "NavigatorImpl::NavigateToEntry"); GURL dest_url = frame_entry.url(); Referrer dest_referrer = frame_entry.referrer(); if (reload_type == ReloadType::ORIGINAL_REQUEST_URL && entry.GetOriginalRequestURL().is_valid() && !entry.GetHasPostData()) { dest_url = entry.GetOriginalRequestURL(); dest_referrer = Referrer(); } if (!dest_url.is_valid() && !dest_url.is_empty()) { LOG(WARNING) << "Refusing to load invalid URL: " << dest_url.possibly_invalid_spec(); return false; } if (dest_url.spec().size() > url::kMaxURLChars) { LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars << " characters."; return false; } base::TimeTicks navigation_start = base::TimeTicks::Now(); TRACE_EVENT_INSTANT_WITH_TIMESTAMP0( "navigation,rail", "NavigationTiming navigationStart", TRACE_EVENT_SCOPE_GLOBAL, navigation_start); LoFiState lofi_state = LOFI_UNSPECIFIED; if (!frame_tree_node->IsMainFrame()) { lofi_state = frame_tree_node->frame_tree() ->root() ->current_frame_host() ->last_navigation_lofi_state(); } else if (reload_type == ReloadType::DISABLE_LOFI_MODE) { lofi_state = LOFI_OFF; } if (IsBrowserSideNavigationEnabled()) { navigation_data_.reset(new NavigationMetricsData(navigation_start, dest_url, entry.restore_type())); RequestNavigation(frame_tree_node, dest_url, dest_referrer, frame_entry, entry, reload_type, lofi_state, is_same_document_history_load, is_history_navigation_in_new_child, navigation_start); if (frame_tree_node->IsMainFrame() && frame_tree_node->navigation_request()) { TRACE_EVENT_ASYNC_BEGIN_WITH_TIMESTAMP1( "navigation", "Navigation timeToNetworkStack", frame_tree_node->navigation_request()->navigation_handle(), navigation_start, "FrameTreeNode id", frame_tree_node->frame_tree_node_id()); } } else { RenderFrameHostImpl* dest_render_frame_host = frame_tree_node->render_manager()->Navigate( dest_url, frame_entry, entry, reload_type != ReloadType::NONE); if (!dest_render_frame_host) return false; // Unable to create the desired RenderFrameHost. if (is_pending_entry) CHECK_EQ(controller_->GetPendingEntry(), &entry); CheckWebUIRendererDoesNotDisplayNormalURL(dest_render_frame_host, dest_url); bool is_transfer = entry.transferred_global_request_id().child_id != -1; if (is_transfer) dest_render_frame_host->set_is_loading(true); if (is_pending_entry && controller_->GetPendingEntryIndex() != -1) DCHECK(frame_entry.page_state().IsValid()); bool is_transfer_to_same = is_transfer && entry.transferred_global_request_id().child_id == dest_render_frame_host->GetProcess()->GetID(); if (!is_transfer_to_same) { navigation_data_.reset(new NavigationMetricsData( navigation_start, dest_url, entry.restore_type())); FrameMsg_Navigate_Type::Value navigation_type = GetNavigationType( controller_->GetBrowserContext(), entry, reload_type); dest_render_frame_host->Navigate( entry.ConstructCommonNavigationParams( frame_entry, post_body, dest_url, dest_referrer, navigation_type, lofi_state, navigation_start), entry.ConstructStartNavigationParams(), entry.ConstructRequestNavigationParams( frame_entry, is_same_document_history_load, is_history_navigation_in_new_child, entry.GetSubframeUniqueNames(frame_tree_node), frame_tree_node->has_committed_real_load(), controller_->GetPendingEntryIndex() == -1, controller_->GetIndexOfEntry(&entry), controller_->GetLastCommittedEntryIndex(), controller_->GetEntryCount())); } } if (is_pending_entry) CHECK_EQ(controller_->GetPendingEntry(), &entry); if (controller_->GetPendingEntryIndex() == -1 && dest_url.SchemeIs(url::kJavaScriptScheme)) { return false; } if (delegate_ && is_pending_entry) delegate_->DidStartNavigationToPendingEntry(dest_url, reload_type); return true; } Commit Message: Drop navigations to NavigationEntry with invalid virtual URLs. BUG=657720 CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2452443002 Cr-Commit-Position: refs/heads/master@{#428056} CWE ID: CWE-20 Target: 1 Example 2: Code: SetCookiesContext(int request_id) : request_id(request_id), remaining(0) {} 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: ovs_instruction_type_from_ofpact_type(enum ofpact_type type) { switch (type) { case OFPACT_METER: return OVSINST_OFPIT13_METER; case OFPACT_CLEAR_ACTIONS: return OVSINST_OFPIT11_CLEAR_ACTIONS; case OFPACT_WRITE_ACTIONS: return OVSINST_OFPIT11_WRITE_ACTIONS; case OFPACT_WRITE_METADATA: return OVSINST_OFPIT11_WRITE_METADATA; case OFPACT_GOTO_TABLE: return OVSINST_OFPIT11_GOTO_TABLE; case OFPACT_OUTPUT: case OFPACT_GROUP: case OFPACT_CLONE: case OFPACT_CONTROLLER: case OFPACT_ENQUEUE: case OFPACT_OUTPUT_REG: case OFPACT_OUTPUT_TRUNC: case OFPACT_BUNDLE: case OFPACT_SET_VLAN_VID: case OFPACT_SET_VLAN_PCP: case OFPACT_STRIP_VLAN: case OFPACT_PUSH_VLAN: case OFPACT_SET_ETH_SRC: case OFPACT_SET_ETH_DST: case OFPACT_SET_IPV4_SRC: case OFPACT_SET_IPV4_DST: case OFPACT_SET_IP_DSCP: case OFPACT_SET_IP_ECN: case OFPACT_SET_IP_TTL: case OFPACT_SET_L4_SRC_PORT: case OFPACT_SET_L4_DST_PORT: case OFPACT_REG_MOVE: case OFPACT_SET_FIELD: case OFPACT_STACK_PUSH: case OFPACT_STACK_POP: case OFPACT_DEC_TTL: case OFPACT_SET_MPLS_LABEL: case OFPACT_SET_MPLS_TC: case OFPACT_SET_MPLS_TTL: case OFPACT_DEC_MPLS_TTL: case OFPACT_PUSH_MPLS: case OFPACT_POP_MPLS: case OFPACT_SET_TUNNEL: case OFPACT_SET_QUEUE: case OFPACT_POP_QUEUE: case OFPACT_FIN_TIMEOUT: case OFPACT_RESUBMIT: case OFPACT_LEARN: case OFPACT_CONJUNCTION: case OFPACT_MULTIPATH: case OFPACT_NOTE: case OFPACT_EXIT: case OFPACT_UNROLL_XLATE: case OFPACT_SAMPLE: case OFPACT_DEBUG_RECIRC: case OFPACT_CT: case OFPACT_CT_CLEAR: case OFPACT_NAT: default: return OVSINST_OFPIT11_APPLY_ACTIONS; } } Commit Message: ofp-actions: Avoid buffer overread in BUNDLE action decoding. Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9052 Signed-off-by: Ben Pfaff <[email protected]> Acked-by: Justin Pettit <[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: void xgroupCommand(client *c) { const char *help[] = { "CREATE <key> <groupname> <id or $> -- Create a new consumer group.", "SETID <key> <groupname> <id or $> -- Set the current group ID.", "DELGROUP <key> <groupname> -- Remove the specified group.", "DELCONSUMER <key> <groupname> <consumer> -- Remove the specified conusmer.", "HELP -- Prints this help.", NULL }; stream *s = NULL; sds grpname = NULL; streamCG *cg = NULL; char *opt = c->argv[1]->ptr; /* Subcommand name. */ /* Lookup the key now, this is common for all the subcommands but HELP. */ if (c->argc >= 4) { robj *o = lookupKeyWriteOrReply(c,c->argv[2],shared.nokeyerr); if (o == NULL) return; s = o->ptr; grpname = c->argv[3]->ptr; /* Certain subcommands require the group to exist. */ if ((cg = streamLookupCG(s,grpname)) == NULL && (!strcasecmp(opt,"SETID") || !strcasecmp(opt,"DELCONSUMER"))) { addReplyErrorFormat(c, "-NOGROUP No such consumer group '%s' " "for key name '%s'", (char*)grpname, (char*)c->argv[2]->ptr); return; } } /* Dispatch the different subcommands. */ if (!strcasecmp(opt,"CREATE") && c->argc == 5) { streamID id; if (!strcmp(c->argv[4]->ptr,"$")) { id = s->last_id; } else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) { return; } streamCG *cg = streamCreateCG(s,grpname,sdslen(grpname),&id); if (cg) { addReply(c,shared.ok); server.dirty++; } else { addReplySds(c, sdsnew("-BUSYGROUP Consumer Group name already exists\r\n")); } } else if (!strcasecmp(opt,"SETID") && c->argc == 5) { streamID id; if (!strcmp(c->argv[4]->ptr,"$")) { id = s->last_id; } else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) { return; } cg->last_id = id; addReply(c,shared.ok); } else if (!strcasecmp(opt,"DESTROY") && c->argc == 4) { if (cg) { raxRemove(s->cgroups,(unsigned char*)grpname,sdslen(grpname),NULL); streamFreeCG(cg); addReply(c,shared.cone); } else { addReply(c,shared.czero); } } else if (!strcasecmp(opt,"DELCONSUMER") && c->argc == 5) { /* Delete the consumer and returns the number of pending messages * that were yet associated with such a consumer. */ long long pending = streamDelConsumer(cg,c->argv[4]->ptr); addReplyLongLong(c,pending); server.dirty++; } else if (!strcasecmp(opt,"HELP")) { addReplyHelp(c, help); } else { addReply(c,shared.syntaxerr); } } Commit Message: Abort in XGROUP if the key is not a stream CWE ID: CWE-704 Target: 1 Example 2: Code: static int unlazy_walk(struct nameidata *nd) { struct dentry *parent = nd->path.dentry; BUG_ON(!(nd->flags & LOOKUP_RCU)); nd->flags &= ~LOOKUP_RCU; if (unlikely(!legitimize_links(nd))) goto out2; if (unlikely(!legitimize_path(nd, &nd->path, nd->seq))) goto out1; if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) { if (unlikely(!legitimize_path(nd, &nd->root, nd->root_seq))) goto out; } rcu_read_unlock(); BUG_ON(nd->inode != parent->d_inode); return 0; out2: nd->path.mnt = NULL; nd->path.dentry = NULL; out1: if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; out: rcu_read_unlock(); return -ECHILD; } Commit Message: dentry name snapshots take_dentry_name_snapshot() takes a safe snapshot of dentry name; if the name is a short one, it gets copied into caller-supplied structure, otherwise an extra reference to external name is grabbed (those are never modified). In either case the pointer to stable string is stored into the same structure. dentry must be held by the caller of take_dentry_name_snapshot(), but may be freely dropped afterwards - the snapshot will stay until destroyed by release_dentry_name_snapshot(). Intended use: struct name_snapshot s; take_dentry_name_snapshot(&s, dentry); ... access s.name ... release_dentry_name_snapshot(&s); Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name to pass down with event. Signed-off-by: Al Viro <[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: fb_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { unsigned long p = *ppos; struct fb_info *info = file_fb_info(file); u8 *buffer, *dst; u8 __iomem *src; int c, cnt = 0, err = 0; unsigned long total_size; if (!info || ! info->screen_base) return -ENODEV; if (info->state != FBINFO_STATE_RUNNING) return -EPERM; if (info->fbops->fb_read) return info->fbops->fb_read(info, buf, count, ppos); total_size = info->screen_size; if (total_size == 0) total_size = info->fix.smem_len; if (p >= total_size) return 0; if (count >= total_size) count = total_size; if (count + p > total_size) count = total_size - p; buffer = kmalloc((count > PAGE_SIZE) ? PAGE_SIZE : count, GFP_KERNEL); if (!buffer) return -ENOMEM; src = (u8 __iomem *) (info->screen_base + p); if (info->fbops->fb_sync) info->fbops->fb_sync(info); while (count) { c = (count > PAGE_SIZE) ? PAGE_SIZE : count; dst = buffer; fb_memcpy_fromfb(dst, src, c); dst += c; src += c; if (copy_to_user(buf, buffer, c)) { err = -EFAULT; break; } *ppos += c; buf += c; cnt += c; count -= c; } kfree(buffer); return (err) ? err : cnt; } Commit Message: vm: convert fb_mmap to vm_iomap_memory() helper This is my example conversion of a few existing mmap users. The fb_mmap() case is a good example because it is a bit more complicated than some: fb_mmap() mmaps one of two different memory areas depending on the page offset of the mmap (but happily there is never any mixing of the two, so the helper function still works). Signed-off-by: Linus Torvalds <[email protected]> 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: void UpdateUI(const char* current_global_engine_id) { DCHECK(current_global_engine_id); const IBusEngineInfo* engine_info = NULL; for (size_t i = 0; i < arraysize(kIBusEngines); ++i) { if (kIBusEngines[i].name == std::string(current_global_engine_id)) { engine_info = &kIBusEngines[i]; break; } } if (!engine_info) { LOG(ERROR) << current_global_engine_id << " is not found in the input method white-list."; return; } InputMethodDescriptor current_input_method = CreateInputMethodDescriptor(engine_info->name, engine_info->longname, engine_info->layout, engine_info->language); DLOG(INFO) << "Updating the UI. ID:" << current_input_method.id << ", keyboard_layout:" << current_input_method.keyboard_layout; current_input_method_changed_(language_library_, current_input_method); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: CacheQueryResult WebBluetoothServiceImpl::QueryCacheForDevice( const blink::WebBluetoothDeviceId& device_id) { const std::string& device_address = allowed_devices().GetDeviceAddress(device_id); if (device_address.empty()) { CrashRendererAndClosePipe(bad_message::BDH_DEVICE_NOT_ALLOWED_FOR_ORIGIN); return CacheQueryResult(CacheQueryOutcome::BAD_RENDERER); } CacheQueryResult result; result.device = GetAdapter()->GetDevice(device_address); if (result.device == nullptr) { result.outcome = CacheQueryOutcome::NO_DEVICE; } return result; } Commit Message: bluetooth: Implement getAvailability() This change implements the getAvailability() method for navigator.bluetooth as defined in the specification. Bug: 707640 Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516 Reviewed-by: Chris Harrelson <[email protected]> Reviewed-by: Giovanni Ortuño Urquidi <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Cr-Commit-Position: refs/heads/master@{#688987} 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 unsigned int seedsize(struct crypto_alg *alg) { struct rng_alg *ralg = container_of(alg, struct rng_alg, base); return alg->cra_rng.rng_make_random ? alg->cra_rng.seedsize : ralg->seedsize; } Commit Message: crypto: rng - Remove old low-level rng interface Now that all rng implementations have switched over to the new interface, we can remove the old low-level interface. Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-476 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: void SyncManager::MaybeSetSyncTabsInNigoriNode( ModelTypeSet enabled_types) { DCHECK(thread_checker_.CalledOnValidThread()); data_->MaybeSetSyncTabsInNigoriNode(enabled_types); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 Target: 1 Example 2: Code: void Gfx::popResources() { GfxResources *resPtr; resPtr = res->getNext(); delete res; res = resPtr; } 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: void WebContentsImpl::DidStartLoading(FrameTreeNode* frame_tree_node, bool to_different_document) { LoadingStateChanged(to_different_document, false, nullptr); BrowserAccessibilityManager* manager = frame_tree_node->current_frame_host()->browser_accessibility_manager(); if (manager) manager->UserIsNavigatingAway(); } Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen. BUG=670135, 550017, 726761, 728276 Review-Url: https://codereview.chromium.org/2906133004 Cr-Commit-Position: refs/heads/master@{#478884} CWE ID: CWE-20 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 Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_ENCODED 2 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bytes_per_line, extent, length; ssize_t count, y; SUNInfo sun_info; unsigned char *sun_data, *sun_pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SUN raster header. */ (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info)); sun_info.magic=ReadBlobMSBLong(image); do { /* Verify SUN identifier. */ if (sun_info.magic != 0x59a66a95) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); sun_info.width=ReadBlobMSBLong(image); sun_info.height=ReadBlobMSBLong(image); sun_info.depth=ReadBlobMSBLong(image); sun_info.length=ReadBlobMSBLong(image); sun_info.type=ReadBlobMSBLong(image); sun_info.maptype=ReadBlobMSBLong(image); sun_info.maplength=ReadBlobMSBLong(image); extent=sun_info.height*sun_info.width; if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && (sun_info.type != RT_FORMAT_RGB)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.depth == 0) || (sun_info.depth > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && (sun_info.maptype != RMT_RAW)) ThrowReaderException(CoderError,"ColormapTypeNotSupported"); image->columns=sun_info.width; image->rows=sun_info.height; image->depth=sun_info.depth <= 8 ? sun_info.depth : MAGICKCORE_QUANTUM_DEPTH; if (sun_info.depth < 24) { size_t one; image->colors=sun_info.maplength; one=1; if (sun_info.maptype == RMT_NONE) image->colors=one << sun_info.depth; if (sun_info.maptype == RMT_EQUAL_RGB) image->colors=sun_info.maplength/3; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } switch (sun_info.maptype) { case RMT_NONE: break; case RMT_EQUAL_RGB: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } case RMT_RAW: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,sun_info.maplength,sun_colormap); if (count != (ssize_t) sun_info.maplength) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=sun_info.width; image->rows=sun_info.height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) != sun_info.length || !sun_info.length) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); number_pixels=(MagickSizeType) image->columns*image->rows; if ((sun_info.type != RT_ENCODED) && (sun_info.depth >= 8) && ((number_pixels*((sun_info.depth+7)/8)) > sun_info.length)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bytes_per_line=sun_info.width*sun_info.depth; sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax( sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data)); if (sun_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); if (count != (ssize_t) sun_info.length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); sun_pixels=sun_data; bytes_per_line=0; if (sun_info.type == RT_ENCODED) { size_t height; /* Read run-length encoded raster pixels. */ height=sun_info.height; if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || ((bytes_per_line/sun_info.depth) != sun_info.width)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bytes_per_line+=15; bytes_per_line<<=1; if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bytes_per_line>>=4; sun_pixels=(unsigned char *) AcquireQuantumMemory(height, bytes_per_line*sizeof(*sun_pixels)); if (sun_pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line* height); sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); } /* Convert SUN raster image to pixel packets. */ p=sun_pixels; if (sun_info.depth == 1) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=7; bit >= 0; bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01), q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),q); q+=GetPixelChannels(image); } p++; } if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image->storage_class == PseudoClass) { if (bytes_per_line == 0) bytes_per_line=image->columns; length=image->rows*(image->columns+image->columns % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { size_t bytes_per_pixel; bytes_per_pixel=3; if (image->alpha_trait != UndefinedPixelTrait) bytes_per_pixel++; if (bytes_per_line == 0) bytes_per_line=bytes_per_pixel*image->columns; length=image->rows*(bytes_per_line+image->columns % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); if (sun_info.type == RT_STANDARD) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); } else { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); } if (image->colors != 0) { SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelRed(image,q)].red),q); SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelGreen(image,q)].green),q); SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelBlue(image,q)].blue),q); } q+=GetPixelChannels(image); } if (((bytes_per_pixel*image->columns) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (image->storage_class == PseudoClass) (void) SyncImage(image,exception); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; sun_info.magic=ReadBlobMSBLong(image); if (sun_info.magic == 0x59a66a95) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (sun_info.magic == 0x59a66a95); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: http://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=26857 CWE ID: CWE-125 Target: 1 Example 2: Code: ProcQueryColors(ClientPtr client) { ColormapPtr pcmp; int rc; REQUEST(xQueryColorsReq); REQUEST_AT_LEAST_SIZE(xQueryColorsReq); rc = dixLookupResourceByType((void **) &pcmp, stuff->cmap, RT_COLORMAP, client, DixReadAccess); if (rc == Success) { int count; xrgb *prgbs; xQueryColorsReply qcr; count = bytes_to_int32((client->req_len << 2) - sizeof(xQueryColorsReq)); prgbs = calloc(count, sizeof(xrgb)); if (!prgbs && count) return BadAlloc; if ((rc = QueryColors(pcmp, count, (Pixel *) &stuff[1], prgbs, client))) { free(prgbs); return rc; } qcr = (xQueryColorsReply) { .type = X_Reply, .sequenceNumber = client->sequence, .length = bytes_to_int32(count * sizeof(xrgb)), .nColors = count }; WriteReplyToClient(client, sizeof(xQueryColorsReply), &qcr); if (count) { client->pSwapReplyFunc = (ReplySwapPtr) SQColorsExtend; WriteSwappedDataToClient(client, count * sizeof(xrgb), prgbs); } free(prgbs); return Success; } else { client->errorValue = stuff->cmap; return rc; } } 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 sas_register_ports(struct sas_ha_struct *sas_ha) { int i; /* initialize the ports and discovery */ for (i = 0; i < sas_ha->num_phys; i++) { struct asd_sas_port *port = sas_ha->sas_port[i]; sas_init_port(port, sas_ha, i); sas_init_disc(&port->disc, port); } return 0; } Commit Message: scsi: libsas: direct call probe and destruct In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery competing with ata error handling") introduced disco mutex to prevent rediscovery competing with ata error handling and put the whole revalidation in the mutex. But the rphy add/remove needs to wait for the error handling which also grabs the disco mutex. This may leads to dead lock.So the probe and destruct event were introduce to do the rphy add/remove asynchronously and out of the lock. The asynchronously processed workers makes the whole discovery process not atomic, the other events may interrupt the process. For example, if a loss of signal event inserted before the probe event, the sas_deform_port() is called and the port will be deleted. And sas_port_delete() may run before the destruct event, but the port-x:x is the top parent of end device or expander. This leads to a kernel WARNING such as: [ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22' [ 82.042983] ------------[ cut here ]------------ [ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237 sysfs_remove_group+0x94/0xa0 [ 82.043059] Call trace: [ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0 [ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70 [ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308 [ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60 [ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80 [ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0 [ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50 [ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0 [ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0 [ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490 [ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128 [ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50 Make probe and destruct a direct call in the disco and revalidate function, but put them outside the lock. The whole discovery or revalidate won't be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT event are deleted as a result of the direct call. Introduce a new list to destruct the sas_port and put the port delete after the destruct. This makes sure the right order of destroying the sysfs kobject and fix the warning above. In sas_ex_revalidate_domain() have a loop to find all broadcasted device, and sometimes we have a chance to find the same expander twice. Because the sas_port will be deleted at the end of the whole revalidate process, sas_port with the same name cannot be added before this. Otherwise the sysfs will complain of creating duplicate filename. Since the LLDD will send broadcast for every device change, we can only process one expander's revalidation. [mkp: kbuild test robot warning] Signed-off-by: Jason Yan <[email protected]> CC: John Garry <[email protected]> CC: Johannes Thumshirn <[email protected]> CC: Ewan Milne <[email protected]> CC: Christoph Hellwig <[email protected]> CC: Tomas Henzl <[email protected]> CC: Dan Williams <[email protected]> Reviewed-by: Hannes Reinecke <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: 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 handle_stdfmna(struct pt_regs *regs, unsigned long sfar, unsigned long sfsr) { unsigned long pc = regs->tpc; unsigned long tstate = regs->tstate; u32 insn; u64 value; u8 freg; int flag; struct fpustate *f = FPUSTATE; if (tstate & TSTATE_PRIV) die_if_kernel("stdfmna from kernel", regs); perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, sfar); if (test_thread_flag(TIF_32BIT)) pc = (u32)pc; if (get_user(insn, (u32 __user *) pc) != -EFAULT) { int asi = decode_asi(insn, regs); freg = ((insn >> 25) & 0x1e) | ((insn >> 20) & 0x20); value = 0; flag = (freg < 32) ? FPRS_DL : FPRS_DU; if ((asi > ASI_SNFL) || (asi < ASI_P)) goto daex; save_and_clear_fpu(); if (current_thread_info()->fpsaved[0] & flag) value = *(u64 *)&f->regs[freg]; switch (asi) { case ASI_P: case ASI_S: break; case ASI_PL: case ASI_SL: value = __swab64p(&value); break; default: goto daex; } if (put_user (value >> 32, (u32 __user *) sfar) || __put_user ((u32)value, (u32 __user *)(sfar + 4))) goto daex; } else { daex: if (tlb_type == hypervisor) sun4v_data_access_exception(regs, sfar, sfsr); else spitfire_data_access_exception(regs, sfsr, sfar); return; } advance(regs); } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: MagickExport MagickBooleanType SetImageInfo(ImageInfo *image_info, const unsigned int frames,ExceptionInfo *exception) { char component[MagickPathExtent], magic[MagickPathExtent], *q; const MagicInfo *magic_info; const MagickInfo *magick_info; ExceptionInfo *sans_exception; Image *image; MagickBooleanType status; register const char *p; ssize_t count; /* Look for 'image.format' in filename. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); *component='\0'; GetPathComponent(image_info->filename,SubimagePath,component); if (*component != '\0') { /* Look for scene specification (e.g. img0001.pcd[4]). */ if (IsSceneGeometry(component,MagickFalse) == MagickFalse) { if (IsGeometry(component) != MagickFalse) (void) CloneString(&image_info->extract,component); } else { size_t first, last; (void) CloneString(&image_info->scenes,component); image_info->scene=StringToUnsignedLong(image_info->scenes); image_info->number_scenes=image_info->scene; p=image_info->scenes; for (q=(char *) image_info->scenes; *q != '\0'; p++) { while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; first=(size_t) strtol(p,&q,10); last=first; while (isspace((int) ((unsigned char) *q)) != 0) q++; if (*q == '-') last=(size_t) strtol(q+1,&q,10); if (first > last) Swap(first,last); if (first < image_info->scene) image_info->scene=first; if (last > image_info->number_scenes) image_info->number_scenes=last; p=q; } image_info->number_scenes-=image_info->scene-1; } } *component='\0'; if (*image_info->magick == '\0') GetPathComponent(image_info->filename,ExtensionPath,component); #if defined(MAGICKCORE_ZLIB_DELEGATE) if (*component != '\0') if ((LocaleCompare(component,"gz") == 0) || (LocaleCompare(component,"Z") == 0) || (LocaleCompare(component,"svgz") == 0) || (LocaleCompare(component,"wmz") == 0)) { char path[MagickPathExtent]; (void) CopyMagickString(path,image_info->filename,MagickPathExtent); path[strlen(path)-strlen(component)-1]='\0'; GetPathComponent(path,ExtensionPath,component); } #endif #if defined(MAGICKCORE_BZLIB_DELEGATE) if (*component != '\0') if (LocaleCompare(component,"bz2") == 0) { char path[MagickPathExtent]; (void) CopyMagickString(path,image_info->filename,MagickPathExtent); path[strlen(path)-strlen(component)-1]='\0'; GetPathComponent(path,ExtensionPath,component); } #endif image_info->affirm=MagickFalse; sans_exception=AcquireExceptionInfo(); if (*component != '\0') { MagickFormatType format_type; register ssize_t i; static const char *format_type_formats[] = { "AUTOTRACE", "BROWSE", "DCRAW", "EDIT", "LAUNCH", "MPEG:DECODE", "MPEG:ENCODE", "PRINT", "PS:ALPHA", "PS:CMYK", "PS:COLOR", "PS:GRAY", "PS:MONO", "SCAN", "SHOW", "WIN", (char *) NULL }; /* User specified image format. */ (void) CopyMagickString(magic,component,MagickPathExtent); LocaleUpper(magic); /* Look for explicit image formats. */ format_type=UndefinedFormatType; magick_info=GetMagickInfo(magic,sans_exception); if ((magick_info != (const MagickInfo *) NULL) && (magick_info->format_type != UndefinedFormatType)) format_type=magick_info->format_type; i=0; while ((format_type == UndefinedFormatType) && (format_type_formats[i] != (char *) NULL)) { if ((*magic == *format_type_formats[i]) && (LocaleCompare(magic,format_type_formats[i]) == 0)) format_type=ExplicitFormatType; i++; } if (format_type == UndefinedFormatType) (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); else if (format_type == ExplicitFormatType) { image_info->affirm=MagickTrue; (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); } if (LocaleCompare(magic,"RGB") == 0) image_info->affirm=MagickFalse; /* maybe SGI disguised as RGB */ } /* Look for explicit 'format:image' in filename. */ *magic='\0'; GetPathComponent(image_info->filename,MagickPath,magic); if (*magic == '\0') (void) CopyMagickString(magic,image_info->magick,MagickPathExtent); else { /* User specified image format. */ LocaleUpper(magic); if (IsMagickConflict(magic) == MagickFalse) { (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); image_info->affirm=MagickTrue; } } magick_info=GetMagickInfo(magic,sans_exception); sans_exception=DestroyExceptionInfo(sans_exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; GetPathComponent(image_info->filename,CanonicalPath,component); (void) CopyMagickString(image_info->filename,component,MagickPathExtent); if ((image_info->adjoin != MagickFalse) && (frames > 1)) { /* Test for multiple image support (e.g. image%02d.png). */ (void) InterpretImageFilename(image_info,(Image *) NULL, image_info->filename,(int) image_info->scene,component,exception); if ((LocaleCompare(component,image_info->filename) != 0) && (strchr(component,'%') == (char *) NULL)) image_info->adjoin=MagickFalse; } if ((image_info->adjoin != MagickFalse) && (frames > 0)) { /* Some image formats do not support multiple frames per file. */ magick_info=GetMagickInfo(magic,exception); if (magick_info != (const MagickInfo *) NULL) if (GetMagickAdjoin(magick_info) == MagickFalse) image_info->adjoin=MagickFalse; } if (image_info->affirm != MagickFalse) return(MagickTrue); if (frames == 0) { unsigned char *magick; size_t magick_size; /* Determine the image format from the first few bytes of the file. */ magick_size=GetMagicPatternExtent(exception); if (magick_size == 0) return(MagickFalse); image=AcquireImage(image_info,exception); (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } if ((IsBlobSeekable(image) == MagickFalse) || (IsBlobExempt(image) != MagickFalse)) { /* Copy standard input or pipe to temporary file. */ *component='\0'; status=ImageToFile(image,component,exception); (void) CloseBlob(image); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } SetImageInfoFile(image_info,(FILE *) NULL); (void) CopyMagickString(image->filename,component,MagickPathExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } (void) CopyMagickString(image_info->filename,component, MagickPathExtent); image_info->temporary=MagickTrue; } magick=(unsigned char *) AcquireMagickMemory(magick_size); if (magick == (unsigned char *) NULL) { (void) CloseBlob(image); image=DestroyImage(image); return(MagickFalse); } (void) ResetMagickMemory(magick,0,magick_size); count=ReadBlob(image,magick_size,magick); (void) SeekBlob(image,-((MagickOffsetType) count),SEEK_CUR); (void) CloseBlob(image); image=DestroyImage(image); /* Check magic.xml configuration file. */ sans_exception=AcquireExceptionInfo(); magic_info=GetMagicInfo(magick,(size_t) count,sans_exception); magick=(unsigned char *) RelinquishMagickMemory(magick); if ((magic_info != (const MagicInfo *) NULL) && (GetMagicName(magic_info) != (char *) NULL)) { /* Try to use magick_info that was determined earlier by the extension */ if ((magick_info != (const MagickInfo *) NULL) && (GetMagickUseExtension(magick_info) != MagickFalse) && (LocaleCompare(magick_info->module,GetMagicName( magic_info)) == 0)) (void) CopyMagickString(image_info->magick,magick_info->name, MagickPathExtent); else { (void) CopyMagickString(image_info->magick,GetMagicName( magic_info),MagickPathExtent); magick_info=GetMagickInfo(image_info->magick,sans_exception); } if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; sans_exception=DestroyExceptionInfo(sans_exception); return(MagickTrue); } magick_info=GetMagickInfo(image_info->magick,sans_exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; sans_exception=DestroyExceptionInfo(sans_exception); } return(MagickTrue); } Commit Message: Set pixel cache to undefined if any resource limit is exceeded 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: XFixesCreateRegionFromBitmap (Display *dpy, Pixmap bitmap) { XFixesExtDisplayInfo *info = XFixesFindDisplay (dpy); xXFixesCreateRegionFromBitmapReq *req; XserverRegion region; XFixesCheckExtension (dpy, info, 0); LockDisplay (dpy); GetReq (XFixesCreateRegionFromBitmap, req); req->reqType = info->codes->major_opcode; req->xfixesReqType = X_XFixesCreateRegionFromBitmap; region = req->region = XAllocID (dpy); req->bitmap = bitmap; UnlockDisplay (dpy); SyncHandle(); return region; } Commit Message: CWE ID: CWE-190 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 MediaElementAudioSourceHandler::WouldTaintOrigin() { if (MediaElement()->GetWebMediaPlayer()->DidPassCORSAccessCheck()) { return false; } if (!MediaElement()->HasSingleSecurityOrigin()) { return true; } return Context()->WouldTaintOrigin(MediaElement()->currentSrc()); } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732 Target: 1 Example 2: Code: static int hw_break_release_slot(int breakno) { struct perf_event **pevent; int cpu; if (dbg_is_early) return 0; for_each_online_cpu(cpu) { pevent = per_cpu_ptr(breakinfo[breakno].pev, cpu); if (dbg_release_bp_slot(*pevent)) /* * The debugger is responsible for handing the retry on * remove failure. */ return -1; } return 0; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 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 FragmentPaintPropertyTreeBuilder::UpdateCssClip() { DCHECK(properties_); if (NeedsPaintPropertyUpdate()) { if (NeedsCssClip(object_)) { DCHECK(object_.CanContainAbsolutePositionObjects()); OnUpdateClip(properties_->UpdateCssClip( context_.current.clip, ClipPaintPropertyNode::State{context_.current.transform, ToClipRect(ToLayoutBox(object_).ClipRect( context_.current.paint_offset))})); } else { OnClearClip(properties_->ClearCssClip()); } } if (properties_->CssClip()) context_.current.clip = properties_->CssClip(); } 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: 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: int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) { enum InjectionPermission { INJECTION_PERMISSION_UNKNOWN, INJECTION_PERMISSION_GRANTED, INJECTION_PERMISSION_DENIED }; nsecs_t startTime = now(); int32_t displayId = entry->displayId; int32_t action = entry->action; int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK; int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING; InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN; sp<InputWindowHandle> newHoverWindowHandle; const TouchState* oldState = NULL; ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId); if (oldStateIndex >= 0) { oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex); mTempTouchState.copyFrom(*oldState); } bool isSplit = mTempTouchState.split; bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 && (mTempTouchState.deviceId != entry->deviceId || mTempTouchState.source != entry->source || mTempTouchState.displayId != displayId); bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT); bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN || maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction); bool wrongDevice = false; if (newGesture) { bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN; if (switchedDevice && mTempTouchState.down && !down) { #if DEBUG_FOCUS ALOGD("Dropping event because a pointer for a different device is already down."); #endif injectionResult = INPUT_EVENT_INJECTION_FAILED; switchedDevice = false; wrongDevice = true; goto Failed; } mTempTouchState.reset(); mTempTouchState.down = down; mTempTouchState.deviceId = entry->deviceId; mTempTouchState.source = entry->source; mTempTouchState.displayId = displayId; isSplit = false; } if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) { /* Case 1: New splittable pointer going down, or need target for hover or scroll. */ int32_t pointerIndex = getMotionEventActionPointerIndex(action); int32_t x = int32_t(entry->pointerCoords[pointerIndex]. getAxisValue(AMOTION_EVENT_AXIS_X)); int32_t y = int32_t(entry->pointerCoords[pointerIndex]. getAxisValue(AMOTION_EVENT_AXIS_Y)); sp<InputWindowHandle> newTouchedWindowHandle; bool isTouchModal = false; size_t numWindows = mWindowHandles.size(); for (size_t i = 0; i < numWindows; i++) { sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i); const InputWindowInfo* windowInfo = windowHandle->getInfo(); if (windowInfo->displayId != displayId) { continue; // wrong display } int32_t flags = windowInfo->layoutParamsFlags; if (windowInfo->visible) { if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) { isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0; if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) { newTouchedWindowHandle = windowHandle; break; // found touched window, exit window loop } } if (maskedAction == AMOTION_EVENT_ACTION_DOWN && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) { int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE; if (isWindowObscuredAtPointLocked(windowHandle, x, y)) { outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED; } mTempTouchState.addOrUpdateWindow( windowHandle, outsideTargetFlags, BitSet32(0)); } } } if (newTouchedWindowHandle != NULL && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) { isSplit = true; } else if (isSplit) { newTouchedWindowHandle = NULL; } if (newTouchedWindowHandle == NULL) { newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); if (newTouchedWindowHandle == NULL) { ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y); injectionResult = INPUT_EVENT_INJECTION_FAILED; goto Failed; } } int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS; if (isSplit) { targetFlags |= InputTarget::FLAG_SPLIT; } if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) { targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED; } if (isHoverAction) { newHoverWindowHandle = newTouchedWindowHandle; } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) { newHoverWindowHandle = mLastHoverWindowHandle; } BitSet32 pointerIds; if (isSplit) { uint32_t pointerId = entry->pointerProperties[pointerIndex].id; pointerIds.markBit(pointerId); } mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds); } else { /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */ if (! mTempTouchState.down) { #if DEBUG_FOCUS ALOGD("Dropping event because the pointer is not down or we previously " "dropped the pointer down event."); #endif injectionResult = INPUT_EVENT_INJECTION_FAILED; goto Failed; } if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry->pointerCount == 1 && mTempTouchState.isSlippery()) { int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X)); int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y)); sp<InputWindowHandle> oldTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y); if (oldTouchedWindowHandle != newTouchedWindowHandle && newTouchedWindowHandle != NULL) { #if DEBUG_FOCUS ALOGD("Touch is slipping out of window %s into window %s.", oldTouchedWindowHandle->getName().string(), newTouchedWindowHandle->getName().string()); #endif mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle, InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0)); if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) { isSplit = true; } int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER; if (isSplit) { targetFlags |= InputTarget::FLAG_SPLIT; } if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) { targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED; } BitSet32 pointerIds; if (isSplit) { pointerIds.markBit(entry->pointerProperties[0].id); } mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds); } } } if (newHoverWindowHandle != mLastHoverWindowHandle) { if (mLastHoverWindowHandle != NULL) { #if DEBUG_HOVER ALOGD("Sending hover exit event to window %s.", mLastHoverWindowHandle->getName().string()); #endif mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle, InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0)); } if (newHoverWindowHandle != NULL) { #if DEBUG_HOVER ALOGD("Sending hover enter event to window %s.", newHoverWindowHandle->getName().string()); #endif mTempTouchState.addOrUpdateWindow(newHoverWindowHandle, InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0)); } } { bool haveForegroundWindow = false; for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { const TouchedWindow& touchedWindow = mTempTouchState.windows[i]; if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) { haveForegroundWindow = true; if (! checkInjectionPermission(touchedWindow.windowHandle, entry->injectionState)) { injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED; injectionPermission = INJECTION_PERMISSION_DENIED; goto Failed; } } } if (! haveForegroundWindow) { #if DEBUG_FOCUS ALOGD("Dropping event because there is no touched foreground window to receive it."); #endif injectionResult = INPUT_EVENT_INJECTION_FAILED; goto Failed; } injectionPermission = INJECTION_PERMISSION_GRANTED; } if (maskedAction == AMOTION_EVENT_ACTION_DOWN) { sp<InputWindowHandle> foregroundWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid; for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { const TouchedWindow& touchedWindow = mTempTouchState.windows[i]; if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) { sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle; if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) { mTempTouchState.addOrUpdateWindow(inputWindowHandle, InputTarget::FLAG_ZERO_COORDS, BitSet32(0)); } } } } for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { const TouchedWindow& touchedWindow = mTempTouchState.windows[i]; if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) { String8 reason = checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry, "touched"); if (!reason.isEmpty()) { injectionResult = handleTargetsNotReadyLocked(currentTime, entry, NULL, touchedWindow.windowHandle, nextWakeupTime, reason.string()); goto Unresponsive; } } } if (maskedAction == AMOTION_EVENT_ACTION_DOWN) { sp<InputWindowHandle> foregroundWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); if (foregroundWindowHandle->getInfo()->hasWallpaper) { for (size_t i = 0; i < mWindowHandles.size(); i++) { sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i); const InputWindowInfo* info = windowHandle->getInfo(); if (info->displayId == displayId && windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) { mTempTouchState.addOrUpdateWindow(windowHandle, InputTarget::FLAG_WINDOW_IS_OBSCURED | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0)); } } } } injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED; for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i); addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags, touchedWindow.pointerIds, inputTargets); } mTempTouchState.filterNonAsIsTouchWindows(); Failed: if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) { if (checkInjectionPermission(NULL, entry->injectionState)) { injectionPermission = INJECTION_PERMISSION_GRANTED; } else { injectionPermission = INJECTION_PERMISSION_DENIED; } } if (injectionPermission == INJECTION_PERMISSION_GRANTED) { if (!wrongDevice) { if (switchedDevice) { #if DEBUG_FOCUS ALOGD("Conflicting pointer actions: Switched to a different device."); #endif *outConflictingPointerActions = true; } if (isHoverAction) { if (oldState && oldState->down) { #if DEBUG_FOCUS ALOGD("Conflicting pointer actions: Hover received while pointer was down."); #endif *outConflictingPointerActions = true; } mTempTouchState.reset(); if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) { mTempTouchState.deviceId = entry->deviceId; mTempTouchState.source = entry->source; mTempTouchState.displayId = displayId; } } else if (maskedAction == AMOTION_EVENT_ACTION_UP || maskedAction == AMOTION_EVENT_ACTION_CANCEL) { mTempTouchState.reset(); } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) { if (oldState && oldState->down) { #if DEBUG_FOCUS ALOGD("Conflicting pointer actions: Down received while already down."); #endif *outConflictingPointerActions = true; } } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) { if (isSplit) { int32_t pointerIndex = getMotionEventActionPointerIndex(action); uint32_t pointerId = entry->pointerProperties[pointerIndex].id; for (size_t i = 0; i < mTempTouchState.windows.size(); ) { TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i); if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) { touchedWindow.pointerIds.clearBit(pointerId); if (touchedWindow.pointerIds.isEmpty()) { mTempTouchState.windows.removeAt(i); continue; } } i += 1; } } } if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) { if (mTempTouchState.displayId >= 0) { if (oldStateIndex >= 0) { mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState); } else { mTouchStatesByDisplay.add(displayId, mTempTouchState); } } else if (oldStateIndex >= 0) { mTouchStatesByDisplay.removeItemsAt(oldStateIndex); } } mLastHoverWindowHandle = newHoverWindowHandle; } } else { #if DEBUG_FOCUS ALOGD("Not updating touch focus because injection was denied."); #endif } Unresponsive: mTempTouchState.reset(); nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime); updateDispatchStatisticsLocked(currentTime, entry, injectionResult, timeSpentWaitingForApplication); #if DEBUG_FOCUS ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, " "timeSpentWaitingForApplication=%0.1fms", injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0); #endif return injectionResult; } Commit Message: Add new MotionEvent flag for partially obscured windows. Due to more complex window layouts resulting in lots of overlapping windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to only be set when the point at which the window was touched is obscured. Unfortunately, this doesn't prevent tapjacking attacks that overlay the dialog's text, making a potentially dangerous operation seem innocuous. To avoid this on particularly sensitive dialogs, introduce a new flag that really does tell you when your window is being even partially overlapped. We aren't exposing this as API since we plan on making the original flag more robust. This is really a workaround for system dialogs since we generally know their layout and screen position, and that they're unlikely to be overlapped by other applications. Bug: 26677796 Change-Id: I9e336afe90f262ba22015876769a9c510048fd47 CWE ID: CWE-264 Target: 1 Example 2: Code: static jboolean android_net_wifi_startSupplicant(JNIEnv* env, jobject, jboolean p2pSupported) { return (::wifi_start_supplicant(p2pSupported) == 0); } Commit Message: Deal correctly with short strings The parseMacAddress function anticipates only properly formed MAC addresses (6 hexadecimal octets separated by ":"). This change properly deals with situations where the string is shorter than expected, making sure that the passed in char* reference in parseHexByte never exceeds the end of the string. BUG: 28164077 TEST: Added a main function: int main(int argc, char **argv) { unsigned char addr[6]; if (argc > 1) { memset(addr, 0, sizeof(addr)); parseMacAddress(argv[1], addr); printf("Result: %02x:%02x:%02x:%02x:%02x:%02x\n", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); } } Tested with "", "a" "ab" "ab:c" "abxc". Change-Id: I0db8d0037e48b62333d475296a45b22ab0efe386 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: ChromeContentBrowserClient::CreateThrottlesForNavigation( content::NavigationHandle* handle) { std::vector<std::unique_ptr<content::NavigationThrottle>> throttles; if (handle->IsInMainFrame()) { throttles.push_back( page_load_metrics::MetricsNavigationThrottle::Create(handle)); } #if BUILDFLAG(ENABLE_PLUGINS) std::unique_ptr<content::NavigationThrottle> flash_url_throttle = FlashDownloadInterception::MaybeCreateThrottleFor(handle); if (flash_url_throttle) throttles.push_back(std::move(flash_url_throttle)); #endif #if BUILDFLAG(ENABLE_SUPERVISED_USERS) std::unique_ptr<content::NavigationThrottle> supervised_user_throttle = SupervisedUserNavigationThrottle::MaybeCreateThrottleFor(handle); if (supervised_user_throttle) throttles.push_back(std::move(supervised_user_throttle)); #endif #if defined(OS_ANDROID) prerender::PrerenderContents* prerender_contents = prerender::PrerenderContents::FromWebContents(handle->GetWebContents()); if (!prerender_contents && handle->IsInMainFrame()) { throttles.push_back( navigation_interception::InterceptNavigationDelegate::CreateThrottleFor( handle)); } throttles.push_back(InterceptOMADownloadNavigationThrottle::Create(handle)); #elif BUILDFLAG(ENABLE_EXTENSIONS) if (handle->IsInMainFrame()) { auto url_to_app_throttle = PlatformAppNavigationRedirector::MaybeCreateThrottleFor(handle); if (url_to_app_throttle) throttles.push_back(std::move(url_to_app_throttle)); } if (base::FeatureList::IsEnabled(features::kDesktopPWAWindowing)) { if (base::FeatureList::IsEnabled(features::kDesktopPWAsLinkCapturing)) { auto bookmark_app_experimental_throttle = extensions::BookmarkAppExperimentalNavigationThrottle:: MaybeCreateThrottleFor(handle); if (bookmark_app_experimental_throttle) throttles.push_back(std::move(bookmark_app_experimental_throttle)); } else if (!base::FeatureList::IsEnabled( features::kDesktopPWAsStayInWindow)) { auto bookmark_app_throttle = extensions::BookmarkAppNavigationThrottle::MaybeCreateThrottleFor( handle); if (bookmark_app_throttle) throttles.push_back(std::move(bookmark_app_throttle)); } } if (base::FeatureList::IsEnabled( features::kMimeHandlerViewInCrossProcessFrame)) { auto plugin_frame_attach_throttle = extensions::ExtensionsGuestViewMessageFilter::MaybeCreateThrottle( handle); if (plugin_frame_attach_throttle) throttles.push_back(std::move(plugin_frame_attach_throttle)); } #endif #if defined(OS_CHROMEOS) if (handle->IsInMainFrame()) { if (merge_session_throttling_utils::ShouldAttachNavigationThrottle() && !merge_session_throttling_utils::AreAllSessionMergedAlready() && handle->GetURL().SchemeIsHTTPOrHTTPS()) { throttles.push_back(MergeSessionNavigationThrottle::Create(handle)); } auto url_to_apps_throttle = chromeos::AppsNavigationThrottle::MaybeCreate(handle); if (url_to_apps_throttle) throttles.push_back(std::move(url_to_apps_throttle)); } #endif #if BUILDFLAG(ENABLE_EXTENSIONS) throttles.push_back( std::make_unique<extensions::ExtensionNavigationThrottle>(handle)); std::unique_ptr<content::NavigationThrottle> user_script_throttle = extensions::ExtensionsBrowserClient::Get() ->GetUserScriptListener() ->CreateNavigationThrottle(handle); if (user_script_throttle) throttles.push_back(std::move(user_script_throttle)); #endif #if BUILDFLAG(ENABLE_SUPERVISED_USERS) std::unique_ptr<content::NavigationThrottle> supervised_user_nav_throttle = SupervisedUserGoogleAuthNavigationThrottle::MaybeCreate(handle); if (supervised_user_nav_throttle) throttles.push_back(std::move(supervised_user_nav_throttle)); #endif content::WebContents* web_contents = handle->GetWebContents(); if (auto* subresource_filter_client = ChromeSubresourceFilterClient::FromWebContents(web_contents)) { subresource_filter_client->MaybeAppendNavigationThrottles(handle, &throttles); } #if !defined(OS_ANDROID) std::unique_ptr<content::NavigationThrottle> background_tab_navigation_throttle = resource_coordinator:: BackgroundTabNavigationThrottle::MaybeCreateThrottleFor(handle); if (background_tab_navigation_throttle) throttles.push_back(std::move(background_tab_navigation_throttle)); #endif #if defined(SAFE_BROWSING_DB_LOCAL) std::unique_ptr<content::NavigationThrottle> password_protection_navigation_throttle = safe_browsing::MaybeCreateNavigationThrottle(handle); if (password_protection_navigation_throttle) { throttles.push_back(std::move(password_protection_navigation_throttle)); } #endif std::unique_ptr<content::NavigationThrottle> pdf_iframe_throttle = PDFIFrameNavigationThrottle::MaybeCreateThrottleFor(handle); if (pdf_iframe_throttle) throttles.push_back(std::move(pdf_iframe_throttle)); std::unique_ptr<content::NavigationThrottle> tab_under_throttle = TabUnderNavigationThrottle::MaybeCreate(handle); if (tab_under_throttle) throttles.push_back(std::move(tab_under_throttle)); throttles.push_back(std::make_unique<PolicyBlacklistNavigationThrottle>( handle, handle->GetWebContents()->GetBrowserContext())); if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) { throttles.push_back(std::make_unique<SSLErrorNavigationThrottle>( handle, std::make_unique<CertificateReportingServiceCertReporter>(web_contents), base::Bind(&SSLErrorHandler::HandleSSLError))); } std::unique_ptr<content::NavigationThrottle> https_upgrade_timing_throttle = TypedNavigationTimingThrottle::MaybeCreateThrottleFor(handle); if (https_upgrade_timing_throttle) throttles.push_back(std::move(https_upgrade_timing_throttle)); #if !defined(OS_ANDROID) std::unique_ptr<content::NavigationThrottle> devtools_throttle = DevToolsWindow::MaybeCreateNavigationThrottle(handle); if (devtools_throttle) throttles.push_back(std::move(devtools_throttle)); std::unique_ptr<content::NavigationThrottle> new_tab_page_throttle = NewTabPageNavigationThrottle::MaybeCreateThrottleFor(handle); if (new_tab_page_throttle) throttles.push_back(std::move(new_tab_page_throttle)); std::unique_ptr<content::NavigationThrottle> google_password_manager_throttle = GooglePasswordManagerNavigationThrottle::MaybeCreateThrottleFor( handle); if (google_password_manager_throttle) throttles.push_back(std::move(google_password_manager_throttle)); #endif std::unique_ptr<content::NavigationThrottle> previews_lite_page_throttle = PreviewsLitePageDecider::MaybeCreateThrottleFor(handle); if (previews_lite_page_throttle) throttles.push_back(std::move(previews_lite_page_throttle)); if (base::FeatureList::IsEnabled(safe_browsing::kCommittedSBInterstitials)) { throttles.push_back( std::make_unique<safe_browsing::SafeBrowsingNavigationThrottle>( handle)); } #if defined(OS_WIN) || defined(OS_MACOSX) || \ (defined(OS_LINUX) && !defined(OS_CHROMEOS)) std::unique_ptr<content::NavigationThrottle> browser_switcher_throttle = browser_switcher::BrowserSwitcherNavigationThrottle :: MaybeCreateThrottleFor(handle); if (browser_switcher_throttle) throttles.push_back(std::move(browser_switcher_throttle)); #endif return throttles; } Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper This CL is for the most part a mechanical change which extracts almost all the frame-based MimeHandlerView code out of ExtensionsGuestViewMessageFilter. This change both removes the current clutter form EGVMF as well as fixesa race introduced when the frame-based logic was added to EGVMF. The reason for the race was that EGVMF is destroyed on IO thread but all the access to it (for frame-based MHV) are from UI. [email protected],[email protected] Bug: 659750, 896679, 911161, 918861 Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda Reviewed-on: https://chromium-review.googlesource.com/c/1401451 Commit-Queue: Ehsan Karamad <[email protected]> Reviewed-by: James MacLean <[email protected]> Reviewed-by: Ehsan Karamad <[email protected]> Cr-Commit-Position: refs/heads/master@{#621155} CWE ID: CWE-362 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: PHP_METHOD(Phar, loadPhar) { char *fname, *alias = NULL, *error; size_t fname_len, alias_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) { return; } phar_request_initialize(); RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } /* }}} */ /* {{{ proto string Phar::apiVersion() Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: static int handle_vmread(struct kvm_vcpu *vcpu) { unsigned long field; u64 field_value; unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION); u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO); gva_t gva = 0; if (!nested_vmx_check_permission(vcpu) || !nested_vmx_check_vmcs12(vcpu)) return 1; /* Decode instruction info and find the field to read */ field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf)); /* Read the field, zero-extended to a u64 field_value */ if (!vmcs12_read_any(vcpu, field, &field_value)) { nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT); skip_emulated_instruction(vcpu); return 1; } /* * Now copy part of this value to register or memory, as requested. * Note that the number of bits actually copied is 32 or 64 depending * on the guest's mode (32 or 64 bit), not on the given field's length. */ if (vmx_instruction_info & (1u << 10)) { kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf), field_value); } else { if (get_vmx_mem_address(vcpu, exit_qualification, vmx_instruction_info, &gva)) return 1; /* _system ok, as nested_vmx_check_permission verified cpl=0 */ kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva, &field_value, (is_long_mode(vcpu) ? 8 : 4), NULL); } nested_vmx_succeed(vcpu); skip_emulated_instruction(vcpu); return 1; } Commit Message: x86,kvm,vmx: Preserve CR4 across VM entry CR4 isn't constant; at least the TSD and PCE bits can vary. TBH, treating CR0 and CR3 as constant scares me a bit, too, but it looks like it's correct. This adds a branch and a read from cr4 to each vm entry. Because it is extremely likely that consecutive entries into the same vcpu will have the same host cr4 value, this fixes up the vmcs instead of restoring cr4 after the fact. A subsequent patch will add a kernel-wide cr4 shadow, reducing the overhead in the common case to just two memory reads and a branch. Signed-off-by: Andy Lutomirski <[email protected]> Acked-by: Paolo Bonzini <[email protected]> Cc: [email protected] Cc: Petr Matousek <[email protected]> Cc: Gleb Natapov <[email protected]> Signed-off-by: Linus Torvalds <[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: store_image_row(PNG_CONST png_store* ps, png_const_structp pp, int nImage, png_uint_32 y) { png_size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2; if (ps->image == NULL) png_error(pp, "no allocated image"); if (coffset + ps->cb_row + 3 > ps->cb_image) png_error(pp, "image too small"); return ps->image + coffset; } 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: static int get_task_ioprio(struct task_struct *p) { int ret; ret = security_task_getioprio(p); if (ret) goto out; ret = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, IOPRIO_NORM); if (p->io_context) ret = p->io_context->ioprio; out: return ret; } Commit Message: block: fix use-after-free in sys_ioprio_get() get_task_ioprio() accesses the task->io_context without holding the task lock and thus can race with exit_io_context(), leading to a use-after-free. The reproducer below hits this within a few seconds on my 4-core QEMU VM: #define _GNU_SOURCE #include <assert.h> #include <unistd.h> #include <sys/syscall.h> #include <sys/wait.h> int main(int argc, char **argv) { pid_t pid, child; long nproc, i; /* ioprio_set(IOPRIO_WHO_PROCESS, 0, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_IDLE, 0)); */ syscall(SYS_ioprio_set, 1, 0, 0x6000); nproc = sysconf(_SC_NPROCESSORS_ONLN); for (i = 0; i < nproc; i++) { pid = fork(); assert(pid != -1); if (pid == 0) { for (;;) { pid = fork(); assert(pid != -1); if (pid == 0) { _exit(0); } else { child = wait(NULL); assert(child == pid); } } } pid = fork(); assert(pid != -1); if (pid == 0) { for (;;) { /* ioprio_get(IOPRIO_WHO_PGRP, 0); */ syscall(SYS_ioprio_get, 2, 0); } } } for (;;) { /* ioprio_get(IOPRIO_WHO_PGRP, 0); */ syscall(SYS_ioprio_get, 2, 0); } return 0; } This gets us KASAN dumps like this: [ 35.526914] ================================================================== [ 35.530009] BUG: KASAN: out-of-bounds in get_task_ioprio+0x7b/0x90 at addr ffff880066f34e6c [ 35.530009] Read of size 2 by task ioprio-gpf/363 [ 35.530009] ============================================================================= [ 35.530009] BUG blkdev_ioc (Not tainted): kasan: bad access detected [ 35.530009] ----------------------------------------------------------------------------- [ 35.530009] Disabling lock debugging due to kernel taint [ 35.530009] INFO: Allocated in create_task_io_context+0x2b/0x370 age=0 cpu=0 pid=360 [ 35.530009] ___slab_alloc+0x55d/0x5a0 [ 35.530009] __slab_alloc.isra.20+0x2b/0x40 [ 35.530009] kmem_cache_alloc_node+0x84/0x200 [ 35.530009] create_task_io_context+0x2b/0x370 [ 35.530009] get_task_io_context+0x92/0xb0 [ 35.530009] copy_process.part.8+0x5029/0x5660 [ 35.530009] _do_fork+0x155/0x7e0 [ 35.530009] SyS_clone+0x19/0x20 [ 35.530009] do_syscall_64+0x195/0x3a0 [ 35.530009] return_from_SYSCALL_64+0x0/0x6a [ 35.530009] INFO: Freed in put_io_context+0xe7/0x120 age=0 cpu=0 pid=1060 [ 35.530009] __slab_free+0x27b/0x3d0 [ 35.530009] kmem_cache_free+0x1fb/0x220 [ 35.530009] put_io_context+0xe7/0x120 [ 35.530009] put_io_context_active+0x238/0x380 [ 35.530009] exit_io_context+0x66/0x80 [ 35.530009] do_exit+0x158e/0x2b90 [ 35.530009] do_group_exit+0xe5/0x2b0 [ 35.530009] SyS_exit_group+0x1d/0x20 [ 35.530009] entry_SYSCALL_64_fastpath+0x1a/0xa4 [ 35.530009] INFO: Slab 0xffffea00019bcd00 objects=20 used=4 fp=0xffff880066f34ff0 flags=0x1fffe0000004080 [ 35.530009] INFO: Object 0xffff880066f34e58 @offset=3672 fp=0x0000000000000001 [ 35.530009] ================================================================== Fix it by grabbing the task lock while we poke at the io_context. Cc: [email protected] Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Omar Sandoval <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-416 Target: 1 Example 2: Code: GF_Err hnti_Size(GF_Box *s) { return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125 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: eval_js(WebKitWebView * web_view, gchar *script, GString *result) { WebKitWebFrame *frame; JSGlobalContextRef context; JSObjectRef globalobject; JSStringRef var_name; JSStringRef js_script; JSValueRef js_result; JSStringRef js_result_string; size_t js_result_size; js_init(); frame = webkit_web_view_get_main_frame(WEBKIT_WEB_VIEW(web_view)); context = webkit_web_frame_get_global_context(frame); globalobject = JSContextGetGlobalObject(context); /* uzbl javascript namespace */ var_name = JSStringCreateWithUTF8CString("Uzbl"); JSObjectSetProperty(context, globalobject, var_name, JSObjectMake(context, uzbl.js.classref, NULL), kJSClassAttributeNone, NULL); /* evaluate the script and get return value*/ js_script = JSStringCreateWithUTF8CString(script); js_result = JSEvaluateScript(context, js_script, globalobject, NULL, 0, NULL); if (js_result && !JSValueIsUndefined(context, js_result)) { js_result_string = JSValueToStringCopy(context, js_result, NULL); js_result_size = JSStringGetMaximumUTF8CStringSize(js_result_string); if (js_result_size) { char js_result_utf8[js_result_size]; JSStringGetUTF8CString(js_result_string, js_result_utf8, js_result_size); g_string_assign(result, js_result_utf8); } JSStringRelease(js_result_string); } /* cleanup */ JSObjectDeleteProperty(context, globalobject, var_name, NULL); JSStringRelease(var_name); JSStringRelease(js_script); } Commit Message: disable Uzbl javascript object because of security problem. CWE ID: CWE-264 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: w3m_exit(int i) { #ifdef USE_MIGEMO init_migemo(); /* close pipe to migemo */ #endif stopDownload(); deleteFiles(); #ifdef USE_SSL free_ssl_ctx(); #endif disconnectFTP(); #ifdef USE_NNTP disconnectNews(); #endif #ifdef __MINGW32_VERSION WSACleanup(); #endif exit(i); } Commit Message: Make temporary directory safely when ~/.w3m is unwritable CWE ID: CWE-59 Target: 1 Example 2: Code: GDataWapiFeedProcessor::GDataWapiFeedProcessor( GDataDirectoryService* directory_service) : directory_service_(directory_service) { } 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: 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: rx_cache_find(const struct rx_header *rxh, const struct ip *ip, int sport, int32_t *opcode) { int i; struct rx_cache_entry *rxent; uint32_t clip; uint32_t sip; UNALIGNED_MEMCPY(&clip, &ip->ip_dst, sizeof(uint32_t)); UNALIGNED_MEMCPY(&sip, &ip->ip_src, sizeof(uint32_t)); /* Start the search where we last left off */ i = rx_cache_hint; do { rxent = &rx_cache[i]; if (rxent->callnum == EXTRACT_32BITS(&rxh->callNumber) && rxent->client.s_addr == clip && rxent->server.s_addr == sip && rxent->serviceId == EXTRACT_32BITS(&rxh->serviceId) && rxent->dport == sport) { /* We got a match! */ rx_cache_hint = i; *opcode = rxent->opcode; return(1); } if (++i >= RX_CACHE_SIZE) i = 0; } while (i != rx_cache_hint); /* Our search failed */ return(0); } Commit Message: (for 4.9.3) CVE-2018-14466/Rx: fix an over-read bug In rx_cache_insert() and rx_cache_find() properly read the serviceId field of the rx_header structure as a 16-bit integer. When those functions tried to read 32 bits the extra 16 bits could be outside of the bounds checked in rx_print() for the rx_header structure, as serviceId is the last field in that structure. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 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: void P2PQuicStreamImpl::OnStreamReset(const quic::QuicRstStreamFrame& frame) { quic::QuicStream::OnStreamReset(frame); delegate_->OnRemoteReset(); } Commit Message: P2PQuicStream write functionality. This adds the P2PQuicStream::WriteData function and adds tests. It also adds the concept of a write buffered amount, enforcing this at the P2PQuicStreamImpl. Bug: 874296 Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131 Reviewed-on: https://chromium-review.googlesource.com/c/1315534 Commit-Queue: Seth Hampson <[email protected]> Reviewed-by: Henrik Boström <[email protected]> Cr-Commit-Position: refs/heads/master@{#605766} CWE ID: CWE-284 Target: 1 Example 2: Code: static int tls_process_cke_dhe(SSL *s, PACKET *pkt, int *al) { #ifndef OPENSSL_NO_DH EVP_PKEY *skey = NULL; DH *cdh; unsigned int i; BIGNUM *pub_key; const unsigned char *data; EVP_PKEY *ckey = NULL; int ret = 0; if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG); goto err; } skey = s->s3->tmp.pkey; if (skey == NULL) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_MISSING_TMP_DH_KEY); goto err; } if (PACKET_remaining(pkt) == 0L) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_MISSING_TMP_DH_KEY); goto err; } if (!PACKET_get_bytes(pkt, &data, i)) { /* We already checked we have enough data */ *al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR); goto err; } ckey = EVP_PKEY_new(); if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) { SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, SSL_R_BN_LIB); goto err; } cdh = EVP_PKEY_get0_DH(ckey); pub_key = BN_bin2bn(data, i, NULL); if (pub_key == NULL || !DH_set0_key(cdh, pub_key, NULL)) { SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR); if (pub_key != NULL) BN_free(pub_key); goto err; } if (ssl_derive(s, skey, ckey) == 0) { *al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR); goto err; } ret = 1; EVP_PKEY_free(s->s3->tmp.pkey); s->s3->tmp.pkey = NULL; err: EVP_PKEY_free(ckey); return ret; #else /* Should never happen */ *al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_TLS_PROCESS_CKE_DHE, ERR_R_INTERNAL_ERROR); return 0; #endif } Commit Message: 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: static int udf_symlink_filler(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct buffer_head *bh = NULL; unsigned char *symlink; int err = -EIO; unsigned char *p = kmap(page); struct udf_inode_info *iinfo; uint32_t pos; iinfo = UDF_I(inode); pos = udf_block_map(inode, 0); down_read(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr; } else { bh = sb_bread(inode->i_sb, pos); if (!bh) goto out; symlink = bh->b_data; } udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p); brelse(bh); up_read(&iinfo->i_data_sem); SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; out: up_read(&iinfo->i_data_sem); SetPageError(page); kunmap(page); unlock_page(page); return err; } Commit Message: udf: Verify symlink size before loading it UDF specification allows arbitrarily large symlinks. However we support only symlinks at most one block large. Check the length of the symlink so that we don't access memory beyond end of the symlink block. CC: [email protected] Reported-by: Carl Henrik Lunde <[email protected]> Signed-off-by: Jan Kara <[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: static bool ldap_push_filter(struct asn1_data *data, struct ldb_parse_tree *tree) { int i; switch (tree->operation) { case LDB_OP_AND: case LDB_OP_OR: asn1_push_tag(data, ASN1_CONTEXT(tree->operation==LDB_OP_AND?0:1)); for (i=0; i<tree->u.list.num_elements; i++) { if (!ldap_push_filter(data, tree->u.list.elements[i])) { return false; } } asn1_pop_tag(data); break; case LDB_OP_NOT: asn1_push_tag(data, ASN1_CONTEXT(2)); if (!ldap_push_filter(data, tree->u.isnot.child)) { return false; } asn1_pop_tag(data); break; case LDB_OP_EQUALITY: /* equality test */ asn1_push_tag(data, ASN1_CONTEXT(3)); asn1_write_OctetString(data, tree->u.equality.attr, strlen(tree->u.equality.attr)); asn1_write_OctetString(data, tree->u.equality.value.data, tree->u.equality.value.length); asn1_pop_tag(data); break; case LDB_OP_SUBSTRING: /* SubstringFilter ::= SEQUENCE { type AttributeDescription, -- at least one must be present substrings SEQUENCE OF CHOICE { initial [0] LDAPString, any [1] LDAPString, final [2] LDAPString } } */ asn1_push_tag(data, ASN1_CONTEXT(4)); asn1_write_OctetString(data, tree->u.substring.attr, strlen(tree->u.substring.attr)); asn1_push_tag(data, ASN1_SEQUENCE(0)); if (tree->u.substring.chunks && tree->u.substring.chunks[0]) { i = 0; if (!tree->u.substring.start_with_wildcard) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0)); asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i]); asn1_pop_tag(data); i++; } while (tree->u.substring.chunks[i]) { int ctx; if (( ! tree->u.substring.chunks[i + 1]) && (tree->u.substring.end_with_wildcard == 0)) { ctx = 2; } else { ctx = 1; } asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(ctx)); asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i]); asn1_pop_tag(data); i++; } } asn1_pop_tag(data); asn1_pop_tag(data); break; case LDB_OP_GREATER: /* greaterOrEqual test */ asn1_push_tag(data, ASN1_CONTEXT(5)); asn1_write_OctetString(data, tree->u.comparison.attr, strlen(tree->u.comparison.attr)); asn1_write_OctetString(data, tree->u.comparison.value.data, tree->u.comparison.value.length); asn1_pop_tag(data); break; case LDB_OP_LESS: /* lessOrEqual test */ asn1_push_tag(data, ASN1_CONTEXT(6)); asn1_write_OctetString(data, tree->u.comparison.attr, strlen(tree->u.comparison.attr)); asn1_write_OctetString(data, tree->u.comparison.value.data, tree->u.comparison.value.length); asn1_pop_tag(data); break; case LDB_OP_PRESENT: /* present test */ asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(7)); asn1_write_LDAPString(data, tree->u.present.attr); asn1_pop_tag(data); return !data->has_error; case LDB_OP_APPROX: /* approx test */ asn1_push_tag(data, ASN1_CONTEXT(8)); asn1_write_OctetString(data, tree->u.comparison.attr, strlen(tree->u.comparison.attr)); asn1_write_OctetString(data, tree->u.comparison.value.data, tree->u.comparison.value.length); asn1_pop_tag(data); break; case LDB_OP_EXTENDED: /* MatchingRuleAssertion ::= SEQUENCE { matchingRule [1] MatchingRuleID OPTIONAL, type [2] AttributeDescription OPTIONAL, matchValue [3] AssertionValue, dnAttributes [4] BOOLEAN DEFAULT FALSE } */ asn1_push_tag(data, ASN1_CONTEXT(9)); if (tree->u.extended.rule_id) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1)); asn1_write_LDAPString(data, tree->u.extended.rule_id); asn1_pop_tag(data); } if (tree->u.extended.attr) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(2)); asn1_write_LDAPString(data, tree->u.extended.attr); asn1_pop_tag(data); } asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(3)); asn1_write_DATA_BLOB_LDAPString(data, &tree->u.extended.value); asn1_pop_tag(data); asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(4)); asn1_write_uint8(data, tree->u.extended.dnAttributes); asn1_pop_tag(data); asn1_pop_tag(data); break; default: return false; } return !data->has_error; } Commit Message: CWE ID: CWE-399 Target: 1 Example 2: Code: void native_flush_tlb_others(const struct cpumask *cpumask, struct mm_struct *mm, unsigned long start, unsigned long end) { struct flush_tlb_info info; info.flush_mm = mm; info.flush_start = start; info.flush_end = end; count_vm_tlb_event(NR_TLB_REMOTE_FLUSH); trace_tlb_flush(TLB_REMOTE_SEND_IPI, end - start); if (is_uv_system()) { unsigned int cpu; cpu = smp_processor_id(); cpumask = uv_flush_tlb_others(cpumask, mm, start, end, cpu); if (cpumask) smp_call_function_many(cpumask, flush_tlb_func, &info, 1); return; } smp_call_function_many(cpumask, flush_tlb_func, &info, 1); } Commit Message: x86/mm: Add barriers and document switch_mm()-vs-flush synchronization When switch_mm() activates a new PGD, it also sets a bit that tells other CPUs that the PGD is in use so that TLB flush IPIs will be sent. In order for that to work correctly, the bit needs to be visible prior to loading the PGD and therefore starting to fill the local TLB. Document all the barriers that make this work correctly and add a couple that were missing. Signed-off-by: Andy Lutomirski <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Andy Lutomirski <[email protected]> Cc: Borislav Petkov <[email protected]> Cc: Brian Gerst <[email protected]> Cc: Dave Hansen <[email protected]> Cc: Denys Vlasenko <[email protected]> Cc: H. Peter Anvin <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Rik van Riel <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: [email protected] Cc: [email protected] Signed-off-by: Ingo Molnar <[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: RenderFrameImpl::PendingNavigationInfo::PendingNavigationInfo( const NavigationPolicyInfo& info) : navigation_type(info.navigation_type), policy(info.default_policy), replaces_current_history_item(info.replaces_current_history_item), history_navigation_in_new_child_frame( info.is_history_navigation_in_new_child_frame), client_redirect(info.is_client_redirect), triggering_event_info(info.triggering_event_info), form(info.form), source_location(info.source_location) {} Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#533790} 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 int decode_slice_header(H264Context *h, H264Context *h0) { unsigned int first_mb_in_slice; unsigned int pps_id; int ret; unsigned int slice_type, tmp, i, j; int last_pic_structure, last_pic_droppable; int must_reinit; int needs_reinit = 0; int field_pic_flag, bottom_field_flag; h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab; h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab; first_mb_in_slice = get_ue_golomb_long(&h->gb); if (first_mb_in_slice == 0) { // FIXME better field boundary detection if (h0->current_slice && FIELD_PICTURE(h)) { field_end(h, 1); } h0->current_slice = 0; if (!h0->first_field) { if (h->cur_pic_ptr && !h->droppable) { ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, h->picture_structure == PICT_BOTTOM_FIELD); } h->cur_pic_ptr = NULL; } } slice_type = get_ue_golomb_31(&h->gb); if (slice_type > 9) { av_log(h->avctx, AV_LOG_ERROR, "slice type too large (%d) at %d %d\n", slice_type, h->mb_x, h->mb_y); return AVERROR_INVALIDDATA; } if (slice_type > 4) { slice_type -= 5; h->slice_type_fixed = 1; } else h->slice_type_fixed = 0; slice_type = golomb_to_pict_type[slice_type]; h->slice_type = slice_type; h->slice_type_nos = slice_type & 3; h->pict_type = h->slice_type; pps_id = get_ue_golomb(&h->gb); if (pps_id >= MAX_PPS_COUNT) { av_log(h->avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id); return AVERROR_INVALIDDATA; } if (!h0->pps_buffers[pps_id]) { av_log(h->avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id); return AVERROR_INVALIDDATA; } h->pps = *h0->pps_buffers[pps_id]; if (!h0->sps_buffers[h->pps.sps_id]) { av_log(h->avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id); return AVERROR_INVALIDDATA; } if (h->pps.sps_id != h->current_sps_id || h0->sps_buffers[h->pps.sps_id]->new) { h0->sps_buffers[h->pps.sps_id]->new = 0; h->current_sps_id = h->pps.sps_id; h->sps = *h0->sps_buffers[h->pps.sps_id]; if (h->mb_width != h->sps.mb_width || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma || h->cur_chroma_format_idc != h->sps.chroma_format_idc ) needs_reinit = 1; if (h->bit_depth_luma != h->sps.bit_depth_luma || h->chroma_format_idc != h->sps.chroma_format_idc) { h->bit_depth_luma = h->sps.bit_depth_luma; h->chroma_format_idc = h->sps.chroma_format_idc; needs_reinit = 1; } if ((ret = h264_set_parameter_from_sps(h)) < 0) return ret; } h->avctx->profile = ff_h264_get_profile(&h->sps); h->avctx->level = h->sps.level_idc; h->avctx->refs = h->sps.ref_frame_count; must_reinit = (h->context_initialized && ( 16*h->sps.mb_width != h->avctx->coded_width || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma || h->cur_chroma_format_idc != h->sps.chroma_format_idc || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio) || h->mb_width != h->sps.mb_width || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) )); if (h0->avctx->pix_fmt != get_pixel_format(h0, 0)) must_reinit = 1; h->mb_width = h->sps.mb_width; h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag); h->mb_num = h->mb_width * h->mb_height; h->mb_stride = h->mb_width + 1; h->b_stride = h->mb_width * 4; h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p h->width = 16 * h->mb_width; h->height = 16 * h->mb_height; ret = init_dimensions(h); if (ret < 0) return ret; if (h->sps.video_signal_type_present_flag) { h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; if (h->sps.colour_description_present_flag) { if (h->avctx->colorspace != h->sps.colorspace) needs_reinit = 1; h->avctx->color_primaries = h->sps.color_primaries; h->avctx->color_trc = h->sps.color_trc; h->avctx->colorspace = h->sps.colorspace; } } if (h->context_initialized && (h->width != h->avctx->coded_width || h->height != h->avctx->coded_height || must_reinit || needs_reinit)) { if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, "changing width/height on " "slice %d\n", h0->current_slice + 1); return AVERROR_INVALIDDATA; } flush_change(h); if ((ret = get_pixel_format(h, 1)) < 0) return ret; h->avctx->pix_fmt = ret; av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, " "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt)); if ((ret = h264_slice_header_init(h, 1)) < 0) { av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed\n"); return ret; } } if (!h->context_initialized) { if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, "Cannot (re-)initialize context during parallel decoding.\n"); return AVERROR_PATCHWELCOME; } if ((ret = get_pixel_format(h, 1)) < 0) return ret; h->avctx->pix_fmt = ret; if ((ret = h264_slice_header_init(h, 0)) < 0) { av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed\n"); return ret; } } if (h == h0 && h->dequant_coeff_pps != pps_id) { h->dequant_coeff_pps = pps_id; init_dequant_tables(h); } h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num); h->mb_mbaff = 0; h->mb_aff_frame = 0; last_pic_structure = h0->picture_structure; last_pic_droppable = h0->droppable; h->droppable = h->nal_ref_idc == 0; if (h->sps.frame_mbs_only_flag) { h->picture_structure = PICT_FRAME; } else { if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) { av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n"); return -1; } field_pic_flag = get_bits1(&h->gb); if (field_pic_flag) { bottom_field_flag = get_bits1(&h->gb); h->picture_structure = PICT_TOP_FIELD + bottom_field_flag; } else { h->picture_structure = PICT_FRAME; h->mb_aff_frame = h->sps.mb_aff; } } h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME; if (h0->current_slice != 0) { if (last_pic_structure != h->picture_structure || last_pic_droppable != h->droppable) { av_log(h->avctx, AV_LOG_ERROR, "Changing field mode (%d -> %d) between slices is not allowed\n", last_pic_structure, h->picture_structure); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_INVALIDDATA; } else if (!h0->cur_pic_ptr) { av_log(h->avctx, AV_LOG_ERROR, "unset cur_pic_ptr on %d. slice\n", h0->current_slice + 1); return AVERROR_INVALIDDATA; } } else { /* Shorten frame num gaps so we don't have to allocate reference * frames just to throw them away */ if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) { int unwrap_prev_frame_num = h->prev_frame_num; int max_frame_num = 1 << h->sps.log2_max_frame_num; if (unwrap_prev_frame_num > h->frame_num) unwrap_prev_frame_num -= max_frame_num; if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) { unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1; if (unwrap_prev_frame_num < 0) unwrap_prev_frame_num += max_frame_num; h->prev_frame_num = unwrap_prev_frame_num; } } /* See if we have a decoded first field looking for a pair... * Here, we're using that to see if we should mark previously * decode frames as "finished". * We have to do that before the "dummy" in-between frame allocation, * since that can modify h->cur_pic_ptr. */ if (h0->first_field) { assert(h0->cur_pic_ptr); assert(h0->cur_pic_ptr->f.data[0]); assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF); /* Mark old field/frame as completed */ if (!last_pic_droppable && h0->cur_pic_ptr->tf.owner == h0->avctx) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_BOTTOM_FIELD); } /* figure out if we have a complementary field pair */ if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) { /* Previous field is unmatched. Don't display it, but let it * remain for reference if marked as such. */ if (!last_pic_droppable && last_pic_structure != PICT_FRAME) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_TOP_FIELD); } } else { if (h0->cur_pic_ptr->frame_num != h->frame_num) { /* This and previous field were reference, but had * different frame_nums. Consider this field first in * pair. Throw away previous field except for reference * purposes. */ if (!last_pic_droppable && last_pic_structure != PICT_FRAME) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_TOP_FIELD); } } else { /* Second field in complementary pair */ if (!((last_pic_structure == PICT_TOP_FIELD && h->picture_structure == PICT_BOTTOM_FIELD) || (last_pic_structure == PICT_BOTTOM_FIELD && h->picture_structure == PICT_TOP_FIELD))) { av_log(h->avctx, AV_LOG_ERROR, "Invalid field mode combination %d/%d\n", last_pic_structure, h->picture_structure); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_INVALIDDATA; } else if (last_pic_droppable != h->droppable) { avpriv_request_sample(h->avctx, "Found reference and non-reference fields in the same frame, which"); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_PATCHWELCOME; } } } } while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 && !h0->first_field && h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) { Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL; av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num); if (!h->sps.gaps_in_frame_num_allowed_flag) for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++) h->last_pocs[i] = INT_MIN; ret = h264_frame_start(h); if (ret < 0) return ret; h->prev_frame_num++; h->prev_frame_num %= 1 << h->sps.log2_max_frame_num; h->cur_pic_ptr->frame_num = h->prev_frame_num; ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0); ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1); ret = ff_generate_sliding_window_mmcos(h, 1); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return ret; ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return ret; /* Error concealment: If a ref is missing, copy the previous ref * in its place. * FIXME: Avoiding a memcpy would be nice, but ref handling makes * many assumptions about there being no actual duplicates. * FIXME: This does not copy padding for out-of-frame motion * vectors. Given we are concealing a lost frame, this probably * is not noticeable by comparison, but it should be fixed. */ if (h->short_ref_count) { if (prev) { av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize, (const uint8_t **)prev->f.data, prev->f.linesize, h->avctx->pix_fmt, h->mb_width * 16, h->mb_height * 16); h->short_ref[0]->poc = prev->poc + 2; } h->short_ref[0]->frame_num = h->prev_frame_num; } } /* See if we have a decoded first field looking for a pair... * We're using that to see whether to continue decoding in that * frame, or to allocate a new one. */ if (h0->first_field) { assert(h0->cur_pic_ptr); assert(h0->cur_pic_ptr->f.data[0]); assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF); /* figure out if we have a complementary field pair */ if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) { /* Previous field is unmatched. Don't display it, but let it * remain for reference if marked as such. */ h0->cur_pic_ptr = NULL; h0->first_field = FIELD_PICTURE(h); } else { if (h0->cur_pic_ptr->frame_num != h->frame_num) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, h0->picture_structure==PICT_BOTTOM_FIELD); /* This and the previous field had different frame_nums. * Consider this field first in pair. Throw away previous * one except for reference purposes. */ h0->first_field = 1; h0->cur_pic_ptr = NULL; } else { /* Second field in complementary pair */ h0->first_field = 0; } } } else { /* Frame or first field in a potentially complementary pair */ h0->first_field = FIELD_PICTURE(h); } if (!FIELD_PICTURE(h) || h0->first_field) { if (h264_frame_start(h) < 0) { h0->first_field = 0; return AVERROR_INVALIDDATA; } } else { release_unused_pictures(h, 0); } /* Some macroblocks can be accessed before they're available in case * of lost slices, MBAFF or threading. */ if (FIELD_PICTURE(h)) { for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++) memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table)); } else { memset(h->slice_table, -1, (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table)); } h0->last_slice_type = -1; } if (h != h0 && (ret = clone_slice(h, h0)) < 0) return ret; /* can't be in alloc_tables because linesize isn't known there. * FIXME: redo bipred weight to not require extra buffer? */ for (i = 0; i < h->slice_context_count; i++) if (h->thread_context[i]) { ret = alloc_scratch_buffers(h->thread_context[i], h->linesize); if (ret < 0) return ret; } h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup av_assert1(h->mb_num == h->mb_width * h->mb_height); if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num || first_mb_in_slice >= h->mb_num) { av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n"); return AVERROR_INVALIDDATA; } h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width; h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) << FIELD_OR_MBAFF_PICTURE(h); if (h->picture_structure == PICT_BOTTOM_FIELD) h->resync_mb_y = h->mb_y = h->mb_y + 1; av_assert1(h->mb_y < h->mb_height); if (h->picture_structure == PICT_FRAME) { h->curr_pic_num = h->frame_num; h->max_pic_num = 1 << h->sps.log2_max_frame_num; } else { h->curr_pic_num = 2 * h->frame_num + 1; h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1); } if (h->nal_unit_type == NAL_IDR_SLICE) get_ue_golomb(&h->gb); /* idr_pic_id */ if (h->sps.poc_type == 0) { h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb); if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME) h->delta_poc_bottom = get_se_golomb(&h->gb); } if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) { h->delta_poc[0] = get_se_golomb(&h->gb); if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME) h->delta_poc[1] = get_se_golomb(&h->gb); } ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc); if (h->pps.redundant_pic_cnt_present) h->redundant_pic_count = get_ue_golomb(&h->gb); ret = ff_set_ref_count(h); if (ret < 0) return ret; if (slice_type != AV_PICTURE_TYPE_I && (h0->current_slice == 0 || slice_type != h0->last_slice_type || memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) { ff_h264_fill_default_ref_list(h); } if (h->slice_type_nos != AV_PICTURE_TYPE_I) { ret = ff_h264_decode_ref_pic_list_reordering(h); if (ret < 0) { h->ref_count[1] = h->ref_count[0] = 0; return ret; } } if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) || (h->pps.weighted_bipred_idc == 1 && h->slice_type_nos == AV_PICTURE_TYPE_B)) ff_pred_weight_table(h); else if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) { implicit_weight_table(h, -1); } else { h->use_weight = 0; for (i = 0; i < 2; i++) { h->luma_weight_flag[i] = 0; h->chroma_weight_flag[i] = 0; } } if (h->nal_ref_idc) { ret = ff_h264_decode_ref_pic_marking(h0, &h->gb, !(h->avctx->active_thread_type & FF_THREAD_FRAME) || h0->current_slice == 0); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return AVERROR_INVALIDDATA; } if (FRAME_MBAFF(h)) { ff_h264_fill_mbaff_ref_list(h); if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) { implicit_weight_table(h, 0); implicit_weight_table(h, 1); } } if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred) ff_h264_direct_dist_scale_factor(h); ff_h264_direct_ref_list_init(h); if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) { tmp = get_ue_golomb_31(&h->gb); if (tmp > 2) { av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n"); return AVERROR_INVALIDDATA; } h->cabac_init_idc = tmp; } h->last_qscale_diff = 0; tmp = h->pps.init_qp + get_se_golomb(&h->gb); if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) { av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp); return AVERROR_INVALIDDATA; } h->qscale = tmp; h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale); h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale); if (h->slice_type == AV_PICTURE_TYPE_SP) get_bits1(&h->gb); /* sp_for_switch_flag */ if (h->slice_type == AV_PICTURE_TYPE_SP || h->slice_type == AV_PICTURE_TYPE_SI) get_se_golomb(&h->gb); /* slice_qs_delta */ h->deblocking_filter = 1; h->slice_alpha_c0_offset = 52; h->slice_beta_offset = 52; if (h->pps.deblocking_filter_parameters_present) { tmp = get_ue_golomb_31(&h->gb); if (tmp > 2) { av_log(h->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp); return AVERROR_INVALIDDATA; } h->deblocking_filter = tmp; if (h->deblocking_filter < 2) h->deblocking_filter ^= 1; // 1<->0 if (h->deblocking_filter) { h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1; h->slice_beta_offset += get_se_golomb(&h->gb) << 1; if (h->slice_alpha_c0_offset > 104U || h->slice_beta_offset > 104U) { av_log(h->avctx, AV_LOG_ERROR, "deblocking filter parameters %d %d out of range\n", h->slice_alpha_c0_offset, h->slice_beta_offset); return AVERROR_INVALIDDATA; } } } if (h->avctx->skip_loop_filter >= AVDISCARD_ALL || (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != AV_PICTURE_TYPE_I) || (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type_nos == AV_PICTURE_TYPE_B) || (h->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0)) h->deblocking_filter = 0; if (h->deblocking_filter == 1 && h0->max_contexts > 1) { if (h->avctx->flags2 & CODEC_FLAG2_FAST) { /* Cheat slightly for speed: * Do not bother to deblock across slices. */ h->deblocking_filter = 2; } else { h0->max_contexts = 1; if (!h0->single_decode_warning) { av_log(h->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n"); h0->single_decode_warning = 1; } if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, "Deblocking switched inside frame.\n"); return 1; } } } h->qp_thresh = 15 + 52 - FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) - FFMAX3(0, h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1]) + 6 * (h->sps.bit_depth_luma - 8); h0->last_slice_type = slice_type; memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count)); h->slice_num = ++h0->current_slice; if (h->slice_num) h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y; if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y && h->slice_num >= MAX_SLICES) { av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES); } for (j = 0; j < 2; j++) { int id_list[16]; int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j]; for (i = 0; i < 16; i++) { id_list[i] = 60; if (j < h->list_count && i < h->ref_count[j] && h->ref_list[j][i].f.buf[0]) { int k; AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer; for (k = 0; k < h->short_ref_count; k++) if (h->short_ref[k]->f.buf[0]->buffer == buf) { id_list[i] = k; break; } for (k = 0; k < h->long_ref_count; k++) if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) { id_list[i] = h->short_ref_count + k; break; } } } ref2frm[0] = ref2frm[1] = -1; for (i = 0; i < 16; i++) ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3); ref2frm[18 + 0] = ref2frm[18 + 1] = -1; for (i = 16; i < 48; i++) ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] + (h->ref_list[j][i].reference & 3); } if (h->ref_count[0]) h->er.last_pic = &h->ref_list[0][0]; if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0]; h->er.ref_count = h->ref_count[0]; if (h->avctx->debug & FF_DEBUG_PICT_INFO) { av_log(h->avctx, AV_LOG_DEBUG, "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n", h->slice_num, (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"), first_mb_in_slice, av_get_picture_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "", pps_id, h->frame_num, h->cur_pic_ptr->field_poc[0], h->cur_pic_ptr->field_poc[1], h->ref_count[0], h->ref_count[1], h->qscale, h->deblocking_filter, h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26, h->use_weight, h->use_weight == 1 && h->use_weight_chroma ? "c" : "", h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""); } return 0; } Commit Message: avcodec/h264: do not trust last_pic_droppable when marking pictures as done This simplifies the code and fixes a deadlock Fixes Ticket2927 Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: Target: 1 Example 2: Code: void InputDispatcher::InjectionState::release() { refCount -= 1; if (refCount == 0) { delete this; } else { ALOG_ASSERT(refCount > 0); } } Commit Message: Add new MotionEvent flag for partially obscured windows. Due to more complex window layouts resulting in lots of overlapping windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to only be set when the point at which the window was touched is obscured. Unfortunately, this doesn't prevent tapjacking attacks that overlay the dialog's text, making a potentially dangerous operation seem innocuous. To avoid this on particularly sensitive dialogs, introduce a new flag that really does tell you when your window is being even partially overlapped. We aren't exposing this as API since we plan on making the original flag more robust. This is really a workaround for system dialogs since we generally know their layout and screen position, and that they're unlikely to be overlapped by other applications. Bug: 26677796 Change-Id: I9e336afe90f262ba22015876769a9c510048fd47 CWE ID: CWE-264 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 __exit pppoe_exit(void) { unregister_netdevice_notifier(&pppoe_notifier); dev_remove_pack(&pppoed_ptype); dev_remove_pack(&pppoes_ptype); unregister_pppox_proto(PX_PROTO_OE); proto_unregister(&pppoe_sk_proto); unregister_pernet_device(&pppoe_net_ops); } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 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 SetDelegateOnIO(content::ResourceDispatcherHostDelegate* new_delegate) { content::ResourceDispatcherHost::Get()->SetDelegate(new_delegate); } Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service. The functionality worked, as part of converting DICE, however the test code didn't work since it depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to better match production, which removes the dependency on net/. Also: -make GetFilePathWithReplacements replace strings in the mock headers if they're present -add a global to google_util to ignore ports; that way other tests can be converted without having to modify each callsite to google_util Bug: 881976 Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058 Reviewed-on: https://chromium-review.googlesource.com/c/1328142 Commit-Queue: John Abd-El-Malek <[email protected]> Reviewed-by: Ramin Halavati <[email protected]> Reviewed-by: Maks Orlovich <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#607652} CWE ID: Target: 1 Example 2: Code: static inline int is_real_num_char(int c) { return (c >= '0' && c <= '9') || c == 'e' || c == 'E' || c == '+' || c == '-' || c == '.'; } 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 ctr_crypt_final(struct crypto_aes_ctx *ctx, struct blkcipher_walk *walk) { u8 *ctrblk = walk->iv; u8 keystream[AES_BLOCK_SIZE]; u8 *src = walk->src.virt.addr; u8 *dst = walk->dst.virt.addr; unsigned int nbytes = walk->nbytes; aesni_enc(ctx, keystream, ctrblk); crypto_xor(keystream, src, nbytes); memcpy(dst, keystream, nbytes); crypto_inc(ctrblk, AES_BLOCK_SIZE); } Commit Message: crypto: aesni - fix memory usage in GCM decryption The kernel crypto API logic requires the caller to provide the length of (ciphertext || authentication tag) as cryptlen for the AEAD decryption operation. Thus, the cipher implementation must calculate the size of the plaintext output itself and cannot simply use cryptlen. The RFC4106 GCM decryption operation tries to overwrite cryptlen memory in req->dst. As the destination buffer for decryption only needs to hold the plaintext memory but cryptlen references the input buffer holding (ciphertext || authentication tag), the assumption of the destination buffer length in RFC4106 GCM operation leads to a too large size. This patch simply uses the already calculated plaintext size. In addition, this patch fixes the offset calculation of the AAD buffer pointer: as mentioned before, cryptlen already includes the size of the tag. Thus, the tag does not need to be added. With the addition, the AAD will be written beyond the already allocated buffer. Note, this fixes a kernel crash that can be triggered from user space via AF_ALG(aead) -- simply use the libkcapi test application from [1] and update it to use rfc4106-gcm-aes. Using [1], the changes were tested using CAVS vectors to demonstrate that the crypto operation still delivers the right results. [1] http://www.chronox.de/libkcapi.html CC: Tadeusz Struk <[email protected]> Cc: [email protected] Signed-off-by: Stephan Mueller <[email protected]> Signed-off-by: Herbert Xu <[email protected]> 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: key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags, key_perm_t perm) { struct keyring_search_context ctx = { .match_data.cmp = lookup_user_key_possessed, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = KEYRING_SEARCH_NO_STATE_CHECK, }; struct request_key_auth *rka; struct key *key; key_ref_t key_ref, skey_ref; int ret; try_again: ctx.cred = get_current_cred(); key_ref = ERR_PTR(-ENOKEY); switch (id) { case KEY_SPEC_THREAD_KEYRING: if (!ctx.cred->thread_keyring) { if (!(lflags & KEY_LOOKUP_CREATE)) goto error; ret = install_thread_keyring(); if (ret < 0) { key_ref = ERR_PTR(ret); goto error; } goto reget_creds; } key = ctx.cred->thread_keyring; __key_get(key); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_PROCESS_KEYRING: if (!ctx.cred->process_keyring) { if (!(lflags & KEY_LOOKUP_CREATE)) goto error; ret = install_process_keyring(); if (ret < 0) { key_ref = ERR_PTR(ret); goto error; } goto reget_creds; } key = ctx.cred->process_keyring; __key_get(key); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_SESSION_KEYRING: if (!ctx.cred->session_keyring) { /* always install a session keyring upon access if one * doesn't exist yet */ ret = install_user_keyrings(); if (ret < 0) goto error; if (lflags & KEY_LOOKUP_CREATE) ret = join_session_keyring(NULL); else ret = install_session_keyring( ctx.cred->user->session_keyring); if (ret < 0) goto error; goto reget_creds; } else if (ctx.cred->session_keyring == ctx.cred->user->session_keyring && lflags & KEY_LOOKUP_CREATE) { ret = join_session_keyring(NULL); if (ret < 0) goto error; goto reget_creds; } rcu_read_lock(); key = rcu_dereference(ctx.cred->session_keyring); __key_get(key); rcu_read_unlock(); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_USER_KEYRING: if (!ctx.cred->user->uid_keyring) { ret = install_user_keyrings(); if (ret < 0) goto error; } key = ctx.cred->user->uid_keyring; __key_get(key); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_USER_SESSION_KEYRING: if (!ctx.cred->user->session_keyring) { ret = install_user_keyrings(); if (ret < 0) goto error; } key = ctx.cred->user->session_keyring; __key_get(key); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_GROUP_KEYRING: /* group keyrings are not yet supported */ key_ref = ERR_PTR(-EINVAL); goto error; case KEY_SPEC_REQKEY_AUTH_KEY: key = ctx.cred->request_key_auth; if (!key) goto error; __key_get(key); key_ref = make_key_ref(key, 1); break; case KEY_SPEC_REQUESTOR_KEYRING: if (!ctx.cred->request_key_auth) goto error; down_read(&ctx.cred->request_key_auth->sem); if (test_bit(KEY_FLAG_REVOKED, &ctx.cred->request_key_auth->flags)) { key_ref = ERR_PTR(-EKEYREVOKED); key = NULL; } else { rka = ctx.cred->request_key_auth->payload.data[0]; key = rka->dest_keyring; __key_get(key); } up_read(&ctx.cred->request_key_auth->sem); if (!key) goto error; key_ref = make_key_ref(key, 1); break; default: key_ref = ERR_PTR(-EINVAL); if (id < 1) goto error; key = key_lookup(id); if (IS_ERR(key)) { key_ref = ERR_CAST(key); goto error; } key_ref = make_key_ref(key, 0); /* check to see if we possess the key */ ctx.index_key.type = key->type; ctx.index_key.description = key->description; ctx.index_key.desc_len = strlen(key->description); ctx.match_data.raw_data = key; kdebug("check possessed"); skey_ref = search_process_keyrings(&ctx); kdebug("possessed=%p", skey_ref); if (!IS_ERR(skey_ref)) { key_put(key); key_ref = skey_ref; } break; } /* unlink does not use the nominated key in any way, so can skip all * the permission checks as it is only concerned with the keyring */ if (lflags & KEY_LOOKUP_FOR_UNLINK) { ret = 0; goto error; } if (!(lflags & KEY_LOOKUP_PARTIAL)) { ret = wait_for_key_construction(key, true); switch (ret) { case -ERESTARTSYS: goto invalid_key; default: if (perm) goto invalid_key; case 0: break; } } else if (perm) { ret = key_validate(key); if (ret < 0) goto invalid_key; } ret = -EIO; if (!(lflags & KEY_LOOKUP_PARTIAL) && !test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) goto invalid_key; /* check the permissions */ ret = key_task_permission(key_ref, ctx.cred, perm); if (ret < 0) goto invalid_key; key->last_used_at = current_kernel_time().tv_sec; error: put_cred(ctx.cred); return key_ref; invalid_key: key_ref_put(key_ref); key_ref = ERR_PTR(ret); goto error; /* if we attempted to install a keyring, then it may have caused new * creds to be installed */ reget_creds: put_cred(ctx.cred); goto try_again; } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: int SelectionDyn(char* title, char* message, char** szChoice, int nChoices) { #define ID_RADIO 12345 LPCWSTR lpwszTypeFace = L"MS Shell Dlg"; LPDLGTEMPLATEA lpdt; LPDLGITEMTEMPLATEA lpdit; LPCWSTR lpwszCaption; LPWORD lpw; LPWSTR lpwsz; int i, ret, nchar; lpdt = (LPDLGTEMPLATE)calloc(512 + nChoices * 256, 1); lpdt->style = WS_POPUP | WS_BORDER | WS_SYSMENU | WS_CAPTION | DS_MODALFRAME | DS_CENTER | DS_SHELLFONT; lpdt->cdit = 2 + nChoices; lpdt->x = 10; lpdt->y = 10; lpdt->cx = 300; lpdt->cy = 100; lpw = (LPWORD)(&lpdt[1]); *lpw++ = 0; // No menu *lpw++ = 0; // Default dialog class lpwsz = (LPWSTR)lpw; nchar = MultiByteToWideChar(CP_UTF8, 0, title, -1, lpwsz, 50); lpw += nchar; if (lpdt->style & (DS_SETFONT | DS_SHELLFONT)) { *lpw++ = 8; for (lpwsz = (LPWSTR)lpw, lpwszCaption = lpwszTypeFace; (*lpwsz++ = *lpwszCaption++) != 0; ); lpw = (LPWORD)lpwsz; } lpw = lpwAlign(lpw); lpdit = (LPDLGITEMTEMPLATE)lpw; lpdit->style = WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON; lpdit->x = 10; lpdit->y = 70; lpdit->cx = 50; lpdit->cy = 14; lpdit->id = IDOK; lpw = (LPWORD)(&lpdit[1]); *lpw++ = 0xFFFF; *lpw++ = 0x0080; // Button class lpwsz = (LPWSTR)lpw; nchar = MultiByteToWideChar(CP_UTF8, 0, "OK", -1, lpwsz, 50); lpw += nchar; *lpw++ = 0; // No creation data lpw = lpwAlign(lpw); lpdit = (LPDLGITEMTEMPLATE)lpw; lpdit->x = 90; lpdit->y = 70; lpdit->cx = 50; lpdit->cy = 14; lpdit->id = IDCANCEL; lpdit->style = WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON; lpw = (LPWORD)(&lpdit[1]); *lpw++ = 0xFFFF; *lpw++ = 0x0080; lpwsz = (LPWSTR)lpw; nchar = MultiByteToWideChar(CP_UTF8, 0, lmprintf(MSG_007), -1, lpwsz, 50); lpw += nchar; *lpw++ = 0; for (i = 0; i < nChoices; i++) { lpw = lpwAlign(lpw); lpdit = (LPDLGITEMTEMPLATE)lpw; lpdit->x = 10; lpdit->y = 10 + 15 * i; lpdit->cx = 40; lpdit->cy = 20; lpdit->id = ID_RADIO; lpdit->style = WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON | (i == 0 ? WS_GROUP : 0); lpw = (LPWORD)(&lpdit[1]); *lpw++ = 0xFFFF; *lpw++ = 0x0080; lpwsz = (LPWSTR)lpw; nchar = MultiByteToWideChar(CP_UTF8, 0, szChoice[i], -1, lpwsz, 150); lpw += nchar; *lpw++ = 0; } ret = (int)DialogBoxIndirect(hMainInstance, (LPDLGTEMPLATE)lpdt, hMainDialog, (DLGPROC)SelectionDynCallback); free(lpdt); return ret; } Commit Message: [pki] fix https://www.kb.cert.org/vuls/id/403768 * This commit effectively fixes https://www.kb.cert.org/vuls/id/403768 (CVE-2017-13083) as it is described per its revision 11, which is the latest revision at the time of this commit, by disabling Windows prompts, enacted during signature validation, that allow the user to bypass the intended signature verification checks. * It needs to be pointed out that the vulnerability ("allow(ing) the use of a self-signed certificate"), which relies on the end-user actively ignoring a Windows prompt that tells them that the update failed the signature validation whilst also advising against running it, is being fully addressed, even as the update protocol remains HTTP. * It also need to be pointed out that the extended delay (48 hours) between the time the vulnerability was reported and the moment it is fixed in our codebase has to do with the fact that the reporter chose to deviate from standard security practices by not disclosing the details of the vulnerability with us, be it publicly or privately, before creating the cert.org report. The only advance notification we received was a generic note about the use of HTTP vs HTTPS, which, as have established, is not immediately relevant to addressing the reported vulnerability. * Closes #1009 * Note: The other vulnerability scenario described towards the end of #1009, which doesn't have to do with the "lack of CA checking", will be addressed separately. CWE ID: CWE-494 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 llc_ui_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddrlen, int peer) { struct sockaddr_llc sllc; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); int rc = 0; memset(&sllc, 0, sizeof(sllc)); lock_sock(sk); if (sock_flag(sk, SOCK_ZAPPED)) goto out; *uaddrlen = sizeof(sllc); memset(uaddr, 0, *uaddrlen); if (peer) { rc = -ENOTCONN; if (sk->sk_state != TCP_ESTABLISHED) goto out; if(llc->dev) sllc.sllc_arphrd = llc->dev->type; sllc.sllc_sap = llc->daddr.lsap; memcpy(&sllc.sllc_mac, &llc->daddr.mac, IFHWADDRLEN); } else { rc = -EINVAL; if (!llc->sap) goto out; sllc.sllc_sap = llc->sap->laddr.lsap; if (llc->dev) { sllc.sllc_arphrd = llc->dev->type; memcpy(&sllc.sllc_mac, llc->dev->dev_addr, IFHWADDRLEN); } } rc = 0; sllc.sllc_family = AF_LLC; memcpy(uaddr, &sllc, sizeof(sllc)); out: release_sock(sk); return rc; } Commit Message: llc: fix info leak via getsockname() The LLC code wrongly returns 0, i.e. "success", when the socket is zapped. Together with the uninitialized uaddrlen pointer argument from sys_getsockname this leads to an arbitrary memory leak of up to 128 bytes kernel stack via the getsockname() syscall. Return an error instead when the socket is zapped to prevent the info leak. Also remove the unnecessary memset(0). We don't directly write to the memory pointed by uaddr but memcpy() a local structure at the end of the function that is properly initialized. Signed-off-by: Mathias Krause <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Signed-off-by: David S. Miller <[email protected]> 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: my_object_class_init (MyObjectClass *mobject_class) { GObjectClass *gobject_class = G_OBJECT_CLASS (mobject_class); gobject_class->finalize = my_object_finalize; gobject_class->set_property = my_object_set_property; gobject_class->get_property = my_object_get_property; g_object_class_install_property (gobject_class, PROP_THIS_IS_A_STRING, g_param_spec_string ("this_is_a_string", _("Sample string"), _("Example of a string property"), "default value", G_PARAM_READWRITE)); signals[FROBNICATE] = g_signal_new ("frobnicate", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); signals[SIG0] = g_signal_new ("sig0", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, my_object_marshal_VOID__STRING_INT_STRING, G_TYPE_NONE, 3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_STRING); signals[SIG1] = g_signal_new ("sig1", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, my_object_marshal_VOID__STRING_BOXED, G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_VALUE); signals[SIG2] = g_signal_new ("sig2", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, g_cclosure_marshal_VOID__BOXED, G_TYPE_NONE, 1, DBUS_TYPE_G_STRING_STRING_HASHTABLE); } Commit Message: CWE ID: CWE-264 Target: 1 Example 2: Code: SSL_CIPHER *ssl3_choose_cipher(SSL *s, STACK_OF(SSL_CIPHER) *clnt, STACK_OF(SSL_CIPHER) *srvr) { SSL_CIPHER *c,*ret=NULL; STACK_OF(SSL_CIPHER) *prio, *allow; int i,ii,ok; #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_EC) unsigned int j; int ec_ok, ec_nid; unsigned char ec_search1 = 0, ec_search2 = 0; #endif CERT *cert; unsigned long alg_k,alg_a,mask_k,mask_a,emask_k,emask_a; /* Let's see which ciphers we can support */ cert=s->cert; #if 0 /* Do not set the compare functions, because this may lead to a * reordering by "id". We want to keep the original ordering. * We may pay a price in performance during sk_SSL_CIPHER_find(), * but would have to pay with the price of sk_SSL_CIPHER_dup(). */ sk_SSL_CIPHER_set_cmp_func(srvr, ssl_cipher_ptr_id_cmp); sk_SSL_CIPHER_set_cmp_func(clnt, ssl_cipher_ptr_id_cmp); #endif #ifdef CIPHER_DEBUG printf("Server has %d from %p:\n", sk_SSL_CIPHER_num(srvr), (void *)srvr); for(i=0 ; i < sk_SSL_CIPHER_num(srvr) ; ++i) { c=sk_SSL_CIPHER_value(srvr,i); printf("%p:%s\n",(void *)c,c->name); } printf("Client sent %d from %p:\n", sk_SSL_CIPHER_num(clnt), (void *)clnt); for(i=0 ; i < sk_SSL_CIPHER_num(clnt) ; ++i) { c=sk_SSL_CIPHER_value(clnt,i); printf("%p:%s\n",(void *)c,c->name); } #endif if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) { prio = srvr; allow = clnt; } else { prio = clnt; allow = srvr; } for (i=0; i<sk_SSL_CIPHER_num(prio); i++) { c=sk_SSL_CIPHER_value(prio,i); /* Skip TLS v1.2 only ciphersuites if lower than v1.2 */ if ((c->algorithm_ssl & SSL_TLSV1_2) && (TLS1_get_version(s) < TLS1_2_VERSION)) continue; ssl_set_cert_masks(cert,c); mask_k = cert->mask_k; mask_a = cert->mask_a; emask_k = cert->export_mask_k; emask_a = cert->export_mask_a; #ifndef OPENSSL_NO_SRP mask_k=cert->mask_k | s->srp_ctx.srp_Mask; emask_k=cert->export_mask_k | s->srp_ctx.srp_Mask; #endif #ifdef KSSL_DEBUG /* printf("ssl3_choose_cipher %d alg= %lx\n", i,c->algorithms);*/ #endif /* KSSL_DEBUG */ alg_k=c->algorithm_mkey; alg_a=c->algorithm_auth; #ifndef OPENSSL_NO_KRB5 if (alg_k & SSL_kKRB5) { if ( !kssl_keytab_is_available(s->kssl_ctx) ) continue; } #endif /* OPENSSL_NO_KRB5 */ #ifndef OPENSSL_NO_PSK /* with PSK there must be server callback set */ if ((alg_k & SSL_kPSK) && s->psk_server_callback == NULL) continue; #endif /* OPENSSL_NO_PSK */ if (SSL_C_IS_EXPORT(c)) { ok = (alg_k & emask_k) && (alg_a & emask_a); #ifdef CIPHER_DEBUG printf("%d:[%08lX:%08lX:%08lX:%08lX]%p:%s (export)\n",ok,alg_k,alg_a,emask_k,emask_a, (void *)c,c->name); #endif } else { ok = (alg_k & mask_k) && (alg_a & mask_a); #ifdef CIPHER_DEBUG printf("%d:[%08lX:%08lX:%08lX:%08lX]%p:%s\n",ok,alg_k,alg_a,mask_k,mask_a,(void *)c, c->name); #endif } #ifndef OPENSSL_NO_TLSEXT #ifndef OPENSSL_NO_EC if ( /* if we are considering an ECC cipher suite that uses our certificate */ (alg_a & SSL_aECDSA || alg_a & SSL_aECDH) /* and we have an ECC certificate */ && (s->cert->pkeys[SSL_PKEY_ECC].x509 != NULL) /* and the client specified a Supported Point Formats extension */ && ((s->session->tlsext_ecpointformatlist_length > 0) && (s->session->tlsext_ecpointformatlist != NULL)) /* and our certificate's point is compressed */ && ( (s->cert->pkeys[SSL_PKEY_ECC].x509->cert_info != NULL) && (s->cert->pkeys[SSL_PKEY_ECC].x509->cert_info->key != NULL) && (s->cert->pkeys[SSL_PKEY_ECC].x509->cert_info->key->public_key != NULL) && (s->cert->pkeys[SSL_PKEY_ECC].x509->cert_info->key->public_key->data != NULL) && ( (*(s->cert->pkeys[SSL_PKEY_ECC].x509->cert_info->key->public_key->data) == POINT_CONVERSION_COMPRESSED) || (*(s->cert->pkeys[SSL_PKEY_ECC].x509->cert_info->key->public_key->data) == POINT_CONVERSION_COMPRESSED + 1) ) ) ) { ec_ok = 0; /* if our certificate's curve is over a field type that the client does not support * then do not allow this cipher suite to be negotiated */ if ( (s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec != NULL) && (s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group != NULL) && (s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group->meth != NULL) && (EC_METHOD_get_field_type(s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group->meth) == NID_X9_62_prime_field) ) { for (j = 0; j < s->session->tlsext_ecpointformatlist_length; j++) { if (s->session->tlsext_ecpointformatlist[j] == TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime) { ec_ok = 1; break; } } } else if (EC_METHOD_get_field_type(s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group->meth) == NID_X9_62_characteristic_two_field) { for (j = 0; j < s->session->tlsext_ecpointformatlist_length; j++) { if (s->session->tlsext_ecpointformatlist[j] == TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2) { ec_ok = 1; break; } } } ok = ok && ec_ok; } if ( /* if we are considering an ECC cipher suite that uses our certificate */ (alg_a & SSL_aECDSA || alg_a & SSL_aECDH) /* and we have an ECC certificate */ && (s->cert->pkeys[SSL_PKEY_ECC].x509 != NULL) /* and the client specified an EllipticCurves extension */ && ((s->session->tlsext_ellipticcurvelist_length > 0) && (s->session->tlsext_ellipticcurvelist != NULL)) ) { ec_ok = 0; if ( (s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec != NULL) && (s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group != NULL) ) { ec_nid = EC_GROUP_get_curve_name(s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group); if ((ec_nid == 0) && (s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group->meth != NULL) ) { if (EC_METHOD_get_field_type(s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group->meth) == NID_X9_62_prime_field) { ec_search1 = 0xFF; ec_search2 = 0x01; } else if (EC_METHOD_get_field_type(s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec->group->meth) == NID_X9_62_characteristic_two_field) { ec_search1 = 0xFF; ec_search2 = 0x02; } } else { ec_search1 = 0x00; ec_search2 = tls1_ec_nid2curve_id(ec_nid); } if ((ec_search1 != 0) || (ec_search2 != 0)) { for (j = 0; j < s->session->tlsext_ellipticcurvelist_length / 2; j++) { if ((s->session->tlsext_ellipticcurvelist[2*j] == ec_search1) && (s->session->tlsext_ellipticcurvelist[2*j+1] == ec_search2)) { ec_ok = 1; break; } } } } ok = ok && ec_ok; } if ( /* if we are considering an ECC cipher suite that uses an ephemeral EC key */ (alg_k & SSL_kEECDH) /* and we have an ephemeral EC key */ && (s->cert->ecdh_tmp != NULL) /* and the client specified an EllipticCurves extension */ && ((s->session->tlsext_ellipticcurvelist_length > 0) && (s->session->tlsext_ellipticcurvelist != NULL)) ) { ec_ok = 0; if (s->cert->ecdh_tmp->group != NULL) { ec_nid = EC_GROUP_get_curve_name(s->cert->ecdh_tmp->group); if ((ec_nid == 0) && (s->cert->ecdh_tmp->group->meth != NULL) ) { if (EC_METHOD_get_field_type(s->cert->ecdh_tmp->group->meth) == NID_X9_62_prime_field) { ec_search1 = 0xFF; ec_search2 = 0x01; } else if (EC_METHOD_get_field_type(s->cert->ecdh_tmp->group->meth) == NID_X9_62_characteristic_two_field) { ec_search1 = 0xFF; ec_search2 = 0x02; } } else { ec_search1 = 0x00; ec_search2 = tls1_ec_nid2curve_id(ec_nid); } if ((ec_search1 != 0) || (ec_search2 != 0)) { for (j = 0; j < s->session->tlsext_ellipticcurvelist_length / 2; j++) { if ((s->session->tlsext_ellipticcurvelist[2*j] == ec_search1) && (s->session->tlsext_ellipticcurvelist[2*j+1] == ec_search2)) { ec_ok = 1; break; } } } } ok = ok && ec_ok; } #endif /* OPENSSL_NO_EC */ #endif /* OPENSSL_NO_TLSEXT */ if (!ok) continue; ii=sk_SSL_CIPHER_find(allow,c); if (ii >= 0) { #if !defined(OPENSSL_NO_EC) && !defined(OPENSSL_NO_TLSEXT) if ((alg_k & SSL_kEECDH) && (alg_a & SSL_aECDSA) && s->s3->is_probably_safari) { if (!ret) ret=sk_SSL_CIPHER_value(allow,ii); continue; } #endif ret=sk_SSL_CIPHER_value(allow,ii); break; } } return(ret); } Commit Message: CWE ID: CWE-310 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: NameValueParserEndElt(void * d, const char * name, int l) { struct NameValueParserData * data = (struct NameValueParserData *)d; struct NameValue * nv; (void)name; (void)l; if(!data->topelt) return; if(strcmp(data->curelt, "NewPortListing") != 0) { int l; /* standard case. Limited to n chars strings */ l = data->cdatalen; nv = malloc(sizeof(struct NameValue)); if(nv == NULL) { /* malloc error */ #ifdef DEBUG fprintf(stderr, "%s: error allocating memory", "NameValueParserEndElt"); #endif /* DEBUG */ return; } if(l>=(int)sizeof(nv->value)) l = sizeof(nv->value) - 1; strncpy(nv->name, data->curelt, 64); nv->name[63] = '\0'; if(data->cdata != NULL) { memcpy(nv->value, data->cdata, l); nv->value[l] = '\0'; } else { nv->value[0] = '\0'; } nv->l_next = data->l_head; /* insert in list */ data->l_head = nv; } data->cdata = NULL; data->cdatalen = 0; data->topelt = 0; } Commit Message: properly initialize data structure for SOAP parsing in ParseNameValue() topelt field was not properly initialized. should fix #268 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: void CCLayerTreeHostTest::doBeginTest() { ASSERT(isMainThread()); ASSERT(!m_running); m_running = true; m_client = MockLayerTreeHostClient::create(this); RefPtr<LayerChromium> rootLayer = LayerChromium::create(0); m_layerTreeHost = MockLayerTreeHost::create(this, m_client.get(), rootLayer, m_settings); ASSERT(m_layerTreeHost); m_beginning = true; beginTest(); m_beginning = false; if (m_endWhenBeginReturns) onEndTest(static_cast<void*>(this)); } Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests https://bugs.webkit.org/show_bug.cgi?id=70161 Reviewed by David Levin. Source/WebCore: Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was destroyed. This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the CCThreadProxy have been drained. Covered by the now-enabled CCLayerTreeHostTest* unit tests. * WebCore.gypi: * platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added. (WebCore::CCScopedMainThreadProxy::create): (WebCore::CCScopedMainThreadProxy::postTask): (WebCore::CCScopedMainThreadProxy::shutdown): (WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy): (WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown): * platform/graphics/chromium/cc/CCThreadProxy.cpp: (WebCore::CCThreadProxy::CCThreadProxy): (WebCore::CCThreadProxy::~CCThreadProxy): (WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread): * platform/graphics/chromium/cc/CCThreadProxy.h: Source/WebKit/chromium: Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor thread scheduling draws by itself. * tests/CCLayerTreeHostTest.cpp: (::CCLayerTreeHostTest::timeout): (::CCLayerTreeHostTest::clearTimeout): (::CCLayerTreeHostTest::CCLayerTreeHostTest): (::CCLayerTreeHostTest::onEndTest): (::CCLayerTreeHostTest::TimeoutTask::TimeoutTask): (::CCLayerTreeHostTest::TimeoutTask::clearTest): (::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask): (::CCLayerTreeHostTest::TimeoutTask::Run): (::CCLayerTreeHostTest::runTest): (::CCLayerTreeHostTest::doBeginTest): (::CCLayerTreeHostTestThreadOnly::runTest): (::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread): git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 1 Example 2: Code: static int llc_ui_wait_for_conn(struct sock *sk, long timeout) { DEFINE_WAIT(wait); while (1) { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (sk_wait_event(sk, &timeout, sk->sk_state != TCP_SYN_SENT)) break; if (signal_pending(current) || !timeout) break; } finish_wait(sk_sleep(sk), &wait); return timeout; } Commit Message: llc: Fix missing msg_namelen update in llc_ui_recvmsg() For stream sockets the code misses to update the msg_namelen member to 0 and therefore makes net/socket.c leak the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. The msg_namelen update is also missing for datagram sockets in case the socket is shutting down during receive. Fix both issues by setting msg_namelen to 0 early. It will be updated later if we're going to fill the msg_name member. Cc: Arnaldo Carvalho de Melo <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[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: bool BrowserView::ExecuteWindowsCommand(int command_id) { #if defined(OS_WIN) && !defined(USE_AURA) if (command_id == IDC_DEBUG_FRAME_TOGGLE) GetWidget()->DebugToggleFrameType(); if (base::win::IsMetroProcess()) { static const int sc_mask = 0xFFF0; if (((command_id & sc_mask) == SC_MOVE) || ((command_id & sc_mask) == SC_SIZE) || ((command_id & sc_mask) == SC_MAXIMIZE)) return true; } #endif int command_id_from_app_command = GetCommandIDForAppCommandID(command_id); if (command_id_from_app_command != -1) command_id = command_id_from_app_command; return chrome::ExecuteCommand(browser_.get(), command_id); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 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: dotraplinkage void do_stack_segment(struct pt_regs *regs, long error_code) { enum ctx_state prev_state; prev_state = exception_enter(); if (notify_die(DIE_TRAP, "stack segment", regs, error_code, X86_TRAP_SS, SIGBUS) != NOTIFY_STOP) { preempt_conditional_sti(regs); do_trap(X86_TRAP_SS, SIGBUS, "stack segment", regs, error_code, NULL); preempt_conditional_cli(regs); } exception_exit(prev_state); } Commit Message: x86_64, traps: Stop using IST for #SS On a 32-bit kernel, this has no effect, since there are no IST stacks. On a 64-bit kernel, #SS can only happen in user code, on a failed iret to user space, a canonical violation on access via RSP or RBP, or a genuine stack segment violation in 32-bit kernel code. The first two cases don't need IST, and the latter two cases are unlikely fatal bugs, and promoting them to double faults would be fine. This fixes a bug in which the espfix64 code mishandles a stack segment violation. This saves 4k of memory per CPU and a tiny bit of code. Signed-off-by: Andy Lutomirski <[email protected]> Reviewed-by: Thomas Gleixner <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: dissect_rpcap_startcap_reply (tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *parent_tree, gint offset) { proto_tree *tree; proto_item *ti; ti = proto_tree_add_item (parent_tree, hf_startcap_reply, tvb, offset, -1, ENC_NA); tree = proto_item_add_subtree (ti, ett_startcap_reply); proto_tree_add_item (tree, hf_bufsize, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; proto_tree_add_item (tree, hf_server_port, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; proto_tree_add_item (tree, hf_dummy, tvb, offset, 2, ENC_BIG_ENDIAN); } Commit Message: The WTAP_ENCAP_ETHERNET dissector needs to be passed a struct eth_phdr. We now require that. Make it so. Bug: 12440 Change-Id: Iffee520976b013800699bde3c6092a3e86be0d76 Reviewed-on: https://code.wireshark.org/review/15424 Reviewed-by: Guy Harris <[email protected]> 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 HTMLStyleElement::Trace(blink::Visitor* visitor) { StyleElement::Trace(visitor); HTMLElement::Trace(visitor); } Commit Message: Do not crash while reentrantly appending to style element. When a node is inserted into a container, it is notified via ::InsertedInto. However, a node may request a second notification via DidNotifySubtreeInsertionsToDocument, which occurs after all the children have been notified as well. *StyleElement is currently using this second notification. This causes a problem, because *ScriptElement is using the same mechanism, which in turn means that scripts can execute before the state of *StyleElements are properly updated. This patch avoids ::DidNotifySubtreeInsertionsToDocument, and instead processes the stylesheet in ::InsertedInto. The original reason for using ::DidNotifySubtreeInsertionsToDocument in the first place appears to be invalid now, as the test case is still passing. [email protected], [email protected] Bug: 853709, 847570 Cq-Include-Trybots: luci.chromium.try:linux_layout_tests_slimming_paint_v2;master.tryserver.blink:linux_trusty_blink_rel Change-Id: Ic0b5fa611044c78c5745cf26870a747f88920a14 Reviewed-on: https://chromium-review.googlesource.com/1104347 Commit-Queue: Anders Ruud <[email protected]> Reviewed-by: Rune Lillesveen <[email protected]> Cr-Commit-Position: refs/heads/master@{#568368} CWE ID: CWE-416 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 perform_gamma_scale16_tests(png_modifier *pm) { # ifndef PNG_MAX_GAMMA_8 # define PNG_MAX_GAMMA_8 11 # endif # define SBIT_16_TO_8 PNG_MAX_GAMMA_8 /* Include the alpha cases here. Note that sbit matches the internal value * used by the library - otherwise we will get spurious errors from the * internal sbit style approximation. * * The threshold test is here because otherwise the 16 to 8 conversion will * proceed *without* gamma correction, and the tests above will fail (but not * by much) - this could be fixed, it only appears with the -g option. */ unsigned int i, j; for (i=0; i<pm->ngamma_tests; ++i) { for (j=0; j<pm->ngamma_tests; ++j) { if (i != j && fabs(pm->gammas[j]/pm->gammas[i]-1) >= PNG_GAMMA_THRESHOLD) { gamma_transform_test(pm, 0, 16, 0, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8, pm->use_input_precision_16to8, 1 /*scale16*/); if (fail(pm)) return; gamma_transform_test(pm, 2, 16, 0, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8, pm->use_input_precision_16to8, 1 /*scale16*/); if (fail(pm)) return; gamma_transform_test(pm, 4, 16, 0, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8, pm->use_input_precision_16to8, 1 /*scale16*/); if (fail(pm)) return; gamma_transform_test(pm, 6, 16, 0, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8, pm->use_input_precision_16to8, 1 /*scale16*/); if (fail(pm)) return; } } } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: void comps_objrtree_copy(COMPS_ObjRTree *rt1, COMPS_ObjRTree *rt2){ COMPS_HSList *to_clone, *tmplist, *new_subnodes; COMPS_HSListItem *it, *it2; COMPS_ObjRTreeData *rtdata; COMPS_Object *new_data; rt1->subnodes = comps_hslist_create(); comps_hslist_init(rt1->subnodes, NULL, NULL, &comps_objrtree_data_destroy_v); if (rt1->subnodes == NULL) { COMPS_OBJECT_DESTROY(rt1); return; } rt1->len = 0; to_clone = comps_hslist_create(); comps_hslist_init(to_clone, NULL, NULL, NULL); for (it = rt2->subnodes->first; it != NULL; it = it->next) { rtdata = comps_objrtree_data_create( ((COMPS_ObjRTreeData*)it->data)->key, NULL); if (((COMPS_ObjRTreeData*)it->data)->data != NULL) new_data = comps_object_copy(((COMPS_ObjRTreeData*)it->data)->data); else new_data = NULL; comps_hslist_destroy(&rtdata->subnodes); rtdata->subnodes = ((COMPS_ObjRTreeData*)it->data)->subnodes; rtdata->data = new_data; comps_hslist_append(rt1->subnodes, rtdata, 0); comps_hslist_append(to_clone, rtdata, 0); } while (to_clone->first) { it2 = to_clone->first; tmplist = ((COMPS_ObjRTreeData*)it2->data)->subnodes; comps_hslist_remove(to_clone, to_clone->first); new_subnodes = comps_hslist_create(); comps_hslist_init(new_subnodes, NULL, NULL, &comps_objrtree_data_destroy_v); for (it = tmplist->first; it != NULL; it = it->next) { rtdata = comps_objrtree_data_create( ((COMPS_ObjRTreeData*)it->data)->key, NULL); if (((COMPS_ObjRTreeData*)it->data)->data != NULL) new_data = comps_object_copy(((COMPS_ObjRTreeData*)it->data)->data); else new_data = NULL; comps_hslist_destroy(&rtdata->subnodes); rtdata->subnodes = ((COMPS_ObjRTreeData*)it->data)->subnodes; rtdata->data = new_data; comps_hslist_append(new_subnodes, rtdata, 0); comps_hslist_append(to_clone, rtdata, 0); } ((COMPS_ObjRTreeData*)it2->data)->subnodes = new_subnodes; free(it2); } comps_hslist_destroy(&to_clone); } Commit Message: Fix UAF in comps_objmrtree_unite function The added field is not used at all in many places and it is probably the left-over of some copy-paste. 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: static inline LineContribType * _gdContributionsAlloc(unsigned int line_length, unsigned int windows_size) { unsigned int u = 0; LineContribType *res; int overflow_error = 0; res = (LineContribType *) gdMalloc(sizeof(LineContribType)); if (!res) { return NULL; } res->WindowSize = windows_size; res->LineLength = line_length; if (overflow2(line_length, sizeof(ContributionType))) { gdFree(res); return NULL; } res->ContribRow = (ContributionType *) gdMalloc(line_length * sizeof(ContributionType)); if (res->ContribRow == NULL) { gdFree(res); return NULL; } for (u = 0 ; u < line_length ; u++) { if (overflow2(windows_size, sizeof(double))) { overflow_error = 1; } else { res->ContribRow[u].Weights = (double *) gdMalloc(windows_size * sizeof(double)); } if (overflow_error == 1 || res->ContribRow[u].Weights == NULL) { unsigned int i; u--; for (i=0;i<=u;i++) { gdFree(res->ContribRow[i].Weights); } gdFree(res->ContribRow); gdFree(res); return NULL; } } return res; } Commit Message: Fix potential unsigned underflow No need to decrease `u`, so we don't do it. While we're at it, we also factor out the overflow check of the loop, what improves performance and readability. This issue has been reported by Stefan Esser to [email protected]. CWE ID: CWE-191 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: pipe_iov_copy_from_user(void *to, struct iovec *iov, unsigned long len, int atomic) { unsigned long copy; while (len > 0) { while (!iov->iov_len) iov++; copy = min_t(unsigned long, len, iov->iov_len); if (atomic) { if (__copy_from_user_inatomic(to, iov->iov_base, copy)) return -EFAULT; } else { if (copy_from_user(to, iov->iov_base, copy)) return -EFAULT; } to += copy; len -= copy; iov->iov_base += copy; iov->iov_len -= copy; } return 0; } Commit Message: new helper: copy_page_from_iter() parallel to copy_page_to_iter(). pipe_write() switched to it (and became ->write_iter()). Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-17 Target: 1 Example 2: Code: void jsvArrayInsertBefore(JsVar *arr, JsVar *beforeIndex, JsVar *element) { if (beforeIndex) { JsVar *idxVar = jsvMakeIntoVariableName(jsvNewFromInteger(0), element); if (!idxVar) return; // out of memory JsVarRef idxRef = jsvGetRef(jsvRef(idxVar)); JsVarRef prev = jsvGetPrevSibling(beforeIndex); if (prev) { JsVar *prevVar = jsvRef(jsvLock(prev)); jsvSetInteger(idxVar, jsvGetInteger(prevVar)+1); // update index number jsvSetNextSibling(prevVar, idxRef); jsvUnLock(prevVar); jsvSetPrevSibling(idxVar, prev); } else { jsvSetPrevSibling(idxVar, 0); jsvSetFirstChild(arr, idxRef); } jsvSetPrevSibling(beforeIndex, idxRef); jsvSetNextSibling(idxVar, jsvGetRef(jsvRef(beforeIndex))); jsvUnLock(idxVar); } else jsvArrayPush(arr, element); } Commit Message: fix jsvGetString regression 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: TestFeaturesNativeHandler::TestFeaturesNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("GetAPIFeatures", base::Bind(&TestFeaturesNativeHandler::GetAPIFeatures, base::Unretained(this))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284 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: void DownloadController::StartAndroidDownloadInternal( const content::ResourceRequestInfo::WebContentsGetter& wc_getter, bool must_download, const DownloadInfo& info, bool allowed) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!allowed) return; WebContents* web_contents = wc_getter.Run(); if (!web_contents) return; base::string16 filename = net::GetSuggestedFilename( info.url, info.content_disposition, std::string(), // referrer_charset std::string(), // suggested_name info.original_mime_type, default_file_name_); ChromeDownloadDelegate::FromWebContents(web_contents)->RequestHTTPGetDownload( info.url.spec(), info.user_agent, info.content_disposition, info.original_mime_type, info.cookie, info.referer, filename, info.total_bytes, info.has_user_gesture, must_download); } Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack The only exception is OMA DRM download. And it only applies to context menu download interception. Clean up the remaining unused code now. BUG=647755 Review-Url: https://codereview.chromium.org/2371773003 Cr-Commit-Position: refs/heads/master@{#421332} CWE ID: CWE-254 Target: 1 Example 2: Code: xsmp_save (GsmClient *client, GError **error) { GsmClientRestartStyle restart_style; GKeyFile *keyfile = NULL; char *desktop_file_path = NULL; char *exec_program = NULL; char *exec_discard = NULL; char *startup_id = NULL; GError *local_error; g_debug ("GsmXSMPClient: saving client with id %s", gsm_client_peek_id (client)); local_error = NULL; restart_style = xsmp_get_restart_style_hint (client); if (restart_style == GSM_CLIENT_RESTART_NEVER) { goto out; } exec_program = xsmp_get_restart_command (client); if (!exec_program) { goto out; } desktop_file_path = get_desktop_file_path (GSM_XSMP_CLIENT (client)); keyfile = create_client_key_file (client, desktop_file_path, &local_error); if (local_error) { goto out; } g_object_get (client, "startup-id", &startup_id, NULL); g_key_file_set_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, GSM_AUTOSTART_APP_STARTUP_ID_KEY, startup_id); g_key_file_set_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_EXEC, exec_program); exec_discard = xsmp_get_discard_command (client); if (exec_discard) g_key_file_set_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, GSM_AUTOSTART_APP_DISCARD_KEY, exec_discard); out: g_free (desktop_file_path); g_free (exec_program); g_free (exec_discard); g_free (startup_id); if (local_error != NULL) { g_propagate_error (error, local_error); g_key_file_free (keyfile); return NULL; } return keyfile; } Commit Message: [gsm] Delay the creation of the GsmXSMPClient until it really exists We used to create the GsmXSMPClient before the XSMP connection is really accepted. This can lead to some issues, though. An example is: https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting: "What is happening is that a new client (probably metacity in your case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION phase, which causes a new GsmXSMPClient to be added to the client store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client has had a chance to establish a xsmp connection, which means that client->priv->conn will not be initialized at the point that xsmp_stop is called on the new unregistered client." The fix is to create the GsmXSMPClient object when there's a real XSMP connection. This implies moving the timeout that makes sure we don't have an empty client to the XSMP server. https://bugzilla.gnome.org/show_bug.cgi?id=598211 CWE ID: CWE-835 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: xps_begin_opacity(xps_document *doc, const fz_matrix *ctm, const fz_rect *area, char *base_uri, xps_resource *dict, char *opacity_att, fz_xml *opacity_mask_tag) { float opacity; if (!opacity_att && !opacity_mask_tag) return; opacity = 1; if (opacity_att) opacity = fz_atof(opacity_att); if (opacity_mask_tag && !strcmp(fz_xml_tag(opacity_mask_tag), "SolidColorBrush")) { char *scb_opacity_att = fz_xml_att(opacity_mask_tag, "Opacity"); char *scb_color_att = fz_xml_att(opacity_mask_tag, "Color"); if (scb_opacity_att) opacity = opacity * fz_atof(scb_opacity_att); if (scb_color_att) { fz_colorspace *colorspace; float samples[32]; xps_parse_color(doc, base_uri, scb_color_att, &colorspace, samples); opacity = opacity * samples[0]; } opacity_mask_tag = NULL; } if (doc->opacity_top + 1 < nelem(doc->opacity)) { doc->opacity[doc->opacity_top + 1] = doc->opacity[doc->opacity_top] * opacity; doc->opacity_top++; } if (opacity_mask_tag) { fz_begin_mask(doc->dev, area, 0, NULL, NULL); xps_parse_brush(doc, ctm, area, base_uri, dict, opacity_mask_tag); fz_end_mask(doc->dev); } } Commit Message: 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: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; int16_t s16; int32_t s32; uint32_t u32; int64_t s64; uint64_t u64; cdf_timestamp_t tp; size_t i, o, o4, nelements, j; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, (const void *) ((const char *)sst->sst_tab + offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); #define CDF_SHLEN_LIMIT (UINT32_MAX / 8) if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } sh.sh_properties = CDF_TOLE4(shp->sh_properties); #define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp))) if (sh.sh_properties > CDF_PROP_LIMIT) goto out; DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (*maxcount) { if (*maxcount > CDF_PROP_LIMIT) goto out; *maxcount += sh.sh_properties; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); } else { *maxcount = sh.sh_properties; inp = CAST(cdf_property_info_t *, malloc(*maxcount * sizeof(*inp))); } if (inp == NULL) goto out; *info = inp; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, (const void *) ((const char *)(const void *)sst->sst_tab + offs + sizeof(sh))); e = CAST(const uint8_t *, (const void *) (((const char *)(const void *)shp) + sh.sh_len)); if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { size_t tail = (i << 1) + 1; if (cdf_check_stream_offset(sst, h, p, tail * sizeof(uint32_t), __LINE__) == -1) goto out; size_t ofs = CDF_GETUINT32(p, tail); q = (const uint8_t *)(const void *) ((const char *)(const void *)p + ofs - 2 * sizeof(uint32_t)); if (q > e) { DPRINTF(("Ran of the end %p > %p\n", q, e)); goto out; } inp[i].pi_id = CDF_GETUINT32(p, i << 1); inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { nelements = CDF_GETUINT32(q, 1); if (nelements == 0) { DPRINTF(("CDF_VECTOR with nelements == 0\n")); goto out; } o = 2; } else { nelements = 1; o = 1; } o4 = o * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s16, &q[o4], sizeof(s16)); inp[i].pi_s16 = CDF_TOLE2(s16); break; case CDF_SIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s32, &q[o4], sizeof(s32)); inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32); break; case CDF_BOOL: case CDF_UNSIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); inp[i].pi_u32 = CDF_TOLE4(u32); break; case CDF_SIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s64, &q[o4], sizeof(s64)); inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64); break; case CDF_UNSIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64); break; case CDF_FLOAT: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); u32 = CDF_TOLE4(u32); memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f)); break; case CDF_DOUBLE: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); u64 = CDF_TOLE8((uint64_t)u64); memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d)); break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; if (*maxcount > CDF_PROP_LIMIT || nelements > CDF_PROP_LIMIT) goto out; *maxcount += nelements; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; inp = *info + nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements && i < sh.sh_properties; j++, i++) { uint32_t l = CDF_GETUINT32(q, o); inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = (const char *) (const void *)(&q[o4 + sizeof(l)]); DPRINTF(("l = %d, r = %" SIZE_T_FORMAT "u, s = %s\n", l, CDF_ROUND(l, sizeof(l)), inp[i].pi_str.s_buf)); if (l & 1) l++; o += l >> 1; if (q + o >= e) goto out; o4 = o * sizeof(uint32_t); } i--; break; case CDF_FILETIME: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&tp, &q[o4], sizeof(tp)); inp[i].pi_tp = CDF_TOLE8((uint64_t)tp); break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: DPRINTF(("Don't know how to deal with %x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); return -1; } Commit Message: Prevent wrap around (Remi Collet at redhat) CWE ID: CWE-189 Target: 1 Example 2: Code: void CreateTestServerAndLocalCreditCards() { personal_data_.ClearCreditCards(); CreditCard masked_server_card; test::SetCreditCardInfo(&masked_server_card, "Elvis Presley", "4234567890123456", // Visa "04", "2999", "1"); masked_server_card.set_guid("00000000-0000-0000-0000-000000000007"); masked_server_card.set_record_type(CreditCard::MASKED_SERVER_CARD); personal_data_.AddServerCreditCard(masked_server_card); CreditCard full_server_card; test::SetCreditCardInfo(&full_server_card, "Buddy Holly", "5187654321098765", // Mastercard "10", "2998", "1"); full_server_card.set_guid("00000000-0000-0000-0000-000000000008"); full_server_card.set_record_type(CreditCard::FULL_SERVER_CARD); personal_data_.AddServerCreditCard(full_server_card); CreditCard local_card; test::SetCreditCardInfo(&local_card, "Elvis Presley", "4234567890123456", // Visa "04", "2999", "1"); local_card.set_guid("00000000-0000-0000-0000-000000000009"); local_card.set_record_type(CreditCard::LOCAL_CARD); personal_data_.AddCreditCard(local_card); } Commit Message: [AF] Don't simplify/dedupe suggestions for (partially) filled sections. Since Autofill does not fill field by field anymore, this simplifying and deduping of suggestions is not useful anymore. Bug: 858820 Cq-Include-Trybots: luci.chromium.try:ios-simulator-full-configs;master.tryserver.chromium.mac:ios-simulator-cronet Change-Id: I36f7cfe425a0bdbf5ba7503a3d96773b405cc19b Reviewed-on: https://chromium-review.googlesource.com/1128255 Reviewed-by: Roger McFarlane <[email protected]> Commit-Queue: Sebastien Seguin-Gagnon <[email protected]> Cr-Commit-Position: refs/heads/master@{#573315} 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 struct perf_event *perf_fget_light(int fd, int *fput_needed) { struct file *file; file = fget_light(fd, fput_needed); if (!file) return ERR_PTR(-EBADF); if (file->f_op != &perf_fops) { fput_light(file, *fput_needed); *fput_needed = 0; return ERR_PTR(-EBADF); } return file->private_data; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 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 SyncTest::TriggerSetSyncTabs() { ASSERT_TRUE(ServerSupportsErrorTriggering()); std::string path = "chromiumsync/synctabs"; ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path)); ASSERT_EQ("Sync Tabs", UTF16ToASCII(browser()->GetSelectedWebContents()->GetTitle())); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 Target: 1 Example 2: Code: bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req) { int i, cpu, me; cpumask_var_t cpus; bool called = true; struct kvm_vcpu *vcpu; zalloc_cpumask_var(&cpus, GFP_ATOMIC); me = get_cpu(); kvm_for_each_vcpu(i, vcpu, kvm) { kvm_make_request(req, vcpu); cpu = vcpu->cpu; /* Set ->requests bit before we read ->mode. */ smp_mb__after_atomic(); if (cpus != NULL && cpu != -1 && cpu != me && kvm_vcpu_exiting_guest_mode(vcpu) != OUTSIDE_GUEST_MODE) cpumask_set_cpu(cpu, cpus); } if (unlikely(cpus == NULL)) smp_call_function_many(cpu_online_mask, ack_flush, NULL, 1); else if (!cpumask_empty(cpus)) smp_call_function_many(cpus, ack_flush, NULL, 1); else called = false; put_cpu(); free_cpumask_var(cpus); return called; } 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: _xfs_buf_find( struct xfs_buftarg *btp, struct xfs_buf_map *map, int nmaps, xfs_buf_flags_t flags, xfs_buf_t *new_bp) { size_t numbytes; struct xfs_perag *pag; struct rb_node **rbp; struct rb_node *parent; xfs_buf_t *bp; xfs_daddr_t blkno = map[0].bm_bn; int numblks = 0; int i; for (i = 0; i < nmaps; i++) numblks += map[i].bm_len; numbytes = BBTOB(numblks); /* Check for IOs smaller than the sector size / not sector aligned */ ASSERT(!(numbytes < (1 << btp->bt_sshift))); ASSERT(!(BBTOB(blkno) & (xfs_off_t)btp->bt_smask)); /* get tree root */ pag = xfs_perag_get(btp->bt_mount, xfs_daddr_to_agno(btp->bt_mount, blkno)); /* walk tree */ spin_lock(&pag->pag_buf_lock); rbp = &pag->pag_buf_tree.rb_node; parent = NULL; bp = NULL; while (*rbp) { parent = *rbp; bp = rb_entry(parent, struct xfs_buf, b_rbnode); if (blkno < bp->b_bn) rbp = &(*rbp)->rb_left; else if (blkno > bp->b_bn) rbp = &(*rbp)->rb_right; else { /* * found a block number match. If the range doesn't * match, the only way this is allowed is if the buffer * in the cache is stale and the transaction that made * it stale has not yet committed. i.e. we are * reallocating a busy extent. Skip this buffer and * continue searching to the right for an exact match. */ if (bp->b_length != numblks) { ASSERT(bp->b_flags & XBF_STALE); rbp = &(*rbp)->rb_right; continue; } atomic_inc(&bp->b_hold); goto found; } } /* No match found */ if (new_bp) { rb_link_node(&new_bp->b_rbnode, parent, rbp); rb_insert_color(&new_bp->b_rbnode, &pag->pag_buf_tree); /* the buffer keeps the perag reference until it is freed */ new_bp->b_pag = pag; spin_unlock(&pag->pag_buf_lock); } else { XFS_STATS_INC(xb_miss_locked); spin_unlock(&pag->pag_buf_lock); xfs_perag_put(pag); } return new_bp; found: spin_unlock(&pag->pag_buf_lock); xfs_perag_put(pag); if (!xfs_buf_trylock(bp)) { if (flags & XBF_TRYLOCK) { xfs_buf_rele(bp); XFS_STATS_INC(xb_busy_locked); return NULL; } xfs_buf_lock(bp); XFS_STATS_INC(xb_get_locked_waited); } /* * if the buffer is stale, clear all the external state associated with * it. We need to keep flags such as how we allocated the buffer memory * intact here. */ if (bp->b_flags & XBF_STALE) { ASSERT((bp->b_flags & _XBF_DELWRI_Q) == 0); ASSERT(bp->b_iodone == NULL); bp->b_flags &= _XBF_KMEM | _XBF_PAGES; bp->b_ops = NULL; } trace_xfs_buf_find(bp, flags, _RET_IP_); XFS_STATS_INC(xb_get_locked); return bp; } Commit Message: xfs: fix _xfs_buf_find oops on blocks beyond the filesystem end When _xfs_buf_find is passed an out of range address, it will fail to find a relevant struct xfs_perag and oops with a null dereference. This can happen when trying to walk a filesystem with a metadata inode that has a partially corrupted extent map (i.e. the block number returned is corrupt, but is otherwise intact) and we try to read from the corrupted block address. In this case, just fail the lookup. If it is readahead being issued, it will simply not be done, but if it is real read that fails we will get an error being reported. Ideally this case should result in an EFSCORRUPTED error being reported, but we cannot return an error through xfs_buf_read() or xfs_buf_get() so this lookup failure may result in ENOMEM or EIO errors being reported instead. Signed-off-by: Dave Chinner <[email protected]> Reviewed-by: Brian Foster <[email protected]> Reviewed-by: Ben Myers <[email protected]> Signed-off-by: Ben Myers <[email protected]> CWE ID: CWE-20 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: PS_SERIALIZER_DECODE_FUNC(php_binary) /* {{{ */ { const char *p; char *name; const char *endptr = val + vallen; zval *current; int namelen; int has_value; php_unserialize_data_t var_hash; PHP_VAR_UNSERIALIZE_INIT(var_hash); for (p = val; p < endptr; ) { zval **tmp; namelen = ((unsigned char)(*p)) & (~PS_BIN_UNDEF); if (namelen < 0 || namelen > PS_BIN_MAX || (p + namelen) >= endptr) { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return FAILURE; } has_value = *p & PS_BIN_UNDEF ? 0 : 1; name = estrndup(p + 1, namelen); p += namelen + 1; if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) { if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) { efree(name); continue; } } if (has_value) { ALLOC_INIT_ZVAL(current); if (php_var_unserialize(&current, (const unsigned char **) &p, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) { php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC); } else { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return FAILURE; } var_push_dtor_no_addref(&var_hash, &current); } PS_ADD_VARL(name, namelen); efree(name); } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return SUCCESS; } /* }}} */ Commit Message: Fix bug #72681 - consume data even if we're not storing them CWE ID: CWE-74 Target: 1 Example 2: Code: static int ati_remote2_suspend(struct usb_interface *interface, pm_message_t message) { struct ati_remote2 *ar2; struct usb_host_interface *alt = interface->cur_altsetting; if (alt->desc.bInterfaceNumber) return 0; ar2 = usb_get_intfdata(interface); dev_dbg(&ar2->intf[0]->dev, "%s()\n", __func__); mutex_lock(&ati_remote2_mutex); if (ar2->flags & ATI_REMOTE2_OPENED) ati_remote2_kill_urbs(ar2); ar2->flags |= ATI_REMOTE2_SUSPENDED; mutex_unlock(&ati_remote2_mutex); return 0; } Commit Message: Input: ati_remote2 - fix crashes on detecting device with invalid descriptor The ati_remote2 driver expects at least two interfaces with one endpoint each. If given malicious descriptor that specify one interface or no endpoints, it will crash in the probe function. Ensure there is at least two interfaces and one endpoint for each interface before using it. The full disclosure: http://seclists.org/bugtraq/2016/Mar/90 Reported-by: Ralf Spenneberg <[email protected]> Signed-off-by: Vladis Dronov <[email protected]> Cc: [email protected] Signed-off-by: Dmitry Torokhov <[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 int cmd_handle_untagged(struct ImapData *idata) { unsigned int count = 0; char *s = imap_next_word(idata->buf); char *pn = imap_next_word(s); if ((idata->state >= IMAP_SELECTED) && isdigit((unsigned char) *s)) { pn = s; s = imap_next_word(s); /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the * connection, so update that one. */ if (mutt_str_strncasecmp("EXISTS", s, 6) == 0) { mutt_debug(2, "Handling EXISTS\n"); /* new mail arrived */ if (mutt_str_atoui(pn, &count) < 0) { mutt_debug(1, "Malformed EXISTS: '%s'\n", pn); } if (!(idata->reopen & IMAP_EXPUNGE_PENDING) && count < idata->max_msn) { /* Notes 6.0.3 has a tendency to report fewer messages exist than * it should. */ mutt_debug(1, "Message count is out of sync\n"); return 0; } /* at least the InterChange server sends EXISTS messages freely, * even when there is no new mail */ else if (count == idata->max_msn) mutt_debug(3, "superfluous EXISTS message.\n"); else { if (!(idata->reopen & IMAP_EXPUNGE_PENDING)) { mutt_debug(2, "New mail in %s - %d messages total.\n", idata->mailbox, count); idata->reopen |= IMAP_NEWMAIL_PENDING; } idata->new_mail_count = count; } } /* pn vs. s: need initial seqno */ else if (mutt_str_strncasecmp("EXPUNGE", s, 7) == 0) cmd_parse_expunge(idata, pn); else if (mutt_str_strncasecmp("FETCH", s, 5) == 0) cmd_parse_fetch(idata, pn); } else if (mutt_str_strncasecmp("CAPABILITY", s, 10) == 0) cmd_parse_capability(idata, s); else if (mutt_str_strncasecmp("OK [CAPABILITY", s, 14) == 0) cmd_parse_capability(idata, pn); else if (mutt_str_strncasecmp("OK [CAPABILITY", pn, 14) == 0) cmd_parse_capability(idata, imap_next_word(pn)); else if (mutt_str_strncasecmp("LIST", s, 4) == 0) cmd_parse_list(idata, s); else if (mutt_str_strncasecmp("LSUB", s, 4) == 0) cmd_parse_lsub(idata, s); else if (mutt_str_strncasecmp("MYRIGHTS", s, 8) == 0) cmd_parse_myrights(idata, s); else if (mutt_str_strncasecmp("SEARCH", s, 6) == 0) cmd_parse_search(idata, s); else if (mutt_str_strncasecmp("STATUS", s, 6) == 0) cmd_parse_status(idata, s); else if (mutt_str_strncasecmp("ENABLED", s, 7) == 0) cmd_parse_enabled(idata, s); else if (mutt_str_strncasecmp("BYE", s, 3) == 0) { mutt_debug(2, "Handling BYE\n"); /* check if we're logging out */ if (idata->status == IMAP_BYE) return 0; /* server shut down our connection */ s += 3; SKIPWS(s); mutt_error("%s", s); cmd_handle_fatal(idata); return -1; } else if (ImapServernoise && (mutt_str_strncasecmp("NO", s, 2) == 0)) { mutt_debug(2, "Handling untagged NO\n"); /* Display the warning message from the server */ mutt_error("%s", s + 3); } return 0; } Commit Message: Handle NO response without message properly CWE ID: CWE-20 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: HarfBuzzShaper::HarfBuzzShaper(const Font* font, const TextRun& run, const GlyphData* emphasisData, HashSet<const SimpleFontData*>* fallbackFonts, FloatRect* bounds) : Shaper(font, run, emphasisData, fallbackFonts, bounds) , m_normalizedBufferLength(0) , m_wordSpacingAdjustment(font->fontDescription().wordSpacing()) , m_letterSpacing(font->fontDescription().letterSpacing()) , m_expansionOpportunityCount(0) , m_fromIndex(0) , m_toIndex(m_run.length()) { m_normalizedBuffer = adoptArrayPtr(new UChar[m_run.length() + 1]); normalizeCharacters(m_run, m_run.length(), m_normalizedBuffer.get(), &m_normalizedBufferLength); setExpansion(m_run.expansion()); setFontFeatures(); } Commit Message: Always initialize |m_totalWidth| in HarfBuzzShaper::shape. [email protected] BUG=476647 Review URL: https://codereview.chromium.org/1108663003 git-svn-id: svn://svn.chromium.org/blink/trunk@194541 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: static struct svc_rdma_op_ctxt *alloc_ctxt(struct svcxprt_rdma *xprt, gfp_t flags) { struct svc_rdma_op_ctxt *ctxt; ctxt = kmalloc(sizeof(*ctxt), flags); if (ctxt) { ctxt->xprt = xprt; INIT_LIST_HEAD(&ctxt->list); } return ctxt; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404 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: std::unique_ptr<HistogramBase> PersistentHistogramAllocator::AllocateHistogram( HistogramType histogram_type, const std::string& name, int minimum, int maximum, const BucketRanges* bucket_ranges, int32_t flags, Reference* ref_ptr) { if (memory_allocator_->IsCorrupt()) { RecordCreateHistogramResult(CREATE_HISTOGRAM_ALLOCATOR_CORRUPT); return nullptr; } PersistentHistogramData* histogram_data = memory_allocator_->New<PersistentHistogramData>( offsetof(PersistentHistogramData, name) + name.length() + 1); if (histogram_data) { memcpy(histogram_data->name, name.c_str(), name.size() + 1); histogram_data->histogram_type = histogram_type; histogram_data->flags = flags | HistogramBase::kIsPersistent; } if (histogram_type != SPARSE_HISTOGRAM) { size_t bucket_count = bucket_ranges->bucket_count(); size_t counts_bytes = CalculateRequiredCountsBytes(bucket_count); if (counts_bytes == 0) { NOTREACHED(); return nullptr; } DCHECK_EQ(this, GlobalHistogramAllocator::Get()); PersistentMemoryAllocator::Reference ranges_ref = bucket_ranges->persistent_reference(); if (!ranges_ref) { size_t ranges_count = bucket_count + 1; size_t ranges_bytes = ranges_count * sizeof(HistogramBase::Sample); ranges_ref = memory_allocator_->Allocate(ranges_bytes, kTypeIdRangesArray); if (ranges_ref) { HistogramBase::Sample* ranges_data = memory_allocator_->GetAsArray<HistogramBase::Sample>( ranges_ref, kTypeIdRangesArray, ranges_count); if (ranges_data) { for (size_t i = 0; i < bucket_ranges->size(); ++i) ranges_data[i] = bucket_ranges->range(i); bucket_ranges->set_persistent_reference(ranges_ref); } else { NOTREACHED(); ranges_ref = PersistentMemoryAllocator::kReferenceNull; } } } else { DCHECK_EQ(kTypeIdRangesArray, memory_allocator_->GetType(ranges_ref)); } if (ranges_ref && histogram_data) { histogram_data->minimum = minimum; histogram_data->maximum = maximum; histogram_data->bucket_count = static_cast<uint32_t>(bucket_count); histogram_data->ranges_ref = ranges_ref; histogram_data->ranges_checksum = bucket_ranges->checksum(); } else { histogram_data = nullptr; // Clear this for proper handling below. } } if (histogram_data) { std::unique_ptr<HistogramBase> histogram = CreateHistogram(histogram_data); DCHECK(histogram); DCHECK_NE(0U, histogram_data->samples_metadata.id); DCHECK_NE(0U, histogram_data->logged_metadata.id); PersistentMemoryAllocator::Reference histogram_ref = memory_allocator_->GetAsReference(histogram_data); if (ref_ptr != nullptr) *ref_ptr = histogram_ref; subtle::NoBarrier_Store(&last_created_, histogram_ref); return histogram; } CreateHistogramResultType result; if (memory_allocator_->IsCorrupt()) { RecordCreateHistogramResult(CREATE_HISTOGRAM_ALLOCATOR_NEWLY_CORRUPT); result = CREATE_HISTOGRAM_ALLOCATOR_CORRUPT; } else if (memory_allocator_->IsFull()) { result = CREATE_HISTOGRAM_ALLOCATOR_FULL; } else { result = CREATE_HISTOGRAM_ALLOCATOR_ERROR; } RecordCreateHistogramResult(result); if (result != CREATE_HISTOGRAM_ALLOCATOR_FULL) NOTREACHED() << memory_allocator_->Name() << ", error=" << result; return nullptr; } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264 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: z2grestore(i_ctx_t *i_ctx_p) { if (!restore_page_device(igs, gs_gstate_saved(igs))) return gs_grestore(igs); return push_callout(i_ctx_p, "%grestorepagedevice"); } Commit Message: CWE ID: Target: 1 Example 2: Code: void RecordDeliveryStatus(content::mojom::PushDeliveryStatus status) { UMA_HISTOGRAM_ENUMERATION( "PushMessaging.DeliveryStatus", status, static_cast<int>(content::mojom::PushDeliveryStatus::LAST) + 1); } Commit Message: Remove some senseless indirection from the Push API code Four files to call one Java function. Let's just call it directly. BUG= Change-Id: I6e988e9a000051dd7e3dd2b517a33a09afc2fff6 Reviewed-on: https://chromium-review.googlesource.com/749147 Reviewed-by: Anita Woodruff <[email protected]> Commit-Queue: Peter Beverloo <[email protected]> Cr-Commit-Position: refs/heads/master@{#513464} 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: std::set<base::CommandLine::StringType> ExtractFlagsFromCommandLine( const base::CommandLine& cmdline) { std::set<base::CommandLine::StringType> flags; base::CommandLine::StringVector::const_iterator first = std::find(cmdline.argv().begin(), cmdline.argv().end(), GetSwitchString(switches::kFlagSwitchesBegin)); base::CommandLine::StringVector::const_iterator last = std::find(cmdline.argv().begin(), cmdline.argv().end(), GetSwitchString(switches::kFlagSwitchesEnd)); if (first != cmdline.argv().end() && last != cmdline.argv().end()) flags.insert(first + 1, last); #if defined(OS_CHROMEOS) first = std::find(cmdline.argv().begin(), cmdline.argv().end(), GetSwitchString(chromeos::switches::kPolicySwitchesBegin)); last = std::find(cmdline.argv().begin(), cmdline.argv().end(), GetSwitchString(chromeos::switches::kPolicySwitchesEnd)); if (first != cmdline.argv().end() && last != cmdline.argv().end()) flags.insert(first + 1, last); #endif return flags; } Commit Message: Move smart deploy to tristate. BUG= Review URL: https://codereview.chromium.org/1149383006 Cr-Commit-Position: refs/heads/master@{#333058} 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 inline signed int ReadPropertyMSBLong(const unsigned char **p, size_t *length) { union { unsigned int unsigned_value; signed int signed_value; } quantum; int c; register ssize_t i; unsigned char buffer[4]; size_t value; if (*length < 4) return(-1); for (i=0; i < 4; i++) { c=(int) (*(*p)++); (*length)--; buffer[i]=(unsigned char) c; } value=(size_t) (buffer[0] << 24); value|=buffer[1] << 16; value|=buffer[2] << 8; value|=buffer[3]; quantum.unsigned_value=(value & 0xffffffff); return(quantum.signed_value); } Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed) CWE ID: CWE-125 Target: 1 Example 2: Code: long syscall_trace_enter(struct pt_regs *regs) { long ret = 0; /* * If we stepped into a sysenter/syscall insn, it trapped in * kernel mode; do_debug() cleared TF and set TIF_SINGLESTEP. * If user-mode had set TF itself, then it's still clear from * do_debug() and we need to set it again to restore the user * state. If we entered on the slow path, TF was already set. */ if (test_thread_flag(TIF_SINGLESTEP)) regs->flags |= X86_EFLAGS_TF; /* do the secure computing check first */ secure_computing(regs->orig_ax); if (unlikely(test_thread_flag(TIF_SYSCALL_EMU))) ret = -1L; if ((ret || test_thread_flag(TIF_SYSCALL_TRACE)) && tracehook_report_syscall_entry(regs)) ret = -1L; if (unlikely(test_thread_flag(TIF_SYSCALL_TRACEPOINT))) trace_sys_enter(regs, regs->orig_ax); if (unlikely(current->audit_context)) { if (IS_IA32) audit_syscall_entry(AUDIT_ARCH_I386, regs->orig_ax, regs->bx, regs->cx, regs->dx, regs->si); #ifdef CONFIG_X86_64 else audit_syscall_entry(AUDIT_ARCH_X86_64, regs->orig_ax, regs->di, regs->si, regs->dx, regs->r10); #endif } return ret ?: regs->orig_ax; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 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 __init ext4_init_fs(void) { int i, err; ext4_check_flag_values(); for (i = 0; i < EXT4_WQ_HASH_SZ; i++) { mutex_init(&ext4__aio_mutex[i]); init_waitqueue_head(&ext4__ioend_wq[i]); } err = ext4_init_pageio(); if (err) return err; err = ext4_init_system_zone(); if (err) goto out7; ext4_kset = kset_create_and_add("ext4", NULL, fs_kobj); if (!ext4_kset) goto out6; ext4_proc_root = proc_mkdir("fs/ext4", NULL); if (!ext4_proc_root) goto out5; err = ext4_init_feat_adverts(); if (err) goto out4; err = ext4_init_mballoc(); if (err) goto out3; err = ext4_init_xattr(); if (err) goto out2; err = init_inodecache(); if (err) goto out1; register_as_ext2(); register_as_ext3(); err = register_filesystem(&ext4_fs_type); if (err) goto out; ext4_li_info = NULL; mutex_init(&ext4_li_mtx); return 0; out: unregister_as_ext2(); unregister_as_ext3(); destroy_inodecache(); out1: ext4_exit_xattr(); out2: ext4_exit_mballoc(); out3: ext4_exit_feat_adverts(); out4: remove_proc_entry("fs/ext4", NULL); out5: kset_unregister(ext4_kset); out6: ext4_exit_system_zone(); out7: ext4_exit_pageio(); return err; } Commit Message: ext4: init timer earlier to avoid a kernel panic in __save_error_info During mount, when we fail to open journal inode or root inode, the __save_error_info will mod_timer. But actually s_err_report isn't initialized yet and the kernel oops. The detailed information can be found https://bugzilla.kernel.org/show_bug.cgi?id=32082. The best way is to check whether the timer s_err_report is initialized or not. But it seems that in include/linux/timer.h, we can't find a good function to check the status of this timer, so this patch just move the initializtion of s_err_report earlier so that we can avoid the kernel panic. The corresponding del_timer is also added in the error path. Reported-by: Sami Liedes <[email protected]> Signed-off-by: Tao Ma <[email protected]> Signed-off-by: "Theodore Ts'o" <[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: FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj, unsigned length) { FLAC__uint32 i; FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)); /* read vendor string */ if (length >= 8) { length -= 8; /* vendor string length + num comments entries alone take 8 bytes */ FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32); if (!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length)) return false; /* read_callback_ sets the state for us */ if (obj->vendor_string.length > 0) { if (length < obj->vendor_string.length) { obj->vendor_string.length = 0; obj->vendor_string.entry = 0; goto skip; } else length -= obj->vendor_string.length; if (0 == (obj->vendor_string.entry = safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) { decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; return false; } if (!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length)) return false; /* read_callback_ sets the state for us */ obj->vendor_string.entry[obj->vendor_string.length] = '\0'; } else obj->vendor_string.entry = 0; /* read num comments */ FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32); if (!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments)) return false; /* read_callback_ sets the state for us */ /* read comments */ if (obj->num_comments > 100000) { /* Possibly malicious file. */ obj->num_comments = 0; return false; } if (obj->num_comments > 0) { if (0 == (obj->comments = safe_malloc_mul_2op_p(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) { decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; return false; } for (i = 0; i < obj->num_comments; i++) { /* Initialize here just to make sure. */ obj->comments[i].length = 0; obj->comments[i].entry = 0; FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32); if (length < 4) { obj->num_comments = i; goto skip; } else length -= 4; if (!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length)) return false; /* read_callback_ sets the state for us */ if (obj->comments[i].length > 0) { if (length < obj->comments[i].length) { obj->num_comments = i; goto skip; } else length -= obj->comments[i].length; if (0 == (obj->comments[i].entry = safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) { decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; return false; } memset (obj->comments[i].entry, 0, obj->comments[i].length) ; if (!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length)) { obj->num_comments = i; goto skip; } obj->comments[i].entry[obj->comments[i].length] = '\0'; } else obj->comments[i].entry = 0; } } else obj->comments = 0; } skip: if (length > 0) { /* This will only happen on files with invalid data in comments */ if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length)) return false; /* read_callback_ sets the state for us */ } return true; } Commit Message: Avoid free-before-initialize vulnerability in heap Bug: 27211885 Change-Id: Ib9c93bd9ffdde2a5f8d31a86f06e267dc9c152db CWE ID: CWE-119 Target: 1 Example 2: Code: void ResourceDispatcherHostImpl::OnTransferRequestToNewPage(int new_routing_id, int request_id) { PendingRequestList::iterator i = pending_requests_.find( GlobalRequestID(filter_->child_id(), request_id)); if (i == pending_requests_.end()) { DVLOG(1) << "Updating a request that wasn't found"; return; } net::URLRequest* request = i->second; ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request); info->set_route_id(new_routing_id); } Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T> This change refines r137676. BUG=122654 TEST=browser_test Review URL: https://chromiumcodereview.appspot.com/10332233 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98 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: xsltAddTemplate(xsltStylesheetPtr style, xsltTemplatePtr cur, const xmlChar *mode, const xmlChar *modeURI) { xsltCompMatchPtr pat, list, next; /* * 'top' will point to style->xxxMatch ptr - declaring as 'void' * avoids gcc 'type-punned pointer' warning. */ void **top = NULL; const xmlChar *name = NULL; float priority; /* the priority */ if ((style == NULL) || (cur == NULL) || (cur->match == NULL)) return(-1); priority = cur->priority; pat = xsltCompilePatternInternal(cur->match, style->doc, cur->elem, style, NULL, 1); if (pat == NULL) return(-1); while (pat) { next = pat->next; pat->next = NULL; name = NULL; pat->template = cur; if (mode != NULL) pat->mode = xmlDictLookup(style->dict, mode, -1); if (modeURI != NULL) pat->modeURI = xmlDictLookup(style->dict, modeURI, -1); if (priority != XSLT_PAT_NO_PRIORITY) pat->priority = priority; /* * insert it in the hash table list corresponding to its lookup name */ switch (pat->steps[0].op) { case XSLT_OP_ATTR: if (pat->steps[0].value != NULL) name = pat->steps[0].value; else top = &(style->attrMatch); break; case XSLT_OP_PARENT: case XSLT_OP_ANCESTOR: top = &(style->elemMatch); break; case XSLT_OP_ROOT: top = &(style->rootMatch); break; case XSLT_OP_KEY: top = &(style->keyMatch); break; case XSLT_OP_ID: /* TODO optimize ID !!! */ case XSLT_OP_NS: case XSLT_OP_ALL: top = &(style->elemMatch); break; case XSLT_OP_END: case XSLT_OP_PREDICATE: xsltTransformError(NULL, style, NULL, "xsltAddTemplate: invalid compiled pattern\n"); xsltFreeCompMatch(pat); return(-1); /* * TODO: some flags at the top level about type based patterns * would be faster than inclusion in the hash table. */ case XSLT_OP_PI: if (pat->steps[0].value != NULL) name = pat->steps[0].value; else top = &(style->piMatch); break; case XSLT_OP_COMMENT: top = &(style->commentMatch); break; case XSLT_OP_TEXT: top = &(style->textMatch); break; case XSLT_OP_ELEM: case XSLT_OP_NODE: if (pat->steps[0].value != NULL) name = pat->steps[0].value; else top = &(style->elemMatch); break; } if (name != NULL) { if (style->templatesHash == NULL) { style->templatesHash = xmlHashCreate(1024); if (style->templatesHash == NULL) { xsltFreeCompMatch(pat); return(-1); } xmlHashAddEntry3(style->templatesHash, name, mode, modeURI, pat); } else { list = (xsltCompMatchPtr) xmlHashLookup3(style->templatesHash, name, mode, modeURI); if (list == NULL) { xmlHashAddEntry3(style->templatesHash, name, mode, modeURI, pat); } else { /* * Note '<=' since one must choose among the matching * template rules that are left, the one that occurs * last in the stylesheet */ if (list->priority <= pat->priority) { pat->next = list; xmlHashUpdateEntry3(style->templatesHash, name, mode, modeURI, pat, NULL); } else { while (list->next != NULL) { if (list->next->priority <= pat->priority) break; list = list->next; } pat->next = list->next; list->next = pat; } } } } else if (top != NULL) { list = *top; if (list == NULL) { *top = pat; pat->next = NULL; } else if (list->priority <= pat->priority) { pat->next = list; *top = pat; } else { while (list->next != NULL) { if (list->next->priority <= pat->priority) break; list = list->next; } pat->next = list->next; list->next = pat; } } else { xsltTransformError(NULL, style, NULL, "xsltAddTemplate: invalid compiled pattern\n"); xsltFreeCompMatch(pat); return(-1); } #ifdef WITH_XSLT_DEBUG_PATTERN if (mode) xsltGenericDebug(xsltGenericDebugContext, "added pattern : '%s' mode '%s' priority %f\n", pat->pattern, pat->mode, pat->priority); else xsltGenericDebug(xsltGenericDebugContext, "added pattern : '%s' priority %f\n", pat->pattern, pat->priority); #endif pat = next; } return(0); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 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 int hns_xgmac_get_sset_count(int stringset) { if (stringset == ETH_SS_STATS) return ARRAY_SIZE(g_xgmac_stats_string); return 0; } Commit Message: net: hns: fix ethtool_get_strings overflow in hns driver hns_get_sset_count() returns HNS_NET_STATS_CNT and the data space allocated is not enough for ethtool_get_strings(), which will cause random memory corruption. When SLAB and DEBUG_SLAB are both enabled, memory corruptions like the the following can be observed without this patch: [ 43.115200] Slab corruption (Not tainted): Acpi-ParseExt start=ffff801fb0b69030, len=80 [ 43.115206] Redzone: 0x9f911029d006462/0x5f78745f31657070. [ 43.115208] Last user: [<5f7272655f746b70>](0x5f7272655f746b70) [ 43.115214] 010: 70 70 65 31 5f 74 78 5f 70 6b 74 00 6b 6b 6b 6b ppe1_tx_pkt.kkkk [ 43.115217] 030: 70 70 65 31 5f 74 78 5f 70 6b 74 5f 6f 6b 00 6b ppe1_tx_pkt_ok.k [ 43.115218] Next obj: start=ffff801fb0b69098, len=80 [ 43.115220] Redzone: 0x706d655f6f666966/0x9f911029d74e35b. [ 43.115229] Last user: [<ffff0000084b11b0>](acpi_os_release_object+0x28/0x38) [ 43.115231] 000: 74 79 00 6b 6b 6b 6b 6b 70 70 65 31 5f 74 78 5f ty.kkkkkppe1_tx_ [ 43.115232] 010: 70 6b 74 5f 65 72 72 5f 63 73 75 6d 5f 66 61 69 pkt_err_csum_fai Signed-off-by: Timmy Li <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static int cts_cbc_encrypt(struct crypto_cts_ctx *ctx, struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int offset, unsigned int nbytes) { int bsize = crypto_blkcipher_blocksize(desc->tfm); u8 tmp[bsize], tmp2[bsize]; struct blkcipher_desc lcldesc; struct scatterlist sgsrc[1], sgdst[1]; int lastn = nbytes - bsize; u8 iv[bsize]; u8 s[bsize * 2], d[bsize * 2]; int err; if (lastn < 0) return -EINVAL; sg_init_table(sgsrc, 1); sg_init_table(sgdst, 1); memset(s, 0, sizeof(s)); scatterwalk_map_and_copy(s, src, offset, nbytes, 0); memcpy(iv, desc->info, bsize); lcldesc.tfm = ctx->child; lcldesc.info = iv; lcldesc.flags = desc->flags; sg_set_buf(&sgsrc[0], s, bsize); sg_set_buf(&sgdst[0], tmp, bsize); err = crypto_blkcipher_encrypt_iv(&lcldesc, sgdst, sgsrc, bsize); memcpy(d + bsize, tmp, lastn); lcldesc.info = tmp; sg_set_buf(&sgsrc[0], s + bsize, bsize); sg_set_buf(&sgdst[0], tmp2, bsize); err = crypto_blkcipher_encrypt_iv(&lcldesc, sgdst, sgsrc, bsize); memcpy(d, tmp2, bsize); scatterwalk_map_and_copy(d, dst, offset, nbytes, 1); memcpy(desc->info, tmp2, bsize); return err; } Commit Message: crypto: include crypto- module prefix in template This adds the module loading prefix "crypto-" to the template lookup as well. For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly includes the "crypto-" prefix at every level, correctly rejecting "vfat": net-pf-38 algif-hash crypto-vfat(blowfish) crypto-vfat(blowfish)-all crypto-vfat Reported-by: Mathias Krause <[email protected]> Signed-off-by: Kees Cook <[email protected]> Acked-by: Mathias Krause <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 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: long mkvparser::UnserializeFloat(IMkvReader* pReader, long long pos, long long size_, double& result) { assert(pReader); assert(pos >= 0); if ((size_ != 4) && (size_ != 8)) return E_FILE_FORMAT_INVALID; const long size = static_cast<long>(size_); unsigned char buf[8]; const int status = pReader->Read(pos, size, buf); if (status < 0) // error return status; if (size == 4) { union { float f; unsigned long ff; }; ff = 0; for (int i = 0;;) { ff |= buf[i]; if (++i >= 4) break; ff <<= 8; } result = f; } else { assert(size == 8); union { double d; unsigned long long dd; }; dd = 0; for (int i = 0;;) { dd |= buf[i]; if (++i >= 8) break; dd <<= 8; } result = d; } return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20 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: void JBIG2Stream::readSegments() { Guint segNum, segFlags, segType, page, segLength; Guint refFlags, nRefSegs; Guint *refSegs; Goffset segDataPos; int c1, c2, c3; Guint i; while (readULong(&segNum)) { if (!readUByte(&segFlags)) { goto eofError1; } segType = segFlags & 0x3f; if (!readUByte(&refFlags)) { goto eofError1; } nRefSegs = refFlags >> 5; if (nRefSegs == 7) { if ((c1 = curStr->getChar()) == EOF || (c2 = curStr->getChar()) == EOF || (c3 = curStr->getChar()) == EOF) { goto eofError1; } refFlags = (refFlags << 24) | (c1 << 16) | (c2 << 8) | c3; nRefSegs = refFlags & 0x1fffffff; for (i = 0; i < (nRefSegs + 9) >> 3; ++i) { if ((c1 = curStr->getChar()) == EOF) { goto eofError1; } } } refSegs = (Guint *)gmallocn(nRefSegs, sizeof(Guint)); if (segNum <= 256) { for (i = 0; i < nRefSegs; ++i) { if (!readUByte(&refSegs[i])) { goto eofError2; } } } else if (segNum <= 65536) { for (i = 0; i < nRefSegs; ++i) { if (!readUWord(&refSegs[i])) { goto eofError2; } } } else { for (i = 0; i < nRefSegs; ++i) { if (!readULong(&refSegs[i])) { goto eofError2; } } } if (segFlags & 0x40) { if (!readULong(&page)) { goto eofError2; } } else { if (!readUByte(&page)) { goto eofError2; } } if (!readULong(&segLength)) { goto eofError2; } segDataPos = curStr->getPos(); if (!pageBitmap && ((segType >= 4 && segType <= 7) || (segType >= 20 && segType <= 43))) { error(errSyntaxError, curStr->getPos(), "First JBIG2 segment associated with a page must be a page information segment"); goto syntaxError; } switch (segType) { case 0: if (!readSymbolDictSeg(segNum, segLength, refSegs, nRefSegs)) { goto syntaxError; } break; case 4: readTextRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs); break; case 6: readTextRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs); break; case 7: readTextRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs); break; case 16: readPatternDictSeg(segNum, segLength); break; case 20: readHalftoneRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs); break; case 22: readHalftoneRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs); break; case 23: readHalftoneRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs); break; case 36: readGenericRegionSeg(segNum, gFalse, gFalse, segLength); break; case 38: readGenericRegionSeg(segNum, gTrue, gFalse, segLength); break; case 39: readGenericRegionSeg(segNum, gTrue, gTrue, segLength); break; case 40: readGenericRefinementRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs); break; case 42: readGenericRefinementRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs); break; case 43: readGenericRefinementRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs); break; case 48: readPageInfoSeg(segLength); break; case 50: readEndOfStripeSeg(segLength); break; case 52: readProfilesSeg(segLength); break; case 53: readCodeTableSeg(segNum, segLength); break; case 62: readExtensionSeg(segLength); break; default: error(errSyntaxError, curStr->getPos(), "Unknown segment type in JBIG2 stream"); for (i = 0; i < segLength; ++i) { if ((c1 = curStr->getChar()) == EOF) { goto eofError2; } } break; } if (segLength != 0xffffffff) { Goffset segExtraBytes = segDataPos + segLength - curStr->getPos(); if (segExtraBytes > 0) { error(errSyntaxError, curStr->getPos(), "{0:d} extraneous byte{1:s} after segment", segExtraBytes, (segExtraBytes > 1) ? "s" : ""); int trash; for (Goffset i = segExtraBytes; i > 0; i--) { readByte(&trash); } } else if (segExtraBytes < 0) { error(errSyntaxError, curStr->getPos(), "Previous segment handler read too many bytes"); } } gfree(refSegs); } return; syntaxError: gfree(refSegs); return; eofError2: gfree(refSegs); eofError1: error(errSyntaxError, curStr->getPos(), "Unexpected EOF in JBIG2 stream"); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: copy_attr (char const *src_path, char const *dst_path) { return 0; } Commit Message: CWE ID: CWE-59 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: fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count = cc; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); if(cc%(bps*stride)!=0) { TIFFErrorExt(tif->tif_clientdata, "fpAcc", "%s", "cc%(bps*stride))!=0"); return 0; } if (!tmp) return 0; while (count > stride) { REPEAT4(stride, cp[stride] = (unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++) count -= stride; } _TIFFmemcpy(tmp, cp0, cc); cp = (uint8 *) cp0; for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[bps * count + byte] = tmp[byte * wc + count]; #else cp[bps * count + byte] = tmp[(bps - byte - 1) * wc + count]; #endif } } _TIFFfree(tmp); return 1; } Commit Message: * libtiff/tif_predic.c: fix memory leaks in error code paths added in previous commit (fix for MSVR 35105) CWE ID: CWE-119 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: void PropertyTreeManager::EmitClipMaskLayer() { int clip_id = EnsureCompositorClipNode(current_clip_); CompositorElementId mask_isolation_id, mask_effect_id; cc::Layer* mask_layer = client_.CreateOrReuseSynthesizedClipLayer( current_clip_, mask_isolation_id, mask_effect_id); cc::EffectNode& mask_isolation = *GetEffectTree().Node(current_effect_id_); DCHECK_EQ(static_cast<uint64_t>(cc::EffectNode::INVALID_STABLE_ID), mask_isolation.stable_id); mask_isolation.stable_id = mask_isolation_id.ToInternalValue(); cc::EffectNode& mask_effect = *GetEffectTree().Node( GetEffectTree().Insert(cc::EffectNode(), current_effect_id_)); mask_effect.stable_id = mask_effect_id.ToInternalValue(); mask_effect.clip_id = clip_id; mask_effect.has_render_surface = true; mask_effect.blend_mode = SkBlendMode::kDstIn; const TransformPaintPropertyNode* clip_space = current_clip_->LocalTransformSpace(); root_layer_->AddChild(mask_layer); mask_layer->set_property_tree_sequence_number(sequence_number_); mask_layer->SetTransformTreeIndex(EnsureCompositorTransformNode(clip_space)); int scroll_id = EnsureCompositorScrollNode(&clip_space->NearestScrollTranslationNode()); mask_layer->SetScrollTreeIndex(scroll_id); mask_layer->SetClipTreeIndex(clip_id); mask_layer->SetEffectTreeIndex(mask_effect.id); } 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 stsg_del(GF_Box *s) { GF_SubTrackSampleGroupBox *ptr = (GF_SubTrackSampleGroupBox *)s; if (ptr == NULL) return; if (ptr->group_description_index) gf_free(ptr->group_description_index); gf_free(ptr); } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125 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: _handle_conference(xmpp_stanza_t *const stanza) { xmpp_stanza_t *xns_conference = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CONFERENCE); const char *from = xmpp_stanza_get_from(stanza); if (!from) { log_warning("Message received with no from attribute, ignoring"); return; } Jid *jidp = jid_create(from); if (!jidp) { return; } const char *room = xmpp_stanza_get_attribute(xns_conference, STANZA_ATTR_JID); if (!room) { jid_destroy(jidp); return; } const char *reason = xmpp_stanza_get_attribute(xns_conference, STANZA_ATTR_REASON); const char *password = xmpp_stanza_get_attribute(xns_conference, STANZA_ATTR_PASSWORD); sv_ev_room_invite(INVITE_DIRECT, jidp->barejid, room, reason, password); jid_destroy(jidp); } Commit Message: Add carbons from check CWE ID: CWE-346 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: ParseNameValue(const char * buffer, int bufsize, struct NameValueParserData * data) { struct xmlparser parser; data->l_head = NULL; data->portListing = NULL; data->portListingLength = 0; /* init xmlparser object */ parser.xmlstart = buffer; parser.xmlsize = bufsize; parser.data = data; parser.starteltfunc = NameValueParserStartElt; parser.endeltfunc = NameValueParserEndElt; parser.datafunc = NameValueParserGetData; parser.attfunc = 0; parsexml(&parser); } Commit Message: properly initialize data structure for SOAP parsing in ParseNameValue() topelt field was not properly initialized. should fix #268 CWE ID: CWE-119 Target: 1 Example 2: Code: int terminal_vhangup_fd(int fd) { assert(fd >= 0); if (ioctl(fd, TIOCVHANGUP) < 0) return -errno; return 0; } Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check VT kbd reset check CWE ID: CWE-255 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 RenderMessageFilter::OnAllocateSharedMemory( uint32 buffer_size, base::SharedMemoryHandle* handle) { ChildProcessHostImpl::AllocateSharedMemory( buffer_size, peer_handle(), handle); } Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/ BUG=172573 Review URL: https://codereview.chromium.org/12177018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-287 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 struct kioctx *ioctx_alloc(unsigned nr_events) { struct mm_struct *mm = current->mm; struct kioctx *ctx; int err = -ENOMEM; /* * We keep track of the number of available ringbuffer slots, to prevent * overflow (reqs_available), and we also use percpu counters for this. * * So since up to half the slots might be on other cpu's percpu counters * and unavailable, double nr_events so userspace sees what they * expected: additionally, we move req_batch slots to/from percpu * counters at a time, so make sure that isn't 0: */ nr_events = max(nr_events, num_possible_cpus() * 4); nr_events *= 2; /* Prevent overflows */ if ((nr_events > (0x10000000U / sizeof(struct io_event))) || (nr_events > (0x10000000U / sizeof(struct kiocb)))) { pr_debug("ENOMEM: nr_events too high\n"); return ERR_PTR(-EINVAL); } if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL)) return ERR_PTR(-EAGAIN); ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL); if (!ctx) return ERR_PTR(-ENOMEM); ctx->max_reqs = nr_events; if (percpu_ref_init(&ctx->users, free_ioctx_users)) goto err; if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs)) goto err; spin_lock_init(&ctx->ctx_lock); spin_lock_init(&ctx->completion_lock); mutex_init(&ctx->ring_lock); init_waitqueue_head(&ctx->wait); INIT_LIST_HEAD(&ctx->active_reqs); ctx->cpu = alloc_percpu(struct kioctx_cpu); if (!ctx->cpu) goto err; if (aio_setup_ring(ctx) < 0) goto err; atomic_set(&ctx->reqs_available, ctx->nr_events - 1); ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4); if (ctx->req_batch < 1) ctx->req_batch = 1; /* limit the number of system wide aios */ spin_lock(&aio_nr_lock); if (aio_nr + nr_events > (aio_max_nr * 2UL) || aio_nr + nr_events < aio_nr) { spin_unlock(&aio_nr_lock); err = -EAGAIN; goto err; } aio_nr += ctx->max_reqs; spin_unlock(&aio_nr_lock); percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */ err = ioctx_add_table(ctx, mm); if (err) goto err_cleanup; pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n", ctx, ctx->user_id, mm, ctx->nr_events); return ctx; err_cleanup: aio_nr_sub(ctx->max_reqs); err: aio_free_ring(ctx); free_percpu(ctx->cpu); free_percpu(ctx->reqs.pcpu_count); free_percpu(ctx->users.pcpu_count); kmem_cache_free(kioctx_cachep, ctx); pr_debug("error allocating ioctx %d\n", err); return ERR_PTR(err); } Commit Message: aio: prevent double free in ioctx_alloc ioctx_alloc() calls aio_setup_ring() to allocate a ring. If aio_setup_ring() fails to do so it would call aio_free_ring() before returning, but ioctx_alloc() would call aio_free_ring() again causing a double free of the ring. This is easily reproducible from userspace. Signed-off-by: Sasha Levin <[email protected]> Signed-off-by: Benjamin LaHaise <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: int jpc_bitstream_fillbuf(jpc_bitstream_t *bitstream) { int c; /* Note: The count has already been decremented by the caller. */ assert(bitstream->openmode_ & JPC_BITSTREAM_READ); assert(bitstream->cnt_ <= 0); if (bitstream->flags_ & JPC_BITSTREAM_ERR) { bitstream->cnt_ = 0; return -1; } if (bitstream->flags_ & JPC_BITSTREAM_EOF) { bitstream->buf_ = 0x7f; bitstream->cnt_ = 7; return 1; } bitstream->buf_ = (bitstream->buf_ << 8) & 0xffff; if ((c = jas_stream_getc((bitstream)->stream_)) == EOF) { bitstream->flags_ |= JPC_BITSTREAM_EOF; return 1; } bitstream->cnt_ = (bitstream->buf_ == 0xff00) ? 6 : 7; bitstream->buf_ |= c & ((1 << (bitstream->cnt_ + 1)) - 1); return (bitstream->buf_ >> bitstream->cnt_) & 1; } Commit Message: Changed the JPC bitstream code to more gracefully handle a request for a larger sized integer than what can be handled (i.e., return with an error instead of failing an assert). CWE ID: 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 GLSurfaceEGLSurfaceControl::SwapBuffersAsync( SwapCompletionCallback completion_callback, PresentationCallback presentation_callback) { CommitPendingTransaction(std::move(completion_callback), std::move(presentation_callback)); } Commit Message: gpu/android : Add support for partial swap with surface control. Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should allow the display compositor to draw the minimum sub-rect necessary from the damage tracking in BufferQueue on the client-side, and also to pass this damage rect to the framework. [email protected] Bug: 926020 Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61 Reviewed-on: https://chromium-review.googlesource.com/c/1457467 Commit-Queue: Khushal <[email protected]> Commit-Queue: Antoine Labour <[email protected]> Reviewed-by: Antoine Labour <[email protected]> Auto-Submit: Khushal <[email protected]> Cr-Commit-Position: refs/heads/master@{#629852} CWE ID: 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: void PresentationConnectionProxy::DidChangeState( content::PresentationConnectionState state) { if (state == content::PRESENTATION_CONNECTION_STATE_CONNECTED) { source_connection_->didChangeState( blink::WebPresentationConnectionState::Connected); } else if (state == content::PRESENTATION_CONNECTION_STATE_CLOSED) { source_connection_->didChangeState( blink::WebPresentationConnectionState::Closed); } else { NOTREACHED(); } } Commit Message: [Presentation API] Add layout test for connection.close() and fix test failures Add layout test. 1-UA connection.close() hits NOTREACHED() in PresentationConnection::didChangeState(). Use PresentationConnection::didClose() instead. BUG=697719 Review-Url: https://codereview.chromium.org/2730123003 Cr-Commit-Position: refs/heads/master@{#455225} CWE ID: Target: 1 Example 2: Code: std::unique_ptr<TracedValue> InspectorEventDispatchEvent::Data( const Event& event) { std::unique_ptr<TracedValue> value = TracedValue::Create(); value->SetString("type", event.type()); SetCallStack(value.get()); return value; } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} 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 shutdown_executor(void) /* {{{ */ { zend_function *func; zend_class_entry *ce; zend_try { /* Removed because this can not be safely done, e.g. in this situation: Object 1 creates object 2 Object 3 holds reference to object 2. Now when 1 and 2 are destroyed, 3 can still access 2 in its destructor, with very problematic results */ /* zend_objects_store_call_destructors(&EG(objects_store)); */ /* Moved after symbol table cleaners, because some of the cleaners can call destructors, which would use EG(symtable_cache_ptr) and thus leave leaks */ /* while (EG(symtable_cache_ptr)>=EG(symtable_cache)) { zend_hash_destroy(*EG(symtable_cache_ptr)); efree(*EG(symtable_cache_ptr)); EG(symtable_cache_ptr)--; } */ zend_llist_apply(&zend_extensions, (llist_apply_func_t) zend_extension_deactivator); if (CG(unclean_shutdown)) { EG(symbol_table).pDestructor = zend_unclean_zval_ptr_dtor; } zend_hash_graceful_reverse_destroy(&EG(symbol_table)); } zend_end_try(); EG(valid_symbol_table) = 0; zend_try { zval *zeh; /* remove error handlers before destroying classes and functions, * so that if handler used some class, crash would not happen */ if (Z_TYPE(EG(user_error_handler)) != IS_UNDEF) { zeh = &EG(user_error_handler); zval_ptr_dtor(zeh); ZVAL_UNDEF(&EG(user_error_handler)); } if (Z_TYPE(EG(user_exception_handler)) != IS_UNDEF) { zeh = &EG(user_exception_handler); zval_ptr_dtor(zeh); ZVAL_UNDEF(&EG(user_exception_handler)); } zend_stack_clean(&EG(user_error_handlers_error_reporting), NULL, 1); zend_stack_clean(&EG(user_error_handlers), (void (*)(void *))ZVAL_DESTRUCTOR, 1); zend_stack_clean(&EG(user_exception_handlers), (void (*)(void *))ZVAL_DESTRUCTOR, 1); } zend_end_try(); zend_try { /* Cleanup static data for functions and arrays. * We need a separate cleanup stage because of the following problem: * Suppose we destroy class X, which destroys the class's function table, * and in the function table we have function foo() that has static $bar. * Now if an object of class X is assigned to $bar, its destructor will be * called and will fail since X's function table is in mid-destruction. * So we want first of all to clean up all data and then move to tables destruction. * Note that only run-time accessed data need to be cleaned up, pre-defined data can * not contain objects and thus are not probelmatic */ if (EG(full_tables_cleanup)) { ZEND_HASH_FOREACH_PTR(EG(function_table), func) { if (func->type == ZEND_USER_FUNCTION) { zend_cleanup_op_array_data((zend_op_array *) func); } } ZEND_HASH_FOREACH_END(); ZEND_HASH_REVERSE_FOREACH_PTR(EG(class_table), ce) { if (ce->type == ZEND_USER_CLASS) { zend_cleanup_user_class_data(ce); } else { zend_cleanup_internal_class_data(ce); } } ZEND_HASH_FOREACH_END(); } else { ZEND_HASH_REVERSE_FOREACH_PTR(EG(function_table), func) { if (func->type != ZEND_USER_FUNCTION) { break; } zend_cleanup_op_array_data((zend_op_array *) func); } ZEND_HASH_FOREACH_END(); ZEND_HASH_REVERSE_FOREACH_PTR(EG(class_table), ce) { if (ce->type != ZEND_USER_CLASS) { break; } zend_cleanup_user_class_data(ce); } ZEND_HASH_FOREACH_END(); zend_cleanup_internal_classes(); } } zend_end_try(); zend_try { zend_llist_destroy(&CG(open_files)); } zend_end_try(); zend_try { zend_close_rsrc_list(&EG(regular_list)); } zend_end_try(); #if ZEND_DEBUG if (GC_G(gc_enabled) && !CG(unclean_shutdown)) { gc_collect_cycles(); } #endif zend_try { zend_objects_store_free_object_storage(&EG(objects_store)); zend_vm_stack_destroy(); /* Destroy all op arrays */ if (EG(full_tables_cleanup)) { zend_hash_reverse_apply(EG(function_table), clean_non_persistent_function_full); zend_hash_reverse_apply(EG(class_table), clean_non_persistent_class_full); } else { zend_hash_reverse_apply(EG(function_table), clean_non_persistent_function); zend_hash_reverse_apply(EG(class_table), clean_non_persistent_class); } while (EG(symtable_cache_ptr)>=EG(symtable_cache)) { zend_hash_destroy(*EG(symtable_cache_ptr)); FREE_HASHTABLE(*EG(symtable_cache_ptr)); EG(symtable_cache_ptr)--; } } zend_end_try(); zend_try { clean_non_persistent_constants(); } zend_end_try(); zend_try { #if 0&&ZEND_DEBUG signal(SIGSEGV, original_sigsegv_handler); #endif zend_hash_destroy(&EG(included_files)); zend_stack_destroy(&EG(user_error_handlers_error_reporting)); zend_stack_destroy(&EG(user_error_handlers)); zend_stack_destroy(&EG(user_exception_handlers)); zend_objects_store_destroy(&EG(objects_store)); if (EG(in_autoload)) { zend_hash_destroy(EG(in_autoload)); FREE_HASHTABLE(EG(in_autoload)); } } zend_end_try(); zend_shutdown_fpu(); EG(ht_iterators_used) = 0; if (EG(ht_iterators) != EG(ht_iterators_slots)) { efree(EG(ht_iterators)); } EG(active) = 0; } /* }}} */ Commit Message: Use format string CWE ID: CWE-134 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 snd_ctl_replace(struct snd_card *card, struct snd_kcontrol *kcontrol, bool add_on_replace) { struct snd_ctl_elem_id id; unsigned int idx; struct snd_kcontrol *old; int ret; if (!kcontrol) return -EINVAL; if (snd_BUG_ON(!card || !kcontrol->info)) { ret = -EINVAL; goto error; } id = kcontrol->id; down_write(&card->controls_rwsem); old = snd_ctl_find_id(card, &id); if (!old) { if (add_on_replace) goto add; up_write(&card->controls_rwsem); ret = -EINVAL; goto error; } ret = snd_ctl_remove(card, old); if (ret < 0) { up_write(&card->controls_rwsem); goto error; } add: if (snd_ctl_find_hole(card, kcontrol->count) < 0) { up_write(&card->controls_rwsem); ret = -ENOMEM; goto error; } list_add_tail(&kcontrol->list, &card->controls); card->controls_count += kcontrol->count; kcontrol->id.numid = card->last_numid + 1; card->last_numid += kcontrol->count; up_write(&card->controls_rwsem); for (idx = 0; idx < kcontrol->count; idx++, id.index++, id.numid++) snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id); return 0; error: snd_ctl_free_one(kcontrol); return ret; } Commit Message: ALSA: control: Don't access controls outside of protected regions A control that is visible on the card->controls list can be freed at any time. This means we must not access any of its memory while not holding the controls_rw_lock. Otherwise we risk a use after free access. Signed-off-by: Lars-Peter Clausen <[email protected]> Acked-by: Jaroslav Kysela <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: Target: 1 Example 2: Code: static void encap_finish(void) { hash_clean(encap_hash, (void (*)(void *))encap_free); hash_free(encap_hash); encap_hash = NULL; #if ENABLE_BGP_VNC hash_clean(vnc_hash, (void (*)(void *))encap_free); hash_free(vnc_hash); vnc_hash = NULL; #endif } Commit Message: bgpd: don't use BGP_ATTR_VNC(255) unless ENABLE_BGP_VNC_ATTR is defined Signed-off-by: Lou Berger <[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: ClassicScript* ClassicPendingScript::GetSource(const KURL& document_url, bool& error_occurred) const { CheckState(); DCHECK(IsReady()); error_occurred = ErrorOccurred(); if (!is_external_) { ScriptSourceCode source_code( GetElement()->TextFromChildren(), source_location_type_, nullptr /* cache_handler */, document_url, StartingPosition()); return ClassicScript::Create(source_code, base_url_for_inline_script_, options_, kSharableCrossOrigin); } DCHECK(GetResource()->IsLoaded()); ScriptResource* resource = ToScriptResource(GetResource()); bool streamer_ready = (ready_state_ == kReady) && streamer_ && !streamer_->StreamingSuppressed(); ScriptSourceCode source_code(streamer_ready ? streamer_ : nullptr, resource); const KURL& base_url = source_code.Url(); return ClassicScript::Create(source_code, base_url, options_, resource->CalculateAccessControlStatus()); } Commit Message: Check CORS using PassesAccessControlCheck() with supplied SecurityOrigin Partial revert of https://chromium-review.googlesource.com/535694. Bug: 799477 Change-Id: I878bb9bcb83afaafe8601293db9aa644fc5929b3 Reviewed-on: https://chromium-review.googlesource.com/898427 Commit-Queue: Hiroshige Hayashizaki <[email protected]> Reviewed-by: Kouhei Ueno <[email protected]> Reviewed-by: Yutaka Hirano <[email protected]> Reviewed-by: Takeshi Yoshino <[email protected]> Cr-Commit-Position: refs/heads/master@{#535176} 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: DataReductionProxySettings::DataReductionProxySettings() : unreachable_(false), deferred_initialization_(false), prefs_(nullptr), config_(nullptr), clock_(base::DefaultClock::GetInstance()) {} Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119 Target: 1 Example 2: Code: int luaD_poscall (lua_State *L, StkId firstResult) { StkId res; int wanted, i; CallInfo *ci; if (L->hookmask & LUA_MASKRET) firstResult = callrethooks(L, firstResult); ci = L->ci--; res = ci->func; /* res == final position of 1st result */ wanted = ci->nresults; L->base = (ci - 1)->base; /* restore base */ L->savedpc = (ci - 1)->savedpc; /* restore savedpc */ /* move results to correct place */ for (i = wanted; i != 0 && firstResult < L->top; i--) setobjs2s(L, res++, firstResult++); while (i-- > 0) setnilvalue(res++); L->top = res; return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */ } Commit Message: disable loading lua bytecode 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: WM_SYMBOL midi *WildMidi_OpenBuffer(uint8_t *midibuffer, uint32_t size) { uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A }; uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' }; midi * ret = NULL; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (NULL); } if (midibuffer == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL midi data buffer)", 0); return (NULL); } if (size > WM_MAXFILESIZE) { /* don't bother loading suspiciously long files */ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_LONGFIL, NULL, 0); return (NULL); } if (memcmp(midibuffer,"HMIMIDIP", 8) == 0) { ret = (void *) _WM_ParseNewHmp(midibuffer, size); } else if (memcmp(midibuffer, "HMI-MIDISONG061595", 18) == 0) { ret = (void *) _WM_ParseNewHmi(midibuffer, size); } else if (memcmp(midibuffer, mus_hdr, 4) == 0) { ret = (void *) _WM_ParseNewMus(midibuffer, size); } else if (memcmp(midibuffer, xmi_hdr, 4) == 0) { ret = (void *) _WM_ParseNewXmi(midibuffer, size); } else { ret = (void *) _WM_ParseNewMidi(midibuffer, size); } if (ret) { if (add_handle(ret) != 0) { WildMidi_Close(ret); ret = NULL; } } return (ret); } Commit Message: wildmidi_lib.c (WildMidi_Open, WildMidi_OpenBuffer): refuse to proceed if less then 18 bytes of input Fixes bug #178. 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: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); extra_confusable_mapper_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8( "[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;" "[ĸκкқҝҟҡӄԟ] > k; [ŋпԥ] > n; œ > ce;" "[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;" "[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;" "[ҫင] > c; ұ > y; [χҳӽӿ] > x;" "ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;" "[зҙӡ] > 3; [บບ] > u"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } Commit Message: Add confusability mapping entries for Myanmar and Georgian U+10D5 (ვ), U+1012 (ဒ) => 3 Bug: 847242, 849398 Test: components_unittests --gtest_filter=*IDN* Change-Id: I9abb8560cf1c9e8e5e8d89980780b89461f7be52 Reviewed-on: https://chromium-review.googlesource.com/1091430 Reviewed-by: Peter Kasting <[email protected]> Commit-Queue: Mustafa Emre Acer <[email protected]> Cr-Commit-Position: refs/heads/master@{#565709} CWE ID: Target: 1 Example 2: Code: error::Error GLES2DecoderPassthroughImpl::DoGetVertexAttribPointerv( GLuint index, GLenum pname, GLsizei bufsize, GLsizei* length, GLuint* pointer) { std::array<void*, 1> temp_pointers{{nullptr}}; GLsizei temp_length = 0; api()->glGetVertexAttribPointervRobustANGLEFn( index, pname, static_cast<GLsizei>(temp_pointers.size()), &temp_length, temp_pointers.data()); DCHECK(temp_length >= 0 && temp_length <= static_cast<GLsizei>(temp_pointers.size()) && temp_length <= bufsize); for (GLsizei ii = 0; ii < temp_length; ii++) { pointer[ii] = static_cast<GLuint>(reinterpret_cast<uintptr_t>(temp_pointers[ii])); } *length = temp_length; return error::kNoError; } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} 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: gss_unwrap_iov (minor_status, context_handle, conf_state, qop_state, iov, iov_count) OM_uint32 * minor_status; gss_ctx_id_t context_handle; int * conf_state; gss_qop_t *qop_state; gss_iov_buffer_desc * iov; int iov_count; { /* EXPORT DELETE START */ OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; status = val_unwrap_iov_args(minor_status, context_handle, conf_state, qop_state, iov, iov_count); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_unwrap_iov) { status = mech->gss_unwrap_iov( minor_status, ctx->internal_ctx_id, conf_state, qop_state, iov, iov_count); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return(status); } /* EXPORT DELETE END */ return (GSS_S_BAD_MECH); } Commit Message: Preserve GSS context on init/accept failure After gss_init_sec_context() or gss_accept_sec_context() has created a context, don't delete the mechglue context on failures from subsequent calls, even if the mechanism deletes the mech-specific context (which is allowed by RFC 2744 but not preferred). Check for union contexts with no mechanism context in each GSS function which accepts a gss_ctx_id_t. CVE-2017-11462: RFC 2744 permits a GSS-API implementation to delete an existing security context on a second or subsequent call to gss_init_sec_context() or gss_accept_sec_context() if the call results in an error. This API behavior has been found to be dangerous, leading to the possibility of memory errors in some callers. For safety, GSS-API implementations should instead preserve existing security contexts on error until the caller deletes them. All versions of MIT krb5 prior to this change may delete acceptor contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through 1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on error. ticket: 8598 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup CWE ID: CWE-415 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 EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int i, j, bl; if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { i = ctx->cipher->do_cipher(ctx, out, in, inl); if (i < 0) return 0; else *outl = i; return 1; } if (inl <= 0) { *outl = 0; return inl == 0; } if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) { if (ctx->cipher->do_cipher(ctx, out, in, inl)) { *outl = inl; return 1; } else { *outl = 0; return 0; } } i = ctx->buf_len; bl = ctx->cipher->block_size; OPENSSL_assert(bl <= (int)sizeof(ctx->buf)); if (i != 0) { if (i + inl < bl) { memcpy(&(ctx->buf[i]), in, inl); ctx->buf_len += inl; *outl = 0; return 1; } else { j = bl - i; memcpy(&(ctx->buf[i]), in, j); if (!ctx->cipher->do_cipher(ctx, out, ctx->buf, bl)) return 0; inl -= j; in += j; out += bl; *outl = bl; } } else *outl = 0; i = inl & (bl - 1); inl -= i; if (inl > 0) { if (!ctx->cipher->do_cipher(ctx, out, in, inl)) return 0; *outl += inl; } if (i != 0) memcpy(ctx->buf, &(in[inl]), i); ctx->buf_len = i; return 1; } Commit Message: CWE ID: CWE-189 Target: 1 Example 2: Code: set_fflags_platform(struct archive_write_disk *a, int fd, const char *name, mode_t mode, unsigned long set, unsigned long clear) { int r; (void)mode; /* UNUSED */ if (set == 0 && clear == 0) return (ARCHIVE_OK); /* * XXX Is the stat here really necessary? Or can I just use * the 'set' flags directly? In particular, I'm not sure * about the correct approach if we're overwriting an existing * file that already has flags on it. XXX */ if ((r = lazy_stat(a)) != ARCHIVE_OK) return (r); a->st.st_flags &= ~clear; a->st.st_flags |= set; #ifdef HAVE_FCHFLAGS /* If platform has fchflags() and we were given an fd, use it. */ if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0) return (ARCHIVE_OK); #endif /* * If we can't use the fd to set the flags, we'll use the * pathname to set flags. We prefer lchflags() but will use * chflags() if we must. */ #ifdef HAVE_LCHFLAGS if (lchflags(name, a->st.st_flags) == 0) return (ARCHIVE_OK); #elif defined(HAVE_CHFLAGS) if (S_ISLNK(a->st.st_mode)) { archive_set_error(&a->archive, errno, "Can't set file flags on symlink."); return (ARCHIVE_WARN); } if (chflags(name, a->st.st_flags) == 0) return (ARCHIVE_OK); #endif archive_set_error(&a->archive, errno, "Failed to set file flags"); return (ARCHIVE_WARN); } Commit Message: Add ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS option This fixes a directory traversal in the cpio tool. CWE ID: CWE-22 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 *eval_map_next(struct seq_file *m, void *v, loff_t *pos) { union trace_eval_map_item *ptr = v; /* * Paranoid! If ptr points to end, we don't want to increment past it. * This really should never happen. */ ptr = update_eval_map(ptr); if (WARN_ON_ONCE(!ptr)) return NULL; ptr++; (*pos)++; ptr = update_eval_map(ptr); return ptr; } Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace Pull tracing fixes from Steven Rostedt: "This contains a few fixes and a clean up. - a bad merge caused an "endif" to go in the wrong place in scripts/Makefile.build - softirq tracing fix for tracing that corrupts lockdep and causes a false splat - histogram documentation typo fixes - fix a bad memory reference when passing in no filter to the filter code - simplify code by using the swap macro instead of open coding the swap" * tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace: tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount tracing: Fix some errors in histogram documentation tracing: Use swap macro in update_max_tr softirq: Reorder trace_softirqs_on to prevent lockdep splat tracing: Check for no filter when processing event filters CWE ID: CWE-787 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: cib_send_plaintext(int sock, xmlNode * msg) { char *xml_text = dump_xml_unformatted(msg); if (xml_text != NULL) { int rc = 0; char *unsent = xml_text; int len = strlen(xml_text); len++; /* null char */ crm_trace("Message on socket %d: size=%d", sock, len); retry: rc = write(sock, unsent, len); if (rc < 0) { switch (errno) { case EINTR: case EAGAIN: crm_trace("Retry"); goto retry; default: crm_perror(LOG_ERR, "Could only write %d of the remaining %d bytes", rc, len); break; } } else if (rc < len) { crm_trace("Only sent %d of %d remaining bytes", rc, len); len -= rc; unsent += rc; goto retry; } else { crm_trace("Sent %d bytes: %.100s", rc, xml_text); } } free(xml_text); return NULL; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399 Target: 1 Example 2: Code: xfs_attr_remove( xfs_inode_t *dp, const unsigned char *name, int flags) { int error; struct xfs_name xname; XFS_STATS_INC(xs_attr_remove); if (XFS_FORCED_SHUTDOWN(dp->i_mount)) return (EIO); error = xfs_attr_name_to_xname(&xname, name); if (error) return error; xfs_ilock(dp, XFS_ILOCK_SHARED); if (!xfs_inode_hasattr(dp)) { xfs_iunlock(dp, XFS_ILOCK_SHARED); return XFS_ERROR(ENOATTR); } xfs_iunlock(dp, XFS_ILOCK_SHARED); return xfs_attr_remove_int(dp, &xname, flags); } Commit Message: xfs: remote attribute overwrite causes transaction overrun Commit e461fcb ("xfs: remote attribute lookups require the value length") passes the remote attribute length in the xfs_da_args structure on lookup so that CRC calculations and validity checking can be performed correctly by related code. This, unfortunately has the side effect of changing the args->valuelen parameter in cases where it shouldn't. That is, when we replace a remote attribute, the incoming replacement stores the value and length in args->value and args->valuelen, but then the lookup which finds the existing remote attribute overwrites args->valuelen with the length of the remote attribute being replaced. Hence when we go to create the new attribute, we create it of the size of the existing remote attribute, not the size it is supposed to be. When the new attribute is much smaller than the old attribute, this results in a transaction overrun and an ASSERT() failure on a debug kernel: XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331 Fix this by keeping the remote attribute value length separate to the attribute value length in the xfs_da_args structure. The enables us to pass the length of the remote attribute to be removed without overwriting the new attribute's length. Also, ensure that when we save remote block contexts for a later rename we zero the original state variables so that we don't confuse the state of the attribute to be removes with the state of the new attribute that we just added. [Spotted by Brain Foster.] Signed-off-by: Dave Chinner <[email protected]> Reviewed-by: Brian Foster <[email protected]> Signed-off-by: Dave Chinner <[email protected]> CWE ID: CWE-19 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 spl_filesystem_file_read_line(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { int ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); while (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY) && ret == SUCCESS && spl_filesystem_file_is_empty_line(intern TSRMLS_CC)) { spl_filesystem_file_free_line(intern TSRMLS_CC); ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); } return ret; } /* }}} */ 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: gs_nulldevice(gs_gstate * pgs) { int code = 0; if (pgs->device == 0 || !gx_device_is_null(pgs->device)) { gx_device *ndev; code = gs_copydevice(&ndev, (const gx_device *)&gs_null_device, pgs->memory); if (code < 0) return code; /* * Internal devices have a reference count of 0, not 1, * aside from references from graphics states. to sort out how the icc profile is best handled with this device. It seems to inherit properties from the current device if there is one */ rc_init(ndev, pgs->memory, 0); if (pgs->device != NULL) { if ((code = dev_proc(pgs->device, get_profile)(pgs->device, &(ndev->icc_struct))) < 0) return code; rc_increment(ndev->icc_struct); set_dev_proc(ndev, get_profile, gx_default_get_profile); } if ((code = gs_setdevice_no_erase(pgs, ndev)) < 0) if ((code = gs_setdevice_no_erase(pgs, ndev)) < 0) gs_free_object(pgs->memory, ndev, "gs_copydevice(device)"); } return code; } Commit Message: CWE ID: CWE-78 Target: 1 Example 2: Code: static int nl80211_remain_on_channel(struct sk_buff *skb, struct genl_info *info) { struct cfg80211_registered_device *rdev = info->user_ptr[0]; struct net_device *dev = info->user_ptr[1]; struct ieee80211_channel *chan; struct sk_buff *msg; void *hdr; u64 cookie; enum nl80211_channel_type channel_type = NL80211_CHAN_NO_HT; u32 freq, duration; int err; if (!info->attrs[NL80211_ATTR_WIPHY_FREQ] || !info->attrs[NL80211_ATTR_DURATION]) return -EINVAL; duration = nla_get_u32(info->attrs[NL80211_ATTR_DURATION]); /* * We should be on that channel for at least one jiffie, * and more than 5 seconds seems excessive. */ if (!duration || !msecs_to_jiffies(duration) || duration > rdev->wiphy.max_remain_on_channel_duration) return -EINVAL; if (!rdev->ops->remain_on_channel) return -EOPNOTSUPP; if (info->attrs[NL80211_ATTR_WIPHY_CHANNEL_TYPE]) { channel_type = nla_get_u32( info->attrs[NL80211_ATTR_WIPHY_CHANNEL_TYPE]); if (channel_type != NL80211_CHAN_NO_HT && channel_type != NL80211_CHAN_HT20 && channel_type != NL80211_CHAN_HT40PLUS && channel_type != NL80211_CHAN_HT40MINUS) return -EINVAL; } freq = nla_get_u32(info->attrs[NL80211_ATTR_WIPHY_FREQ]); chan = rdev_freq_to_chan(rdev, freq, channel_type); if (chan == NULL) return -EINVAL; msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL); if (!msg) return -ENOMEM; hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0, NL80211_CMD_REMAIN_ON_CHANNEL); if (IS_ERR(hdr)) { err = PTR_ERR(hdr); goto free_msg; } err = rdev->ops->remain_on_channel(&rdev->wiphy, dev, chan, channel_type, duration, &cookie); if (err) goto free_msg; NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, cookie); genlmsg_end(msg, hdr); return genlmsg_reply(msg, info); nla_put_failure: err = -ENOBUFS; free_msg: nlmsg_free(msg); return err; } Commit Message: nl80211: fix check for valid SSID size in scan operations In both trigger_scan and sched_scan operations, we were checking for the SSID length before assigning the value correctly. Since the memory was just kzalloc'ed, the check was always failing and SSID with over 32 characters were allowed to go through. This was causing a buffer overflow when copying the actual SSID to the proper place. This bug has been there since 2.6.29-rc4. Cc: [email protected] Signed-off-by: Luciano Coelho <[email protected]> Signed-off-by: John W. Linville <[email protected]> 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 file_checksum(const char *fname, const STRUCT_STAT *st_p, char *sum) { struct map_struct *buf; OFF_T i, len = st_p->st_size; md_context m; int32 remainder; int fd; memset(sum, 0, MAX_DIGEST_LEN); fd = do_open(fname, O_RDONLY, 0); if (fd == -1) return; buf = map_file(fd, len, MAX_MAP_SIZE, CSUM_CHUNK); switch (checksum_type) { case CSUM_MD5: md5_begin(&m); for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) { md5_update(&m, (uchar *)map_ptr(buf, i, CSUM_CHUNK), CSUM_CHUNK); } remainder = (int32)(len - i); if (remainder > 0) md5_update(&m, (uchar *)map_ptr(buf, i, remainder), remainder); md5_result(&m, (uchar *)sum); break; case CSUM_MD4: case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: mdfour_begin(&m); for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) { } /* Prior to version 27 an incorrect MD4 checksum was computed * by failing to call mdfour_tail() for block sizes that * are multiples of 64. This is fixed by calling mdfour_update() * even when there are no more bytes. */ * are multiples of 64. This is fixed by calling mdfour_update() * even when there are no more bytes. */ remainder = (int32)(len - i); if (remainder > 0 || checksum_type != CSUM_MD4_BUSTED) mdfour_update(&m, (uchar *)map_ptr(buf, i, remainder), remainder); mdfour_result(&m, (uchar *)sum); rprintf(FERROR, "invalid checksum-choice for the --checksum option (%d)\n", checksum_type); exit_cleanup(RERR_UNSUPPORTED); } close(fd); unmap_file(buf); } Commit Message: CWE ID: CWE-354 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 int fallocate_chunk(struct inode *inode, loff_t offset, loff_t len, int mode) { struct gfs2_inode *ip = GFS2_I(inode); struct buffer_head *dibh; int error; u64 start = offset >> PAGE_CACHE_SHIFT; unsigned int start_offset = offset & ~PAGE_CACHE_MASK; u64 end = (offset + len - 1) >> PAGE_CACHE_SHIFT; pgoff_t curr; struct page *page; unsigned int end_offset = (offset + len) & ~PAGE_CACHE_MASK; unsigned int from, to; if (!end_offset) end_offset = PAGE_CACHE_SIZE; error = gfs2_meta_inode_buffer(ip, &dibh); if (unlikely(error)) goto out; gfs2_trans_add_bh(ip->i_gl, dibh, 1); if (gfs2_is_stuffed(ip)) { error = gfs2_unstuff_dinode(ip, NULL); if (unlikely(error)) goto out; } curr = start; offset = start << PAGE_CACHE_SHIFT; from = start_offset; to = PAGE_CACHE_SIZE; while (curr <= end) { page = grab_cache_page_write_begin(inode->i_mapping, curr, AOP_FLAG_NOFS); if (unlikely(!page)) { error = -ENOMEM; goto out; } if (curr == end) to = end_offset; error = write_empty_blocks(page, from, to, mode); if (!error && offset + to > inode->i_size && !(mode & FALLOC_FL_KEEP_SIZE)) { i_size_write(inode, offset + to); } unlock_page(page); page_cache_release(page); if (error) goto out; curr++; offset += PAGE_CACHE_SIZE; from = 0; } mark_inode_dirty(inode); brelse(dibh); out: return error; } Commit Message: GFS2: rewrite fallocate code to write blocks directly GFS2's fallocate code currently goes through the page cache. Since it's only writing to the end of the file or to holes in it, it doesn't need to, and it was causing issues on low memory environments. This patch pulls in some of Steve's block allocation work, and uses it to simply allocate the blocks for the file, and zero them out at allocation time. It provides a slight performance increase, and it dramatically simplifies the code. Signed-off-by: Benjamin Marzinski <[email protected]> Signed-off-by: Steven Whitehouse <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: int size() const { return size_; } Commit Message: net: don't process truncated headers on HTTPS connections. This change causes us to not process any headers unless they are correctly terminated with a \r\n\r\n sequence. BUG=244260 Review URL: https://chromiumcodereview.appspot.com/15688012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@202927 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: OMX_ERRORTYPE omx_vdec::fill_this_buffer(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_BUFFERHEADERTYPE* buffer) { unsigned nPortIndex = 0; if (dynamic_buf_mode) { private_handle_t *handle = NULL; struct VideoDecoderOutputMetaData *meta; unsigned int nPortIndex = 0; if (!buffer || !buffer->pBuffer) { DEBUG_PRINT_ERROR("%s: invalid params: %p", __FUNCTION__, buffer); return OMX_ErrorBadParameter; } meta = (struct VideoDecoderOutputMetaData *)buffer->pBuffer; handle = (private_handle_t *)meta->pHandle; DEBUG_PRINT_LOW("FTB: metabuf: %p buftype: %d bufhndl: %p ", meta, meta->eType, meta->pHandle); if (!handle) { DEBUG_PRINT_ERROR("FTB: Error: IL client passed an invalid buf handle - %p", handle); return OMX_ErrorBadParameter; } nPortIndex = buffer-((OMX_BUFFERHEADERTYPE *)client_buffers.get_il_buf_hdr()); drv_ctx.ptr_outputbuffer[nPortIndex].pmem_fd = handle->fd; drv_ctx.ptr_outputbuffer[nPortIndex].bufferaddr = (OMX_U8*) buffer; native_buffer[nPortIndex].privatehandle = handle; native_buffer[nPortIndex].nativehandle = handle; buffer->nFilledLen = 0; buffer->nAllocLen = handle->size; } if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("FTB in Invalid State"); return OMX_ErrorInvalidState; } if (!m_out_bEnabled) { DEBUG_PRINT_ERROR("ERROR:FTB incorrect state operation, output port is disabled."); return OMX_ErrorIncorrectStateOperation; } nPortIndex = buffer - client_buffers.get_il_buf_hdr(); if (buffer == NULL || (nPortIndex >= drv_ctx.op_buf.actualcount)) { DEBUG_PRINT_ERROR("FTB: ERROR: invalid buffer index, nPortIndex %u bufCount %u", nPortIndex, drv_ctx.op_buf.actualcount); return OMX_ErrorBadParameter; } if (buffer->nOutputPortIndex != OMX_CORE_OUTPUT_PORT_INDEX) { DEBUG_PRINT_ERROR("ERROR:FTB invalid port in header %u", (unsigned int)buffer->nOutputPortIndex); return OMX_ErrorBadPortIndex; } DEBUG_PRINT_LOW("[FTB] bufhdr = %p, bufhdr->pBuffer = %p", buffer, buffer->pBuffer); post_event((unsigned long) hComp, (unsigned long)buffer, m_fill_output_msg); return OMX_ErrorNone; } Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states (per the spec) ETB/FTB should not be handled in states other than Executing, Paused and Idle. This avoids accessing invalid buffers. Also add a lock to protect the private-buffers from being deleted while accessing from another thread. Bug: 27890802 Security Vulnerability - Heap Use-After-Free and Possible LPE in MediaServer (libOmxVdec problem #6) CRs-Fixed: 1008882 Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e CWE ID: 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: SendTabToSelfInfoBarDelegate::Create(const SendTabToSelfEntry* entry) { return base::WrapUnique(new SendTabToSelfInfoBarDelegate(entry)); } Commit Message: [SendTabToSelf] Added logic to display an infobar for the feature. This CL is one of many to come. It covers: * Creation of the infobar from the SendTabToSelfInfoBarController * Plumbed the call to create the infobar to the native code. * Open the link when user taps on the link In follow-up CLs, the following will be done: * Instantiate the InfobarController in the ChromeActivity * Listen for Model changes in the Controller Bug: 949233,963193 Change-Id: I5df1359debb5f0f35c32c2df3b691bf9129cdeb8 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1604406 Reviewed-by: Tommy Nyquist <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: Mikel Astiz <[email protected]> Reviewed-by: sebsg <[email protected]> Reviewed-by: Jeffrey Cohen <[email protected]> Reviewed-by: Matthew Jones <[email protected]> Commit-Queue: Tanya Gupta <[email protected]> Cr-Commit-Position: refs/heads/master@{#660854} CWE ID: CWE-190 Target: 1 Example 2: Code: static int dcbnl_setfeatcfg(struct net_device *netdev, struct nlmsghdr *nlh, u32 seq, struct nlattr **tb, struct sk_buff *skb) { struct nlattr *data[DCB_FEATCFG_ATTR_MAX + 1]; int ret, i; u8 value; if (!netdev->dcbnl_ops->setfeatcfg) return -ENOTSUPP; if (!tb[DCB_ATTR_FEATCFG]) return -EINVAL; ret = nla_parse_nested(data, DCB_FEATCFG_ATTR_MAX, tb[DCB_ATTR_FEATCFG], dcbnl_featcfg_nest); if (ret) goto err; for (i = DCB_FEATCFG_ATTR_ALL+1; i <= DCB_FEATCFG_ATTR_MAX; i++) { if (data[i] == NULL) continue; value = nla_get_u8(data[i]); ret = netdev->dcbnl_ops->setfeatcfg(netdev, i, value); if (ret) goto err; } err: ret = nla_put_u8(skb, DCB_ATTR_FEATCFG, ret); return ret; } Commit Message: dcbnl: fix various netlink info leaks The dcb netlink interface leaks stack memory in various places: * perm_addr[] buffer is only filled at max with 12 of the 32 bytes but copied completely, * no in-kernel driver fills all fields of an IEEE 802.1Qaz subcommand, so we're leaking up to 58 bytes for ieee_ets structs, up to 136 bytes for ieee_pfc structs, etc., * the same is true for CEE -- no in-kernel driver fills the whole struct, Prevent all of the above stack info leaks by properly initializing the buffers/structures involved. Signed-off-by: Mathias Krause <[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: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 2) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); int nonCallback(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); if (exec->argumentCount() <= 1 || !exec->argument(1).isFunction()) { setDOMException(exec, TYPE_MISMATCH_ERR); return JSValue::encode(jsUndefined()); } RefPtr<TestCallback> callback = JSTestCallback::create(asObject(exec->argument(1)), castedThis->globalObject()); impl->methodWithNonCallbackArgAndCallbackArg(nonCallback, callback); return JSValue::encode(jsUndefined()); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 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 void ctrycatchfinally(JF, js_Ast *trystm, js_Ast *catchvar, js_Ast *catchstm, js_Ast *finallystm) { int L1, L2, L3; L1 = emitjump(J, F, OP_TRY); { /* if we get here, we have caught an exception in the try block */ L2 = emitjump(J, F, OP_TRY); { /* if we get here, we have caught an exception in the catch block */ cstm(J, F, finallystm); /* inline finally block */ emit(J, F, OP_THROW); /* rethrow exception */ } label(J, F, L2); if (F->strict) { checkfutureword(J, F, catchvar); if (!strcmp(catchvar->string, "arguments")) jsC_error(J, catchvar, "redefining 'arguments' is not allowed in strict mode"); if (!strcmp(catchvar->string, "eval")) jsC_error(J, catchvar, "redefining 'eval' is not allowed in strict mode"); } emitline(J, F, catchvar); emitstring(J, F, OP_CATCH, catchvar->string); cstm(J, F, catchstm); emit(J, F, OP_ENDCATCH); L3 = emitjump(J, F, OP_JUMP); /* skip past the try block to the finally block */ } label(J, F, L1); cstm(J, F, trystm); emit(J, F, OP_ENDTRY); label(J, F, L3); cstm(J, F, finallystm); } Commit Message: Bug 700947: Add missing ENDTRY opcode in try/catch/finally byte code. In one of the code branches in handling exceptions in the catch block we forgot to call the ENDTRY opcode to pop the inner hidden try. This leads to an unbalanced exception stack which can cause a crash due to us jumping to a stack frame that has already been exited. CWE ID: CWE-119 Target: 1 Example 2: Code: static bool GetFilePathWithHostAndPortReplacement( const std::string& original_file_path, const net::HostPortPair& host_port_pair, std::string* replacement_path) { std::vector<net::TestServer::StringPair> replacement_text; replacement_text.push_back( make_pair("REPLACE_WITH_HOST_AND_PORT", host_port_pair.ToString())); return net::TestServer::GetFilePathWithReplacements( original_file_path, replacement_text, replacement_path); } Commit Message: Disable SSLUITest.TestCNInvalidStickiness, flakily hits an assertion. TBR=rsleevi BUG=68448, 49377 TEST=browser_tests Review URL: http://codereview.chromium.org/6178005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70876 0039d316-1c4b-4281-b951-d872f2087c98 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: const Cluster* BlockEntry::GetCluster() const { return m_pCluster; } 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: virtual void ResetModel() { last_pts_ = 0; bits_in_buffer_model_ = cfg_.rc_target_bitrate * cfg_.rc_buf_initial_sz; frame_number_ = 0; tot_frame_number_ = 0; first_drop_ = 0; num_drops_ = 0; for (int i = 0; i < 3; ++i) { bits_total_[i] = 0; } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: static void reply_spnego_negotiate(struct smb_request *req, uint16 vuid, DATA_BLOB blob1, AUTH_NTLMSSP_STATE **auth_ntlmssp_state) { DATA_BLOB secblob; DATA_BLOB chal; char *kerb_mech = NULL; NTSTATUS status; struct smbd_server_connection *sconn = smbd_server_conn; status = parse_spnego_mechanisms(blob1, &secblob, &kerb_mech); if (!NT_STATUS_IS_OK(status)) { /* Kill the intermediate vuid */ invalidate_vuid(sconn, vuid); reply_nterror(req, nt_status_squash(status)); return; } DEBUG(3,("reply_spnego_negotiate: Got secblob of size %lu\n", (unsigned long)secblob.length)); #ifdef HAVE_KRB5 if (kerb_mech && ((lp_security()==SEC_ADS) || USE_KERBEROS_KEYTAB) ) { bool destroy_vuid = True; reply_spnego_kerberos(req, &secblob, kerb_mech, vuid, &destroy_vuid); data_blob_free(&secblob); if (destroy_vuid) { /* Kill the intermediate vuid */ invalidate_vuid(sconn, vuid); } SAFE_FREE(kerb_mech); return; } #endif if (*auth_ntlmssp_state) { auth_ntlmssp_end(auth_ntlmssp_state); } if (kerb_mech) { data_blob_free(&secblob); /* The mechtoken is a krb5 ticket, but * we need to fall back to NTLM. */ reply_spnego_downgrade_to_ntlmssp(req, vuid); SAFE_FREE(kerb_mech); return; } status = auth_ntlmssp_start(auth_ntlmssp_state); if (!NT_STATUS_IS_OK(status)) { /* Kill the intermediate vuid */ invalidate_vuid(sconn, vuid); reply_nterror(req, nt_status_squash(status)); return; } status = auth_ntlmssp_update(*auth_ntlmssp_state, secblob, &chal); data_blob_free(&secblob); reply_spnego_ntlmssp(req, vuid, auth_ntlmssp_state, &chal, status, OID_NTLMSSP, true); data_blob_free(&chal); /* already replied */ return; } 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: int vcc_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct atm_vcc *vcc; int len; if (get_user(len, optlen)) return -EFAULT; if (__SO_LEVEL_MATCH(optname, level) && len != __SO_SIZE(optname)) return -EINVAL; vcc = ATM_SD(sock); switch (optname) { case SO_ATMQOS: if (!test_bit(ATM_VF_HASQOS, &vcc->flags)) return -EINVAL; return copy_to_user(optval, &vcc->qos, sizeof(vcc->qos)) ? -EFAULT : 0; case SO_SETCLP: return put_user(vcc->atm_options & ATM_ATMOPT_CLP ? 1 : 0, (unsigned long __user *)optval) ? -EFAULT : 0; case SO_ATMPVC: { struct sockaddr_atmpvc pvc; if (!vcc->dev || !test_bit(ATM_VF_ADDR, &vcc->flags)) return -ENOTCONN; pvc.sap_family = AF_ATMPVC; pvc.sap_addr.itf = vcc->dev->number; pvc.sap_addr.vpi = vcc->vpi; pvc.sap_addr.vci = vcc->vci; return copy_to_user(optval, &pvc, sizeof(pvc)) ? -EFAULT : 0; } default: if (level == SOL_SOCKET) return -EINVAL; break; } if (!vcc->dev || !vcc->dev->ops->getsockopt) return -EINVAL; return vcc->dev->ops->getsockopt(vcc, level, optname, optval, len); } Commit Message: atm: fix info leak in getsockopt(SO_ATMPVC) The ATM code fails to initialize the two padding bytes of struct sockaddr_atmpvc inserted for alignment. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> 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 ssize_t o2nm_node_local_store(struct config_item *item, const char *page, size_t count) { struct o2nm_node *node = to_o2nm_node(item); struct o2nm_cluster *cluster = to_o2nm_cluster_from_node(node); unsigned long tmp; char *p = (char *)page; ssize_t ret; tmp = simple_strtoul(p, &p, 0); if (!p || (*p && (*p != '\n'))) return -EINVAL; tmp = !!tmp; /* boolean of whether this node wants to be local */ /* setting local turns on networking rx for now so we require having * set everything else first */ if (!test_bit(O2NM_NODE_ATTR_ADDRESS, &node->nd_set_attributes) || !test_bit(O2NM_NODE_ATTR_NUM, &node->nd_set_attributes) || !test_bit(O2NM_NODE_ATTR_PORT, &node->nd_set_attributes)) return -EINVAL; /* XXX */ /* the only failure case is trying to set a new local node * when a different one is already set */ if (tmp && tmp == cluster->cl_has_local && cluster->cl_local_node != node->nd_num) return -EBUSY; /* bring up the rx thread if we're setting the new local node. */ if (tmp && !cluster->cl_has_local) { ret = o2net_start_listening(node); if (ret) return ret; } if (!tmp && cluster->cl_has_local && cluster->cl_local_node == node->nd_num) { o2net_stop_listening(node); cluster->cl_local_node = O2NM_INVALID_NODE_NUM; } node->nd_local = tmp; if (node->nd_local) { cluster->cl_has_local = tmp; cluster->cl_local_node = node->nd_num; } return count; } Commit Message: ocfs2: subsystem.su_mutex is required while accessing the item->ci_parent The subsystem.su_mutex is required while accessing the item->ci_parent, otherwise, NULL pointer dereference to the item->ci_parent will be triggered in the following situation: add node delete node sys_write vfs_write configfs_write_file o2nm_node_store o2nm_node_local_write do_rmdir vfs_rmdir configfs_rmdir mutex_lock(&subsys->su_mutex); unlink_obj item->ci_group = NULL; item->ci_parent = NULL; to_o2nm_cluster_from_node node->nd_item.ci_parent->ci_parent BUG since of NULL pointer dereference to nd_item.ci_parent Moreover, the o2nm_cluster also should be protected by the subsystem.su_mutex. [[email protected]: v2] Link: http://lkml.kernel.org/r/[email protected] Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Alex Chen <[email protected]> Reviewed-by: Jun Piao <[email protected]> Reviewed-by: Joseph Qi <[email protected]> Cc: Mark Fasheh <[email protected]> Cc: Joel Becker <[email protected]> Cc: Junxiao Bi <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-476 Target: 1 Example 2: Code: void prefetch_motion(VP8Context *s, VP8Macroblock *mb, int mb_x, int mb_y, int mb_xy, int ref) { /* Don't prefetch refs that haven't been used very often this frame. */ if (s->ref_count[ref - 1] > (mb_xy >> 5)) { int x_off = mb_x << 4, y_off = mb_y << 4; int mx = (mb->mv.x >> 2) + x_off + 8; int my = (mb->mv.y >> 2) + y_off; uint8_t **src = s->framep[ref]->tf.f->data; int off = mx + (my + (mb_x & 3) * 4) * s->linesize + 64; /* For threading, a ff_thread_await_progress here might be useful, but * it actually slows down the decoder. Since a bad prefetch doesn't * generate bad decoder output, we don't run it here. */ s->vdsp.prefetch(src[0] + off, s->linesize, 4); off = (mx >> 1) + ((my >> 1) + (mb_x & 7)) * s->uvlinesize + 64; s->vdsp.prefetch(src[1] + off, src[2] - src[1], 2); } } Commit Message: avcodec/webp: Always set pix_fmt Fixes: out of array access Fixes: 1434/clusterfuzz-testcase-minimized-6314998085189632 Fixes: 1435/clusterfuzz-testcase-minimized-6483783723253760 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Reviewed-by: "Ronald S. Bultje" <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> 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 RenderWidgetHostImpl::OnAutoscrollStart(const gfx::PointF& position) { GetView()->OnAutoscrollStart(); WebGestureEvent scroll_begin = SyntheticWebGestureEventBuilder::Build( WebInputEvent::kGestureScrollBegin, blink::kWebGestureDeviceSyntheticAutoscroll); scroll_begin.SetPositionInWidget(position); ForwardGestureEventWithLatencyInfo( scroll_begin, ui::LatencyInfo(ui::SourceEventType::OTHER)); OnAutoscrollFling(gfx::Vector2dF()); } Commit Message: Start rendering timer after first navigation Currently the new content rendering timer in the browser process, which clears an old page's contents 4 seconds after a navigation if the new page doesn't draw in that time, is not set on the first navigation for a top-level frame. This is problematic because content can exist before the first navigation, for instance if it was created by a javascript: URL. This CL removes the code that skips the timer activation on the first navigation. Bug: 844881 Change-Id: I19b3ad1ff62c69ded3a5f7b1c0afde191aaf4584 Reviewed-on: https://chromium-review.googlesource.com/1188589 Reviewed-by: Fady Samuel <[email protected]> Reviewed-by: ccameron <[email protected]> Commit-Queue: Ken Buchanan <[email protected]> Cr-Commit-Position: refs/heads/master@{#586913} CWE ID: CWE-20 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: ResourceHostMsg_Request CreateXHRRequestWithOrigin(const char* origin) { ResourceHostMsg_Request request; request.method = "GET"; request.url = GURL("http://bar.com/simple_page.html"); request.first_party_for_cookies = GURL(origin); request.referrer_policy = blink::WebReferrerPolicyDefault; request.headers = base::StringPrintf("Origin: %s\r\n", origin); request.load_flags = 0; request.origin_pid = 0; request.resource_type = RESOURCE_TYPE_XHR; request.request_context = 0; request.appcache_host_id = kAppCacheNoHostId; request.download_to_file = false; request.should_reset_appcache = false; request.is_main_frame = true; request.parent_is_main_frame = false; request.parent_render_frame_id = -1; request.transition_type = ui::PAGE_TRANSITION_LINK; request.allow_download = true; return request; } Commit Message: Block a compromised renderer from reusing request ids. BUG=578882 Review URL: https://codereview.chromium.org/1608573002 Cr-Commit-Position: refs/heads/master@{#372547} CWE ID: CWE-362 Target: 1 Example 2: Code: void ComputeWebKitPrintParamsInDesiredDpi( const PrintMsg_Print_Params& print_params, WebKit::WebPrintParams* webkit_print_params) { int dpi = GetDPI(&print_params); webkit_print_params->printerDPI = dpi; webkit_print_params->printScalingOption = print_params.print_scaling_option; using printing::ConvertUnit; webkit_print_params->printContentArea.width = ConvertUnit(print_params.content_size.width(), dpi, print_params.desired_dpi); webkit_print_params->printContentArea.height = ConvertUnit(print_params.content_size.height(), dpi, print_params.desired_dpi); webkit_print_params->printableArea.x = ConvertUnit(print_params.printable_area.x(), dpi, print_params.desired_dpi); webkit_print_params->printableArea.y = ConvertUnit(print_params.printable_area.y(), dpi, print_params.desired_dpi); webkit_print_params->printableArea.width = ConvertUnit(print_params.printable_area.width(), dpi, print_params.desired_dpi); webkit_print_params->printableArea.height = ConvertUnit(print_params.printable_area.height(), dpi, print_params.desired_dpi); webkit_print_params->paperSize.width = ConvertUnit(print_params.page_size.width(), dpi, print_params.desired_dpi); webkit_print_params->paperSize.height = ConvertUnit(print_params.page_size.height(), dpi, print_params.desired_dpi); } Commit Message: Guard against the same PrintWebViewHelper being re-entered. BUG=159165 Review URL: https://chromiumcodereview.appspot.com/11367076 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@165821 0039d316-1c4b-4281-b951-d872f2087c98 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: void HTMLFormElement::ScheduleFormSubmission(FormSubmission* submission) { DCHECK(submission->Method() == FormSubmission::kPostMethod || submission->Method() == FormSubmission::kGetMethod); DCHECK(submission->Data()); DCHECK(submission->Form()); if (submission->Action().IsEmpty()) return; if (GetDocument().IsSandboxed(kSandboxForms)) { GetDocument().AddConsoleMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Blocked form submission to '" + submission->Action().ElidedString() + "' because the form's frame is sandboxed and the 'allow-forms' " "permission is not set.")); return; } if (!GetDocument().GetContentSecurityPolicy()->AllowFormAction( submission->Action())) { return; } if (submission->Action().ProtocolIsJavaScript()) { GetDocument() .GetFrame() ->GetScriptController() .ExecuteScriptIfJavaScriptURL(submission->Action(), this); return; } Frame* target_frame = GetDocument().GetFrame()->FindFrameForNavigation( submission->Target(), *GetDocument().GetFrame(), submission->RequestURL()); if (!target_frame) { target_frame = GetDocument().GetFrame(); } else { submission->ClearTarget(); } if (!target_frame->GetPage()) return; UseCounter::Count(GetDocument(), WebFeature::kFormsSubmitted); if (MixedContentChecker::IsMixedFormAction(GetDocument().GetFrame(), submission->Action())) { UseCounter::Count(GetDocument().GetFrame(), WebFeature::kMixedContentFormsSubmitted); } if (target_frame->IsLocalFrame()) { ToLocalFrame(target_frame) ->GetNavigationScheduler() .ScheduleFormSubmission(&GetDocument(), submission); } else { FrameLoadRequest frame_load_request = submission->CreateFrameLoadRequest(&GetDocument()); ToRemoteFrame(target_frame)->Navigate(frame_load_request); } } Commit Message: Move user activation check to RemoteFrame::Navigate's callers. Currently RemoteFrame::Navigate is the user of Frame::HasTransientUserActivation that passes a RemoteFrame*, and it seems wrong because the user activation (user gesture) needed by the navigation should belong to the LocalFrame that initiated the navigation. Follow-up CLs after this one will update UserActivation code in Frame to take a LocalFrame* instead of a Frame*, and get rid of redundant IPCs. Bug: 811414 Change-Id: I771c1694043edb54374a44213d16715d9c7da704 Reviewed-on: https://chromium-review.googlesource.com/914736 Commit-Queue: Mustaq Ahmed <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#536728} 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: void ScreenOrientationDispatcherHost::OnLockRequest( RenderFrameHost* render_frame_host, blink::WebScreenOrientationLockType orientation, int request_id) { if (current_lock_) { NotifyLockError(current_lock_->request_id, blink::WebLockOrientationErrorCanceled); } current_lock_ = new LockInformation(request_id, render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID()); if (!provider_) { NotifyLockError(request_id, blink::WebLockOrientationErrorNotAvailable); return; } provider_->LockOrientation(request_id, orientation); } Commit Message: Cleanups in ScreenOrientationDispatcherHost. BUG=None Review URL: https://codereview.chromium.org/408213003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@284786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 Target: 1 Example 2: Code: file_free(struct xar_file *file) { struct xattr *xattr; archive_string_free(&(file->pathname)); archive_string_free(&(file->symlink)); archive_string_free(&(file->uname)); archive_string_free(&(file->gname)); archive_string_free(&(file->hardlink)); xattr = file->xattr_list; while (xattr != NULL) { struct xattr *next; next = xattr->next; xattr_free(xattr); xattr = next; } free(file); } Commit Message: Do something sensible for empty strings to make fuzzers happy. CWE ID: CWE-125 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 OxideQQuickWebViewPrivate::LoadingChanged() { Q_Q(OxideQQuickWebView); emit q->loadingStateChanged(); } Commit Message: CWE ID: CWE-20 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: GpuChannelHost::GpuChannelHost( GpuChannelHostFactory* factory, int gpu_process_id, int client_id) : factory_(factory), gpu_process_id_(gpu_process_id), client_id_(client_id), state_(kUnconnected) { } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: static void print_stats(BIO *bio, SSL_CTX *ssl_ctx) { BIO_printf(bio, "%4ld items in the session cache\n", SSL_CTX_sess_number(ssl_ctx)); BIO_printf(bio, "%4ld client connects (SSL_connect())\n", SSL_CTX_sess_connect(ssl_ctx)); BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n", SSL_CTX_sess_connect_renegotiate(ssl_ctx)); BIO_printf(bio, "%4ld client connects that finished\n", SSL_CTX_sess_connect_good(ssl_ctx)); BIO_printf(bio, "%4ld server accepts (SSL_accept())\n", SSL_CTX_sess_accept(ssl_ctx)); BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n", SSL_CTX_sess_accept_renegotiate(ssl_ctx)); BIO_printf(bio, "%4ld server accepts that finished\n", SSL_CTX_sess_accept_good(ssl_ctx)); BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx)); BIO_printf(bio, "%4ld session cache misses\n", SSL_CTX_sess_misses(ssl_ctx)); BIO_printf(bio, "%4ld session cache timeouts\n", SSL_CTX_sess_timeouts(ssl_ctx)); BIO_printf(bio, "%4ld callback cache hits\n", SSL_CTX_sess_cb_hits(ssl_ctx)); BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n", SSL_CTX_sess_cache_full(ssl_ctx), SSL_CTX_sess_get_cache_size(ssl_ctx)); } Commit Message: 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: static int readContigStripsIntoBuffer (TIFF* in, uint8* buf) { uint8* bufp = buf; int32 bytes_read = 0; uint16 strip, nstrips = TIFFNumberOfStrips(in); uint32 stripsize = TIFFStripSize(in); uint32 rows = 0; uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); tsize_t scanline_size = TIFFScanlineSize(in); if (scanline_size == 0) { TIFFError("", "TIFF scanline size is zero!"); return 0; } for (strip = 0; strip < nstrips; strip++) { bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1); rows = bytes_read / scanline_size; if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize)) TIFFError("", "Strip %d: read %lu bytes, strip size %lu", (int)strip + 1, (unsigned long) bytes_read, (unsigned long)stripsize); if (bytes_read < 0 && !ignore) { TIFFError("", "Error reading strip %lu after %lu rows", (unsigned long) strip, (unsigned long)rows); return 0; } bufp += bytes_read; } return 1; } /* end readContigStripsIntoBuffer */ Commit Message: * tools/tiffcp.c: fix read of undefined variable in case of missing required tags. Found on test case of MSVR 35100. * tools/tiffcrop.c: fix read of undefined buffer in readContigStripsIntoBuffer() due to uint16 overflow. Probably not a security issue but I can be wrong. Reported as MSVR 35100 by Axel Souchet from the MSRC Vulnerabilities & Mitigations team. 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: void HandleCompleteLogin(const base::ListValue* args) { #if defined(OS_CHROMEOS) oauth2_delegate_.reset(new InlineLoginUIOAuth2Delegate(web_ui())); oauth2_token_fetcher_.reset(new chromeos::OAuth2TokenFetcher( oauth2_delegate_.get(), profile_->GetRequestContext())); oauth2_token_fetcher_->StartExchangeFromCookies(); #elif !defined(OS_ANDROID) const base::DictionaryValue* dict = NULL; string16 email; string16 password; if (!args->GetDictionary(0, &dict) || !dict || !dict->GetString("email", &email) || !dict->GetString("password", &password)) { NOTREACHED(); return; } new OneClickSigninSyncStarter( profile_, NULL, "0" /* session_index 0 for the default user */, UTF16ToASCII(email), UTF16ToASCII(password), OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS, true /* force_same_tab_navigation */, OneClickSigninSyncStarter::NO_CONFIRMATION); web_ui()->CallJavascriptFunction("inline.login.closeDialog"); #endif } Commit Message: Display confirmation dialog for untrusted signins BUG=252062 Review URL: https://chromiumcodereview.appspot.com/17482002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200 Target: 1 Example 2: Code: static noinline int relink_extent_backref(struct btrfs_path *path, struct sa_defrag_extent_backref *prev, struct sa_defrag_extent_backref *backref) { struct btrfs_file_extent_item *extent; struct btrfs_file_extent_item *item; struct btrfs_ordered_extent *ordered; struct btrfs_trans_handle *trans; struct btrfs_fs_info *fs_info; struct btrfs_root *root; struct btrfs_key key; struct extent_buffer *leaf; struct old_sa_defrag_extent *old = backref->old; struct new_sa_defrag_extent *new = old->new; struct inode *src_inode = new->inode; struct inode *inode; struct extent_state *cached = NULL; int ret = 0; u64 start; u64 len; u64 lock_start; u64 lock_end; bool merge = false; int index; if (prev && prev->root_id == backref->root_id && prev->inum == backref->inum && prev->file_pos + prev->num_bytes == backref->file_pos) merge = true; /* step 1: get root */ key.objectid = backref->root_id; key.type = BTRFS_ROOT_ITEM_KEY; key.offset = (u64)-1; fs_info = BTRFS_I(src_inode)->root->fs_info; index = srcu_read_lock(&fs_info->subvol_srcu); root = btrfs_read_fs_root_no_name(fs_info, &key); if (IS_ERR(root)) { srcu_read_unlock(&fs_info->subvol_srcu, index); if (PTR_ERR(root) == -ENOENT) return 0; return PTR_ERR(root); } if (btrfs_root_readonly(root)) { srcu_read_unlock(&fs_info->subvol_srcu, index); return 0; } /* step 2: get inode */ key.objectid = backref->inum; key.type = BTRFS_INODE_ITEM_KEY; key.offset = 0; inode = btrfs_iget(fs_info->sb, &key, root, NULL); if (IS_ERR(inode)) { srcu_read_unlock(&fs_info->subvol_srcu, index); return 0; } srcu_read_unlock(&fs_info->subvol_srcu, index); /* step 3: relink backref */ lock_start = backref->file_pos; lock_end = backref->file_pos + backref->num_bytes - 1; lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end, 0, &cached); ordered = btrfs_lookup_first_ordered_extent(inode, lock_end); if (ordered) { btrfs_put_ordered_extent(ordered); goto out_unlock; } trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_unlock; } key.objectid = backref->inum; key.type = BTRFS_EXTENT_DATA_KEY; key.offset = backref->file_pos; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) { goto out_free_path; } else if (ret > 0) { ret = 0; goto out_free_path; } extent = btrfs_item_ptr(path->nodes[0], path->slots[0], struct btrfs_file_extent_item); if (btrfs_file_extent_generation(path->nodes[0], extent) != backref->generation) goto out_free_path; btrfs_release_path(path); start = backref->file_pos; if (backref->extent_offset < old->extent_offset + old->offset) start += old->extent_offset + old->offset - backref->extent_offset; len = min(backref->extent_offset + backref->num_bytes, old->extent_offset + old->offset + old->len); len -= max(backref->extent_offset, old->extent_offset + old->offset); ret = btrfs_drop_extents(trans, root, inode, start, start + len, 1); if (ret) goto out_free_path; again: key.objectid = btrfs_ino(inode); key.type = BTRFS_EXTENT_DATA_KEY; key.offset = start; path->leave_spinning = 1; if (merge) { struct btrfs_file_extent_item *fi; u64 extent_len; struct btrfs_key found_key; ret = btrfs_search_slot(trans, root, &key, path, 0, 1); if (ret < 0) goto out_free_path; path->slots[0]--; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); extent_len = btrfs_file_extent_num_bytes(leaf, fi); if (extent_len + found_key.offset == start && relink_is_mergable(leaf, fi, new)) { btrfs_set_file_extent_num_bytes(leaf, fi, extent_len + len); btrfs_mark_buffer_dirty(leaf); inode_add_bytes(inode, len); ret = 1; goto out_free_path; } else { merge = false; btrfs_release_path(path); goto again; } } ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent)); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_free_path; } leaf = path->nodes[0]; item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr); btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len); btrfs_set_file_extent_offset(leaf, item, start - new->file_pos); btrfs_set_file_extent_num_bytes(leaf, item, len); btrfs_set_file_extent_ram_bytes(leaf, item, new->len); btrfs_set_file_extent_generation(leaf, item, trans->transid); btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG); btrfs_set_file_extent_compression(leaf, item, new->compress_type); btrfs_set_file_extent_encryption(leaf, item, 0); btrfs_set_file_extent_other_encoding(leaf, item, 0); btrfs_mark_buffer_dirty(leaf); inode_add_bytes(inode, len); btrfs_release_path(path); ret = btrfs_inc_extent_ref(trans, root, new->bytenr, new->disk_len, 0, backref->root_id, backref->inum, new->file_pos, 0); /* start - extent_offset */ if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_free_path; } ret = 1; out_free_path: btrfs_release_path(path); path->leave_spinning = 0; btrfs_end_transaction(trans, root); out_unlock: unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end, &cached, GFP_NOFS); iput(inode); return ret; } Commit Message: Btrfs: fix truncation of compressed and inlined extents When truncating a file to a smaller size which consists of an inline extent that is compressed, we did not discard (or made unusable) the data between the new file size and the old file size, wasting metadata space and allowing for the truncated data to be leaked and the data corruption/loss mentioned below. We were also not correctly decrementing the number of bytes used by the inode, we were setting it to zero, giving a wrong report for callers of the stat(2) syscall. The fsck tool also reported an error about a mismatch between the nbytes of the file versus the real space used by the file. Now because we weren't discarding the truncated region of the file, it was possible for a caller of the clone ioctl to actually read the data that was truncated, allowing for a security breach without requiring root access to the system, using only standard filesystem operations. The scenario is the following: 1) User A creates a file which consists of an inline and compressed extent with a size of 2000 bytes - the file is not accessible to any other users (no read, write or execution permission for anyone else); 2) The user truncates the file to a size of 1000 bytes; 3) User A makes the file world readable; 4) User B creates a file consisting of an inline extent of 2000 bytes; 5) User B issues a clone operation from user A's file into its own file (using a length argument of 0, clone the whole range); 6) User B now gets to see the 1000 bytes that user A truncated from its file before it made its file world readbale. User B also lost the bytes in the range [1000, 2000[ bytes from its own file, but that might be ok if his/her intention was reading stale data from user A that was never supposed to be public. Note that this contrasts with the case where we truncate a file from 2000 bytes to 1000 bytes and then truncate it back from 1000 to 2000 bytes. In this case reading any byte from the range [1000, 2000[ will return a value of 0x00, instead of the original data. This problem exists since the clone ioctl was added and happens both with and without my recent data loss and file corruption fixes for the clone ioctl (patch "Btrfs: fix file corruption and data loss after cloning inline extents"). So fix this by truncating the compressed inline extents as we do for the non-compressed case, which involves decompressing, if the data isn't already in the page cache, compressing the truncated version of the extent, writing the compressed content into the inline extent and then truncate it. The following test case for fstests reproduces the problem. In order for the test to pass both this fix and my previous fix for the clone ioctl that forbids cloning a smaller inline extent into a larger one, which is titled "Btrfs: fix file corruption and data loss after cloning inline extents", are needed. Without that other fix the test fails in a different way that does not leak the truncated data, instead part of destination file gets replaced with zeroes (because the destination file has a larger inline extent than the source). seq=`basename $0` seqres=$RESULT_DIR/$seq echo "QA output created by $seq" tmp=/tmp/$$ status=1 # failure is the default! trap "_cleanup; exit \$status" 0 1 2 3 15 _cleanup() { rm -f $tmp.* } # get standard environment, filters and checks . ./common/rc . ./common/filter # real QA test starts here _need_to_be_root _supported_fs btrfs _supported_os Linux _require_scratch _require_cloner rm -f $seqres.full _scratch_mkfs >>$seqres.full 2>&1 _scratch_mount "-o compress" # Create our test files. File foo is going to be the source of a clone operation # and consists of a single inline extent with an uncompressed size of 512 bytes, # while file bar consists of a single inline extent with an uncompressed size of # 256 bytes. For our test's purpose, it's important that file bar has an inline # extent with a size smaller than foo's inline extent. $XFS_IO_PROG -f -c "pwrite -S 0xa1 0 128" \ -c "pwrite -S 0x2a 128 384" \ $SCRATCH_MNT/foo | _filter_xfs_io $XFS_IO_PROG -f -c "pwrite -S 0xbb 0 256" $SCRATCH_MNT/bar | _filter_xfs_io # Now durably persist all metadata and data. We do this to make sure that we get # on disk an inline extent with a size of 512 bytes for file foo. sync # Now truncate our file foo to a smaller size. Because it consists of a # compressed and inline extent, btrfs did not shrink the inline extent to the # new size (if the extent was not compressed, btrfs would shrink it to 128 # bytes), it only updates the inode's i_size to 128 bytes. $XFS_IO_PROG -c "truncate 128" $SCRATCH_MNT/foo # Now clone foo's inline extent into bar. # This clone operation should fail with errno EOPNOTSUPP because the source # file consists only of an inline extent and the file's size is smaller than # the inline extent of the destination (128 bytes < 256 bytes). However the # clone ioctl was not prepared to deal with a file that has a size smaller # than the size of its inline extent (something that happens only for compressed # inline extents), resulting in copying the full inline extent from the source # file into the destination file. # # Note that btrfs' clone operation for inline extents consists of removing the # inline extent from the destination inode and copy the inline extent from the # source inode into the destination inode, meaning that if the destination # inode's inline extent is larger (N bytes) than the source inode's inline # extent (M bytes), some bytes (N - M bytes) will be lost from the destination # file. Btrfs could copy the source inline extent's data into the destination's # inline extent so that we would not lose any data, but that's currently not # done due to the complexity that would be needed to deal with such cases # (specially when one or both extents are compressed), returning EOPNOTSUPP, as # it's normally not a very common case to clone very small files (only case # where we get inline extents) and copying inline extents does not save any # space (unlike for normal, non-inlined extents). $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/foo $SCRATCH_MNT/bar # Now because the above clone operation used to succeed, and due to foo's inline # extent not being shinked by the truncate operation, our file bar got the whole # inline extent copied from foo, making us lose the last 128 bytes from bar # which got replaced by the bytes in range [128, 256[ from foo before foo was # truncated - in other words, data loss from bar and being able to read old and # stale data from foo that should not be possible to read anymore through normal # filesystem operations. Contrast with the case where we truncate a file from a # size N to a smaller size M, truncate it back to size N and then read the range # [M, N[, we should always get the value 0x00 for all the bytes in that range. # We expected the clone operation to fail with errno EOPNOTSUPP and therefore # not modify our file's bar data/metadata. So its content should be 256 bytes # long with all bytes having the value 0xbb. # # Without the btrfs bug fix, the clone operation succeeded and resulted in # leaking truncated data from foo, the bytes that belonged to its range # [128, 256[, and losing data from bar in that same range. So reading the # file gave us the following content: # # 0000000 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 # * # 0000200 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a # * # 0000400 echo "File bar's content after the clone operation:" od -t x1 $SCRATCH_MNT/bar # Also because the foo's inline extent was not shrunk by the truncate # operation, btrfs' fsck, which is run by the fstests framework everytime a # test completes, failed reporting the following error: # # root 5 inode 257 errors 400, nbytes wrong status=0 exit Cc: [email protected] Signed-off-by: Filipe Manana <[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: bool DownloadItemImpl::IsTemporary() const { return is_temporary_; } Commit Message: Refactors to simplify rename pathway in DownloadFileManager. This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted due to CrOS failure) with the completion logic moved to after the auto-opening. The tests that test the auto-opening (for web store install) were waiting for download completion to check install, and hence were failing when completion was moved earlier. Doing this right would probably require another state (OPENED). BUG=123998 BUG-134930 [email protected] Review URL: https://chromiumcodereview.appspot.com/10701040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 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 CNB::DoIPHdrCSO(PVOID IpHeader, ULONG EthPayloadLength) const { ParaNdis_CheckSumVerifyFlat(IpHeader, EthPayloadLength, pcrIpChecksum | pcrFixIPChecksum, __FUNCTION__); } Commit Message: NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: static void ipip_destroy_tunnels(struct ipip_net *ipn, struct list_head *head) { int prio; for (prio = 1; prio < 4; prio++) { int h; for (h = 0; h < HASH_SIZE; h++) { struct ip_tunnel *t = ipn->tunnels[prio][h]; while (t != NULL) { unregister_netdevice_queue(t->dev, head); t = t->next; } } } } Commit Message: tunnels: fix netns vs proto registration ordering Same stuff as in ip_gre patch: receive hook can be called before netns setup is done, oopsing in net_generic(). Signed-off-by: Alexey Dobriyan <[email protected]> Signed-off-by: David S. Miller <[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: HRESULT CGaiaCredentialBase::ValidateOrCreateUser( const base::DictionaryValue* result, BSTR* domain, BSTR* username, BSTR* sid, BSTR* error_text) { LOGFN(INFO); DCHECK(domain); DCHECK(username); DCHECK(sid); DCHECK(error_text); DCHECK(sid); *error_text = nullptr; base::string16 local_password = GetDictString(result, kKeyPassword); wchar_t found_username[kWindowsUsernameBufferLength]; wchar_t found_domain[kWindowsDomainBufferLength]; wchar_t found_sid[kWindowsSidBufferLength]; base::string16 gaia_id; MakeUsernameForAccount( result, &gaia_id, found_username, base::size(found_username), found_domain, base::size(found_domain), found_sid, base::size(found_sid)); if (found_sid[0]) { HRESULT hr = ValidateExistingUser(found_username, found_domain, found_sid, error_text); if (FAILED(hr)) { LOGFN(ERROR) << "ValidateExistingUser hr=" << putHR(hr); return hr; } *username = ::SysAllocString(found_username); *domain = ::SysAllocString(found_domain); *sid = ::SysAllocString(found_sid); return S_OK; } DWORD cpus = 0; provider()->GetUsageScenario(&cpus); if (cpus == CPUS_UNLOCK_WORKSTATION) { *error_text = AllocErrorString(IDS_INVALID_UNLOCK_WORKSTATION_USER_BASE); return HRESULT_FROM_WIN32(ERROR_LOGON_TYPE_NOT_GRANTED); } else if (!CGaiaCredentialProvider::CanNewUsersBeCreated( static_cast<CREDENTIAL_PROVIDER_USAGE_SCENARIO>(cpus))) { *error_text = AllocErrorString(IDS_ADD_USER_DISALLOWED_BASE); return HRESULT_FROM_WIN32(ERROR_LOGON_TYPE_NOT_GRANTED); } base::string16 local_fullname = GetDictString(result, kKeyFullname); base::string16 comment(GetStringResource(IDS_USER_ACCOUNT_COMMENT_BASE)); HRESULT hr = CreateNewUser( OSUserManager::Get(), found_username, local_password.c_str(), local_fullname.c_str(), comment.c_str(), /*add_to_users_group=*/true, kMaxUsernameAttempts, username, sid); if (hr == HRESULT_FROM_WIN32(NERR_UserExists)) { LOGFN(ERROR) << "Could not find a new username based on desired username '" << found_domain << "\\" << found_username << "'. Maximum attempts reached."; *error_text = AllocErrorString(IDS_INTERNAL_ERROR_BASE); return hr; } *domain = ::SysAllocString(found_domain); return hr; } Commit Message: [GCPW] Disallow sign in of consumer accounts when mdm is enabled. Unless the registry key "mdm_aca" is explicitly set to 1, always fail sign in of consumer accounts when mdm enrollment is enabled. Consumer accounts are defined as accounts with gmail.com or googlemail.com domain. Bug: 944049 Change-Id: Icb822f3737d90931de16a8d3317616dd2b159edd Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1532903 Commit-Queue: Tien Mai <[email protected]> Reviewed-by: Roger Tawa <[email protected]> Cr-Commit-Position: refs/heads/master@{#646278} CWE ID: CWE-284 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: sctp_disposition_t sctp_sf_do_asconf(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sctp_chunk *asconf_ack = NULL; struct sctp_paramhdr *err_param = NULL; sctp_addiphdr_t *hdr; union sctp_addr_param *addr_param; __u32 serial; int length; if (!sctp_vtag_verify(chunk, asoc)) { sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG, SCTP_NULL()); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } /* ADD-IP: Section 4.1.1 * This chunk MUST be sent in an authenticated way by using * the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk * is received unauthenticated it MUST be silently discarded as * described in [I-D.ietf-tsvwg-sctp-auth]. */ if (!net->sctp.addip_noauth && !chunk->auth) return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands); /* Make sure that the ASCONF ADDIP chunk has a valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_addip_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); hdr = (sctp_addiphdr_t *)chunk->skb->data; serial = ntohl(hdr->serial); addr_param = (union sctp_addr_param *)hdr->params; length = ntohs(addr_param->p.length); if (length < sizeof(sctp_paramhdr_t)) return sctp_sf_violation_paramlen(net, ep, asoc, type, arg, (void *)addr_param, commands); /* Verify the ASCONF chunk before processing it. */ if (!sctp_verify_asconf(asoc, (sctp_paramhdr_t *)((void *)addr_param + length), (void *)chunk->chunk_end, &err_param)) return sctp_sf_violation_paramlen(net, ep, asoc, type, arg, (void *)err_param, commands); /* ADDIP 5.2 E1) Compare the value of the serial number to the value * the endpoint stored in a new association variable * 'Peer-Serial-Number'. */ if (serial == asoc->peer.addip_serial + 1) { /* If this is the first instance of ASCONF in the packet, * we can clean our old ASCONF-ACKs. */ if (!chunk->has_asconf) sctp_assoc_clean_asconf_ack_cache(asoc); /* ADDIP 5.2 E4) When the Sequence Number matches the next one * expected, process the ASCONF as described below and after * processing the ASCONF Chunk, append an ASCONF-ACK Chunk to * the response packet and cache a copy of it (in the event it * later needs to be retransmitted). * * Essentially, do V1-V5. */ asconf_ack = sctp_process_asconf((struct sctp_association *) asoc, chunk); if (!asconf_ack) return SCTP_DISPOSITION_NOMEM; } else if (serial < asoc->peer.addip_serial + 1) { /* ADDIP 5.2 E2) * If the value found in the Sequence Number is less than the * ('Peer- Sequence-Number' + 1), simply skip to the next * ASCONF, and include in the outbound response packet * any previously cached ASCONF-ACK response that was * sent and saved that matches the Sequence Number of the * ASCONF. Note: It is possible that no cached ASCONF-ACK * Chunk exists. This will occur when an older ASCONF * arrives out of order. In such a case, the receiver * should skip the ASCONF Chunk and not include ASCONF-ACK * Chunk for that chunk. */ asconf_ack = sctp_assoc_lookup_asconf_ack(asoc, hdr->serial); if (!asconf_ack) return SCTP_DISPOSITION_DISCARD; /* Reset the transport so that we select the correct one * this time around. This is to make sure that we don't * accidentally use a stale transport that's been removed. */ asconf_ack->transport = NULL; } else { /* ADDIP 5.2 E5) Otherwise, the ASCONF Chunk is discarded since * it must be either a stale packet or from an attacker. */ return SCTP_DISPOSITION_DISCARD; } /* ADDIP 5.2 E6) The destination address of the SCTP packet * containing the ASCONF-ACK Chunks MUST be the source address of * the SCTP packet that held the ASCONF Chunks. * * To do this properly, we'll set the destination address of the chunk * and at the transmit time, will try look up the transport to use. * Since ASCONFs may be bundled, the correct transport may not be * created until we process the entire packet, thus this workaround. */ asconf_ack->dest = chunk->source; sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(asconf_ack)); if (asoc->new_transport) { sctp_sf_heartbeat(ep, asoc, type, asoc->new_transport, commands); ((struct sctp_association *)asoc)->new_transport = NULL; } return SCTP_DISPOSITION_CONSUME; } Commit Message: net: sctp: fix skb_over_panic when receiving malformed ASCONF chunks Commit 6f4c618ddb0 ("SCTP : Add paramters validity check for ASCONF chunk") added basic verification of ASCONF chunks, however, it is still possible to remotely crash a server by sending a special crafted ASCONF chunk, even up to pre 2.6.12 kernels: skb_over_panic: text:ffffffffa01ea1c3 len:31056 put:30768 head:ffff88011bd81800 data:ffff88011bd81800 tail:0x7950 end:0x440 dev:<NULL> ------------[ cut here ]------------ kernel BUG at net/core/skbuff.c:129! [...] Call Trace: <IRQ> [<ffffffff8144fb1c>] skb_put+0x5c/0x70 [<ffffffffa01ea1c3>] sctp_addto_chunk+0x63/0xd0 [sctp] [<ffffffffa01eadaf>] sctp_process_asconf+0x1af/0x540 [sctp] [<ffffffff8152d025>] ? _read_unlock_bh+0x15/0x20 [<ffffffffa01e0038>] sctp_sf_do_asconf+0x168/0x240 [sctp] [<ffffffffa01e3751>] sctp_do_sm+0x71/0x1210 [sctp] [<ffffffff8147645d>] ? fib_rules_lookup+0xad/0xf0 [<ffffffffa01e6b22>] ? sctp_cmp_addr_exact+0x32/0x40 [sctp] [<ffffffffa01e8393>] sctp_assoc_bh_rcv+0xd3/0x180 [sctp] [<ffffffffa01ee986>] sctp_inq_push+0x56/0x80 [sctp] [<ffffffffa01fcc42>] sctp_rcv+0x982/0xa10 [sctp] [<ffffffffa01d5123>] ? ipt_local_in_hook+0x23/0x28 [iptable_filter] [<ffffffff8148bdc9>] ? nf_iterate+0x69/0xb0 [<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0 [<ffffffff8148bf86>] ? nf_hook_slow+0x76/0x120 [<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0 [<ffffffff81496ded>] ip_local_deliver_finish+0xdd/0x2d0 [<ffffffff81497078>] ip_local_deliver+0x98/0xa0 [<ffffffff8149653d>] ip_rcv_finish+0x12d/0x440 [<ffffffff81496ac5>] ip_rcv+0x275/0x350 [<ffffffff8145c88b>] __netif_receive_skb+0x4ab/0x750 [<ffffffff81460588>] netif_receive_skb+0x58/0x60 This can be triggered e.g., through a simple scripted nmap connection scan injecting the chunk after the handshake, for example, ... -------------- INIT[ASCONF; ASCONF_ACK] -------------> <----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------ -------------------- COOKIE-ECHO --------------------> <-------------------- COOKIE-ACK --------------------- ------------------ ASCONF; UNKNOWN ------------------> ... where ASCONF chunk of length 280 contains 2 parameters ... 1) Add IP address parameter (param length: 16) 2) Add/del IP address parameter (param length: 255) ... followed by an UNKNOWN chunk of e.g. 4 bytes. Here, the Address Parameter in the ASCONF chunk is even missing, too. This is just an example and similarly-crafted ASCONF chunks could be used just as well. The ASCONF chunk passes through sctp_verify_asconf() as all parameters passed sanity checks, and after walking, we ended up successfully at the chunk end boundary, and thus may invoke sctp_process_asconf(). Parameter walking is done with WORD_ROUND() to take padding into account. In sctp_process_asconf()'s TLV processing, we may fail in sctp_process_asconf_param() e.g., due to removal of the IP address that is also the source address of the packet containing the ASCONF chunk, and thus we need to add all TLVs after the failure to our ASCONF response to remote via helper function sctp_add_asconf_response(), which basically invokes a sctp_addto_chunk() adding the error parameters to the given skb. When walking to the next parameter this time, we proceed with ... length = ntohs(asconf_param->param_hdr.length); asconf_param = (void *)asconf_param + length; ... instead of the WORD_ROUND()'ed length, thus resulting here in an off-by-one that leads to reading the follow-up garbage parameter length of 12336, and thus throwing an skb_over_panic for the reply when trying to sctp_addto_chunk() next time, which implicitly calls the skb_put() with that length. Fix it by using sctp_walk_params() [ which is also used in INIT parameter processing ] macro in the verification *and* in ASCONF processing: it will make sure we don't spill over, that we walk parameters WORD_ROUND()'ed. Moreover, we're being more defensive and guard against unknown parameter types and missized addresses. Joint work with Vlad Yasevich. Fixes: b896b82be4ae ("[SCTP] ADDIP: Support for processing incoming ASCONF_ACK chunks.") Signed-off-by: Daniel Borkmann <[email protected]> Signed-off-by: Vlad Yasevich <[email protected]> Acked-by: Neil Horman <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: ps_simple_scale( PSH_Hint_Table table, FT_Fixed scale, FT_Fixed delta, FT_Int dimension ) { PSH_Hint hint; FT_UInt count; for ( count = 0; count < table->max_hints; count++ ) { hint = table->hints + count; hint->cur_pos = FT_MulFix( hint->org_pos, scale ) + delta; hint->cur_len = FT_MulFix( hint->org_len, scale ); if ( ps_debug_hint_func ) ps_debug_hint_func( hint, dimension ); } } Commit Message: 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: static ut64 read_uleb128(ulebr *r, ut8 *end) { ut64 result = 0; int bit = 0; ut64 slice = 0; ut8 *p = r->p; do { if (p == end) { eprintf ("malformed uleb128"); break; } slice = *p & 0x7f; if (bit > 63) { eprintf ("uleb128 too big for uint64, bit=%d, result=0x%"PFMT64x, bit, result); } else { result |= (slice << bit); bit += 7; } } while (*p++ & 0x80); r->p = p; return result; } Commit Message: Fix null deref and uaf in mach0 parser CWE ID: CWE-416 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: ContentEncoding::GetCompressionByIndex(unsigned long idx) const { const ptrdiff_t count = compression_entries_end_ - compression_entries_; assert(count >= 0); if (idx >= static_cast<unsigned long>(count)) return NULL; return compression_entries_[idx]; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20 Target: 1 Example 2: Code: void RenderBlock::layoutBlock(bool) { ASSERT_NOT_REACHED(); clearNeedsLayout(); } Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1) Previously StyleDifference was an enum that proximately bigger values imply smaller values (e.g. StyleDifferenceLayout implies StyleDifferenceRepaint). This causes unnecessary repaints in some cases on layout change. Convert StyleDifference to a structure containing relatively independent flags. This change doesn't directly improve the result, but can make further repaint optimizations possible. Step 1 doesn't change any functionality. RenderStyle still generate the legacy StyleDifference enum when comparing styles and convert the result to the new StyleDifference. Implicit requirements are not handled during the conversion. Converted call sites to use the new StyleDifference according to the following conversion rules: - diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange() - diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly() - diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout() - diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout() - diff > StyleDifferenceRepaintLayer => diff.needsLayout() - diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly() - diff == StyleDifferenceLayout => diff.needsFullLayout() BUG=358460 TEST=All existing layout tests. [email protected], [email protected], [email protected] Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983 Review URL: https://codereview.chromium.org/236203020 git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: bool RenderWidgetHostImpl::IsInOverscrollGesture() const { return overscroll_controller_.get() && overscroll_controller_->overscroll_mode() != OVERSCROLL_NONE; } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
0